From doug at alum.mit.edu Sat Jun 16 15:26:45 2007 From: doug at alum.mit.edu (Douglas Alan) Date: Sat, 16 Jun 2007 15:26:45 -0400 Subject: Python's "only one way to do it" philosophy isn't good? References: <1181368143.874341.273140@r19g2000prf.googlegroups.com> <1181385768_30305@sp12lax.superfeed.net> <7OJci.4752$tb6.1638@newsread3.news.pas.earthlink.net> Message-ID: Dennis Lee Bieber writes: > Macros? Unfortunately to my world, macros are those things > found in C, high-powered assemblers, and pre-VBA Office. As such, > they do anything but keep a language small, and one encounters > multiple implementations of similar functionality -- each > implementation the pride of one person, and abhorred by the person > who now must edit the code. Comparing C macros to Lisp macros is like comparing a Sawzall to a scalpel. Regarding having enough rope to hang yourself, the same claim can be made about any language abstraction mechanism. E.g., classes are to data types as macros are to syntax. You can abuse classes and you can abuse macros. Both abuses will lead to abhorring by your collaborators. And either abstraction mechanism, when used properly, will result in more elegant, easier to read and maintain code. Both abstraction mechanisms also allow language feature exploration to occur outside of the privileged few who are allowed to commit changes into the code-base for the interpreter or compiler. I think that this is one of the things that Gerry Sussman might be getting at when he talks about how science works. (Or at least that's what I would be getting at if I were in his shoes.) In the Lisp community, for instance, there have been lots of language features that were implemented by people who were not part of the core language development clique, but that were later widely adopted. E.g., the Common Lisp OO system with mutimethods (CLOS), and the "loop" macro. These features didn't require any changes to the core language implementation, and so you can see that Lisp-style macros are also a huge modularity boon for language implementation. |>oug From showell30 at yahoo.com Fri Jun 1 13:16:09 2007 From: showell30 at yahoo.com (Steve Howell) Date: Fri, 1 Jun 2007 10:16:09 -0700 (PDT) Subject: subexpressions In-Reply-To: <1180699443.822567.256680@g4g2000hsf.googlegroups.com> Message-ID: <629685.88548.qm@web33514.mail.mud.yahoo.com> --- Paul Boddie wrote: > On 1 Jun, 12:55, Steve Howell > wrote: > > FWIW there's the possibility that even without a > > subexpression syntax, some Python implementations > > would detect the duplication of x*x and optimize > that > > for you. It would have to know that x*x had no > side > > effects, which I think is a safe assumption even > in a > > dynamic language like Python. > > On the basis of you believing that x is one of the > built-in numeric > types, yes, but how does the compiler know that? > Disclaimer up front--premature optimization is the root of all evil, etc. But to answer the question... The compiler doesn't know the types up front, but if you wanted to do this kind of optimization (and you believed that 95% of x*x cases would benefit from it, and you're willing to sacrifice performance for the 5% of folks that overload multiply), then the compiler could generate bytecode that set the stage for later conditional caching of the first execution of x*x. You'd then need the execution of the bytecodes at runtime (ceval.c or something called by it) to work in such a way that they only cache the result when side effects are not an issue. At runtime you can reliably detect whether something is still a virgin builtin, correct? To my disclaimer, you would only undertake such an optimization if multiplication were really, really expensive (which I don't think is even true for floats today), and even then you'd proceed cautiously. ____________________________________________________________________________________ Get your own web address. Have a HUGE year through Yahoo! Small Business. http://smallbusiness.yahoo.com/domains/?p=BESTDEAL From survivedsushi at yahoo.com Wed Jun 27 16:25:14 2007 From: survivedsushi at yahoo.com (Matthew Peter) Date: Wed, 27 Jun 2007 13:25:14 -0700 (PDT) Subject: Return name of caller function? In-Reply-To: <20070626155646.GA28204@slaniel-laptop.itasoftware.com> Message-ID: <197779.8091.qm@web35210.mail.mud.yahoo.com> --- Stephen R Laniel wrote: > On Mon, Jun 25, 2007 at 06:27:29PM -0700, Matthew Peter wrote: > > For example, how do I get this to work? > > > > def func(): > > print "This is", __?__ > > return __caller__ > > > > def echo(): > > print "This is ", __?__ > > return func() > > inspect is your friend: > http://docs.python.org/lib/inspect-stack.html > > -- > Stephen R. Laniel > steve at laniels.org > Cell: +(617) 308-5571 > http://laniels.org/ > PGP key: http://laniels.org/slaniel.key > -- > http://mail.python.org/mailman/listinfo/python-list > --- Stephen R Laniel wrote: > On Mon, Jun 25, 2007 at 06:27:29PM -0700, Matthew Peter wrote: > > For example, how do I get this to work? > > > > def func(): > > print "This is", __?__ > > return __caller__ > > > > def echo(): > > print "This is ", __?__ > > return func() > > inspect is your friend: > http://docs.python.org/lib/inspect-stack.html > > -- > Stephen R. Laniel > steve at laniels.org > Cell: +(617) 308-5571 > http://laniels.org/ > PGP key: http://laniels.org/slaniel.key > -- > http://mail.python.org/mailman/listinfo/python-list > Parsing the stack's tuple to get those attributes didn't feel reliable or pythonic. I am likely overlooking something. Is there a brief example you could show me in the context of using inspect to accomplish the goal I outlined above? The goal is using a function and not a class. Thanks! ____________________________________________________________________________________ Yahoo! oneSearch: Finally, mobile search that gives answers, not web links. http://mobile.yahoo.com/mobileweb/onesearch?refer=1ONXIC From MI5Victim at mi5.gov.uk Fri Jun 22 23:42:51 2007 From: MI5Victim at mi5.gov.uk (MI5Victim at mi5.gov.uk) Date: 23 Jun 2007 03:42:51 GMT Subject: MI5 Persecution: Stasi 21/4/96 (15702) Message-ID: Subject: Chief Constable Alderson Condemns "Stasi" MI5 Newsgroups:uk.misc,uk.politics,uk.media,uk.legal,soc.culture.british Organization: Toronto Free-Net Summary: Keywords: John Alderson, former Chief Constable of Devon and Cornwall, had the following to say about the expansion of the Security Service's powers, in a recent magazine article; "It is fatal to let the secret service into the area of ordinary crime. MI5 is not under the same restraints as the police. They infiltrate organisations, people's jobs and lives. They operate almost like a cancer." "At the moment the acorn of a Stasi [the former East German communists' secret service] has been planted. It is there for future governments to build on." The message is clear. Criminal subversion and criminal harassment by an unpoliced minority not subject to the law, "infiltration of people's jobs and lives" is with us today. 15702 From andre.roberge at gmail.com Mon Jun 25 17:14:51 2007 From: andre.roberge at gmail.com (=?iso-8859-1?B?QW5kcuk=?=) Date: Mon, 25 Jun 2007 21:14:51 -0000 Subject: listing all property variables of a class instance In-Reply-To: References: <1182789455.818944.227660@g37g2000prf.googlegroups.com> Message-ID: <1182806091.384411.200730@m37g2000prh.googlegroups.com> On Jun 25, 2:09 pm, Neil Cerutti wrote: > On 2007-06-25, Andr? wrote: > > > > > Suppose I define a class with a number of variables defined as > > properties. Something like: > > > class MyClass(object): > > > def __init__(self): > > self.some_variable = 42 > > self._a = None > > self._b = "pi" > > > def get_a(self): > > return self._a > > def set_a(self, value): > > self._a = value > > > def get_b(self): > > return self._b > > def set_b(self, value): > > self._b = value > > > a = property(get_a, set_a, None, "a is a property") > > b = property(get_b, set_b, None, "b is a property") > > > Is there a way to write a method that would list automatically > > all the variables defined as a property (say by printing their > > docstring and/ or their value), and only those variables? > > This is off the cuff. There's likely a better way. > > for k, v in MyClass.__dict__.iteritems(): > if isinstance(v, property): > print k, v.__doc__ Thank you, this solved my problem nicely. Andr? > > -- > Neil Cerutti > 22 members were present at the church meeting held at the home of Mrs. Marsha > Crutchfield last evening. Mrs. Crutchfield and Mrs. Rankin sang a duet, The > Lord Knows Why. --Church Bulletin Blooper From brunobgDELETETHIS at users.sourceforge.net Thu Jun 28 17:44:02 2007 From: brunobgDELETETHIS at users.sourceforge.net (Bruno Barberi Gnecco) Date: Thu, 28 Jun 2007 18:44:02 -0300 Subject: IMAP library Message-ID: It seems that this question has been asked a few times in this group before, but sometime has passed since the last post and maybe there's something new. I'm looking for a high level IMAP library--I know of imaplib, but it's awfully documented and I was hoping to avoid reading RFCs for a simple email reader routine. So, is there any example, routine, library or code in some software package that reads mails from IMAP, with attachments? I don't need anything fancy, just reading the emails and decoding them. If there isn't, I'm willing to write one and release it under LGPL. Anybody would like to help? -- Bruno Barberi Gnecco From iamfractal at hotmail.com Tue Jun 19 15:21:15 2007 From: iamfractal at hotmail.com (Ed) Date: Tue, 19 Jun 2007 12:21:15 -0700 Subject: The Modernization of Emacs In-Reply-To: References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <873b0p9vpm.fsf@W0053328.mgh.harvard.edu> Message-ID: <1182280875.861486.324370@w5g2000hsg.googlegroups.com> On 19 Juni, 07:14, Harry George > > I've used emacs since the 1980's. ... > -- > Harry George > PLM Engineering Architecture I've asked this question on an emacs forum and got no response, so I presume the answer is no, but I see, Harry, that you're a veteran, so maybe you've seen things few others have. Have you ever seen an, "Extract method," function for emacs? Whereby you highlight some lines of code, press a key, and the code is whisked into its own method, with the appropriate method invocation left in its place. If you could post a link, that'd be just champion. .ed -- www.EdmundKirwan.com - Home of The Fractal Class Composition From sergey at fidoman.ru Fri Jun 1 04:53:26 2007 From: sergey at fidoman.ru (Sergey Dorofeev) Date: Fri, 1 Jun 2007 12:53:26 +0400 Subject: subexpressions References: Message-ID: "Peter Otten" <__peter__ at web.de> wrote in message news:f3ok60$vp7$03$1 at news.t-online.com... > Sergey Dorofeev wrote: > >> Please help, is there way to use sub-expressions in lambda? >> For example, if I want to calculate sin(x^2)+cos(x^2) I must code: >> lambda x: sin(x*x)+cos(x*x) >> How to make x*x to be evaluated once? > >>>> (lambda x: [sin(x2) + cos(x2) for x2 in [x*x]][0])(.5) == sin(.5*.5) + > cos(.5*.5) > True > > The real answer is of course: Use a function. But what about something like lambda x: sin(y)+cos(y) where y=x*x ? May be this could be a PEP? If there is no straight way to do this. From horpner at yahoo.com Wed Jun 20 13:31:27 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Wed, 20 Jun 2007 17:31:27 GMT Subject: Python and (n)curses References: <1182211133.956524.160020@g4g2000hsf.googlegroups.com> <87y7igzapo.fsf@benfinney.id.au> <1182246189.210723.16280@w5g2000hsg.googlegroups.com> <1182325869.237652.157800@c77g2000hse.googlegroups.com> Message-ID: On 2007-06-20, Jorgen Grahn wrote: > On Wed, 20 Jun 2007 00:51:09 -0700, peter wrote: >> >>> > For me, introducing similar commands in Python would be by far the biggest single improvement that could be made to the language. >> >>> If it should be done, it should be done as a compatible subset of >>> curses, IMHO. It has such a long history as the standard "GUI toolkit" >> >> But curses doesn't run under Windows - thats the whole point! > > I meant to say "as a compatible subset of the Python 'curses' module > API". > > I don't know what's so difficult about porting curses. Maybe > it's that the DOS console is too broken, or maybe too many > Unixisms are exposed by the API (can you get a signal when the > DOS console window is resized?). I think it's just a ton of work that wouldn't benefit that many people. If you're using curses on Windows, what are the chances you end up needing some other part of cygwin for the same program? > (Alex Martelli simply wrote something like this in his Python > book: "I hear about curses ports to Windows now and then, but > I've never seen one that worked". Something like that.) There's a curses emulator written for python called wcurses, that might provide enough functionality to allow a Windows implementation of your Python curses program. It doesn't actually use the windows console, however. You could write your own little console interface, tailored to your needs, which is implemented using curses on Unix, and the effbot's 'console' on Windows. -- Neil Cerutti Symphonies of the Romantic era were a lot longer in length. --Music Lit Essay From dwahler at gmail.com Fri Jun 15 13:21:54 2007 From: dwahler at gmail.com (David Wahler) Date: Fri, 15 Jun 2007 18:21:54 +0100 Subject: No subject In-Reply-To: <6F773C5D529B0148AE6EB025F9871F4701D39EE2@gsmcmail01.corp.gsmc.org> References: <6F773C5D529B0148AE6EB025F9871F4701D39EE2@gsmcmail01.corp.gsmc.org> Message-ID: On 6/15/07, Wiley Thomas wrote: > I'm trying to write a script to open a file on our (windows) network. The > file is located on a machine that is not part of the domain and requires a > separate user id and password to access. I tried using urllib2 and the > password_manager to authenticate but as some point urllib2 sees I'm trying > to access a local file and passes it off to os. The error message I get is: > > "WindowsError: [Error 1326] Logon failure: unknown user name or bad > password: > Does anyone know of a better approach. Urllib2 is used for making HTTP/FTP requests. When you open a file on a network share, the networking is handled by Windows; as far as Python is concerned, it's treated the same as a local file. You could try something like this (untested): os.system(r"NET USE \\computer\share password /USER:username") # do something with file os.system(r"NET USE \\computer\share /DELETE") That should authenticate and de-authenticate you properly, but it seems like a fragile way of doing it -- for one thing, I think it would grant access to any other program running under your login session. There may be a better way of doing this using the Windows API. Alternatively, depending on your application, you might want to consider using a simple web or FTP server. -- David From ndbecker2 at gmail.com Fri Jun 15 10:34:39 2007 From: ndbecker2 at gmail.com (Neal Becker) Date: Fri, 15 Jun 2007 10:34:39 -0400 Subject: global destructor not called? Message-ID: To implement logging, I'm using a class: class logger (object): def __init__ (self, name): self.name = name self.f = open (self.name, 'w') def write (self, stuff): self.f.write (stuff) def close (self): self.f.close() def flush (self): self.f.flush() def reopen (self): self.f.flush() self.f.close() os.rename (self.name, self.name + '.old') self.f = open (self.name, 'w') def __del__ (self): try: os.remove (self.name + '.old') except: pass And setting: sys.stderr = logger(...) It seems my cleanup (__del__) is never called, even though I believe my program exits normally. What's wrong? From timr at probo.com Wed Jun 13 01:35:22 2007 From: timr at probo.com (Tim Roberts) Date: Wed, 13 Jun 2007 05:35:22 GMT Subject: updating db with csv References: <1181234515.502945.43770@q66g2000hsg.googlegroups.com> <1181551597.685686.129100@k79g2000hse.googlegroups.com> Message-ID: Captain Paralytic wrote: >On 11 Jun, 07:37, Tim Roberts wrote: >| Not in standard SQL. MySQL supports a REPLACE extension that does >| an UPDATE if the key already exists, and an INSERT if it does not. >| There is also an extension clause to the INSERT statement called >| "ON DUPLICATE KEY UPDATE xxx" that might do what you want. > >No Tim, that is not correct. the REPLACE extension does not do an >update, it does a replace. It delets the old record and inserts a new >one. The INSERT...ON DUPLICATE KEY UPDATE... does an update. So a >REPLACE will remove all existing field values not referenced in the >statement, whilst an INSERT...ON DUPLICATE KEY UPDATE... will preserve >them. Also REPLACE will make a TIMESTAMP column which has a DEFAULT >CURRENT_TIMESTAMP setting work like one which has ON UPDATE >CURRENT_TIMESTAMP DEFAULT CURRENT_TIMESTAMP setting. Thanks for the correction; that's an important difference. I'm a Postgres guy; if I had noticed this was cross-posted to c.d.mysql as well as comp.lang.python, I probably would have kept quiet. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From horpner at yahoo.com Fri Jun 8 08:06:57 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Fri, 08 Jun 2007 12:06:57 GMT Subject: *Naming Conventions* References: <1180909218.939713.112010@q69g2000hsb.googlegroups.com> <1180990280.960271.235550@h2g2000hsg.googlegroups.com> <466699e9$0$2308$426a74cc@news.free.fr> <46690c7c$0$32006$426a34cc@news.free.fr> Message-ID: On 2007-06-08, Bruno Desthuilliers wrote: > Neil Cerutti a ?crit : >> On 2007-06-06, Bruno Desthuilliers >> wrote: >>> Neil Cerutti a ?crit : >>>> On 2007-06-04, Michael Hoffman wrote: >>>>> Wildemar Wildenburger wrote: >>>>> I agree with Bruno that i and j should be used only for >>>>> indices, but I'm usually less terse than that. >>>> I find i and j preferable to overly generic terms like "item." >>> Since 'i' and 'j' are canonically loop indices, I find it >>> totally confusing to use them to name the iteration variable - >>> which is not an index. >>> >>> At least, 'item' suggests that it's an object, and a part of >>> the collection - not just an index you'll have to use to >>> subscript the container. Also, and as far as I'm concerned, I >>> certainly dont find 'i' and 'j' *less* generic than 'item' !-) >> >> Thanks, I didn't say clearly what I meant. >> >> Certainly i and j are just as generic, but they have the >> advantage over 'item' of being more terse. > > I'm not sure this is really an "advantage" here. Why not? -- Neil Cerutti Beethoven's symphonies had more balls, if you will, than say a Mozart. --Music Lit Essay From ping.nsr.yeh at gmail.com Sat Jun 16 04:12:07 2007 From: ping.nsr.yeh at gmail.com (Ping) Date: Sat, 16 Jun 2007 08:12:07 -0000 Subject: a_list.count(a_callable) ? In-Reply-To: References: <1181850818.567840.251090@x35g2000prf.googlegroups.com> <1181853479.914070.217270@i13g2000prf.googlegroups.com> <1181855184.511137.100870@z28g2000prd.googlegroups.com> <1181916937.648267.163070@z28g2000prd.googlegroups.com> Message-ID: <1181981527.960296.135820@i13g2000prf.googlegroups.com> On 6 16 , 2 06 , "BJ?rn Lindqvist" wrote: > > Maybe you could extend count() analogous to how sort() works: > > # L is a list of Person objects, each Person has a name attribute > L.sort(key = attrgetter("name")) > > # How many olle are there? > print L.count("olle", key = attrgetter("name")) > > # And index could be extended in the same way! > # Whom has id 1234? > print L.index(1234, key = attrgetter("id")).name > > All of these could be solved by giving Person an __eq__() method, but > it fails when you need to search, sort or count on a different key. > > -- > mvh Bj?rn Wow! This jumps out of my screen! I like it very much. How to get the extension into the language? cheers, Ping p.s. By the way, I guess you meant print L[L.index(1234, key = attrgetter("id"))].name in the index example. From robert.kern at gmail.com Thu Jun 21 23:43:53 2007 From: robert.kern at gmail.com (Robert Kern) Date: Thu, 21 Jun 2007 22:43:53 -0500 Subject: Issues with nonfunctioning VTK under python 2.5 In-Reply-To: <8iEei.132$Ct1.38@newsfe03.lga> References: <8iEei.132$Ct1.38@newsfe03.lga> Message-ID: Eric Carlson wrote: > Any suggestions would be greatly appreciated. Please bring these bug reports to enthought-dev at enthought.com and possibly make a ticket on our Trac. https://mail.enthought.com/mailman/listinfo/enthought-dev https://svn.enthought.com/enthought Thanks. -- 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 S.Mientki-nospam at mailbox.kun.nl Tue Jun 5 17:57:15 2007 From: S.Mientki-nospam at mailbox.kun.nl (Stef Mientki) Date: Tue, 05 Jun 2007 23:57:15 +0200 Subject: PATH or PYTHONPATH under Windows ??? Message-ID: <90155$4665db45$d443bb3a$16812@news.speedlinq.nl> hello, after cleaning up a PC, Python can't find any libraries anymore. But happily I've still one PC, where Python is running perfect. Now I always read about the environment variable "PYTHONPATH". But on neither PC there exists a "PYTHONPATH". On the PC that works ok, there is the standard "PATH" environment variable, and indeed there are all the Python Library references. Please enlighten me. thanks, Stef Mientki From per9000 at gmail.com Tue Jun 5 05:52:36 2007 From: per9000 at gmail.com (per9000) Date: Tue, 05 Jun 2007 02:52:36 -0700 Subject: magic names in python In-Reply-To: <1181034149.249199.258570@i38g2000prf.googlegroups.com> References: <1180939436.862957.127810@p77g2000hsh.googlegroups.com> <1181034149.249199.258570@i38g2000prf.googlegroups.com> Message-ID: <1181037156.003143.99690@m36g2000hse.googlegroups.com> On 5 Juni, 11:02, ai wrote: > I don't think it is magic. If you think it is magic, can you talk > about what's the better way and how can you implement the functions > without any magic. [...] Well, in a sense I guess all reserved words can be considered magic, but in Python you can kill it (AFAIK that is pretty unique to python): >>> a = int(8) >>> int = float >>> b = int(8) >>> (a, b) (8, 8.0) I guess the amount and flavor of the magic is a matter of personal taste - coming from a C*-background I pretty much like myClass.myClass() instead of myClass.__init__() - but these are equivalent and I guess I just have to live with the way python has __special__ names and print a list of the cases I end up with often to keep my memory from forgetting them. > There are some special names even in Lisp. I guess you just hate the > '__'. Yes and no. Indeed, I find the overuse of underscores ugly, but I can accept some use of __special__ functions. AFAIK there must be reserved words in a programming language - f.x. names of ctors in oo-languages. The exceptions are perhaps brainf**k and whitespace that has special chars instead. Also I find it unfortunate that the name mangling and underscores are the way to make members "less public". But I can live with that - I just have to read more python code to get the hang of it. [:)]-|--< /Per -- Per Erik Strandberg home: www.pererikstrandberg.se work: www.incf.org also: www.spongswedencare.se > > On Jun 4, 2:43 pm, per9000 wrote: > > > Hi, > > > I recently started working a lot more in python than I have done in > > the past. And I discovered something that totally removed the pretty > > pink clouds of beautifulness that had surrounded my previous python > > experiences: magic names (I felt almost as sad as when I discovered > > the strange pink worms that eat you in nethack, not to mention the > > mind flayers - I really hate them). > > > I guess all programming languages have magic names to some extent > > (f.x. classes in the "C-family" have constructors that must have the > > same name as the class (foo::foo) instead of foo.__init__). > > > I just used a search engine a little on this topic and I found no > > comprehensive list of magic names in python. > > > So my questions: > > * is there a comprehensive list of magic names in python (so far i > > know of __init__ and __repr__)? > > * are these lists complete or can magic names be added over time (to > > the python "core")? > > * are magic names the same in different python versions? > > > I also tried (selected parts of(?)) the unittest package for use in > > Zope and it seemed functions that I created for my test with the magic > > prefix "test" were magic, other functions were not. > > > So another question emerges: > > * is the use of magic names encouraged and/or part of good coding > > practice. > > > Live long and prosper, > > Per > > > -- > > > Per Erik Strandberg > > home:www.pererikstrandberg.se > > work:www.incf.org > > also:www.spongswedencare.se From ptmcg at austin.rr.com Sat Jun 9 14:41:27 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: Sat, 09 Jun 2007 11:41:27 -0700 Subject: Where can I suggest an enchantment for Python Zip lib? In-Reply-To: References: Message-ID: <1181414487.690852.41650@m36g2000hse.googlegroups.com> Hogwarts. Sorry, I couldn't resist either. I'm sure you meant to say "enhancement" - an "enchantment" is a magic spell, often used to lull an unsuspecting victim into some sort of compliance or trance. Actually, if you have an *enchantment* for Python, I'm sure several people on this list would be interested. :) But yes, *enhancement* requests can be posted on the SF feature request list. You may need to more clearly define what kind of data these zlib callbacks would receive, and under what conditions they would be called. -- Paul From alejandro.weinstein at gmail.com Wed Jun 20 17:03:37 2007 From: alejandro.weinstein at gmail.com (Alejandro) Date: Wed, 20 Jun 2007 21:03:37 -0000 Subject: wxpython: Redirect the stdout to a textctrl In-Reply-To: <1182287230.696722.247930@u2g2000hsc.googlegroups.com> References: <1182284207.035976.92170@q19g2000prn.googlegroups.com> <1182287230.696722.247930@u2g2000hsc.googlegroups.com> Message-ID: <1182373417.606213.19190@g37g2000prf.googlegroups.com> On Jun 19, 5:07 pm, kyoso... at gmail.com wrote: > Give this a try: > > [good piece of code] > It worked like a charm! Thanks. I still don't understand why my initial aproach didn't work as expected. Regards, Alejandro. From evan at yelp.com Fri Jun 22 02:45:18 2007 From: evan at yelp.com (Evan Klitzke) Date: Thu, 21 Jun 2007 23:45:18 -0700 Subject: "assert" annoyance In-Reply-To: <1182494049.327182.205310@u2g2000hsc.googlegroups.com> References: <7xmyys368j.fsf_-_@ruckus.brouhaha.com> <1182494049.327182.205310@u2g2000hsc.googlegroups.com> Message-ID: On 6/21/07, Miles wrote: > On Jun 22, 1:31 am, Paul Rubin wrote: > > What I really want is for any assertion failure, anywhere in the > > program, to trap to the debugger WITHOUT blowing out of the scope > > where the failure happened, so I can examine the local frame. That > > just seems natural, but I don't see an obvious way to do it. > > You could run the entire program through pdb: > ---- > #!/usr/bin/env python -m pdb > > print "Hello!" > assert False > print "...world!" > ---- You can only pass one argument to a command that you invoke with the shebang sequence, so this won't work the way you wrote it. -- Evan Klitzke From martin at v.loewis.de Mon Jun 18 17:40:53 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Mon, 18 Jun 2007 23:40:53 +0200 Subject: XMLRPC and SSL In-Reply-To: References: Message-ID: <4676fbe5$0$23246$9b622d9e@news.freenet.de> Chaz Ginger schrieb: > I have a web service that I built and it requires using SSL. I have > found a few examples of clients using SSL but none that allow me to > change the client's certificate or the chain of certificates the client > will use to authenticate the server. > > I was wondering if anyone knows of a good example of this? I don't have an example, but I think you should create a ServerProxy, passing explicitly a SafeTransport subclass as the transport= argument. That subclass should override get_host_info, and return the x509 parameters to be passed to httplib.HTTPSConnection (i.e. keyfile= and cert_file=). Regards, Martin From thomas at jollans.com Wed Jun 27 15:48:53 2007 From: thomas at jollans.com (Thomas Jollans) Date: Wed, 27 Jun 2007 21:48:53 +0200 Subject: Capturing stdout from a class method In-Reply-To: <1182970818.052675.115480@n60g2000hse.googlegroups.com> References: <1182970818.052675.115480@n60g2000hse.googlegroups.com> Message-ID: Falcolas wrote: > I have a rather strange situation, and I'm not sure my brief > experience of Python will let me handle it properly. > > The situation is this: I have a Java class "X" which I need to call in > a Jython script. The output of "X" is sent to stdout using the java > call System.out. I need to capture this output, and preform tests on > it in the Jython script. > > My first pass at a design involves two jython scripts. One (we'll call > it "Y") whose sole function is to instantiate and call "X", and die. > The second script will call "Y" using a method which captures stdout > to a pipe. The second script would then read the stdout from the pipe > and act accordingly. > > Can anybody suggest a better way to handle this? The Java class, "X", > can not be modified for this test. How about subprocess.Popen ? I'm thinking of something like this: import subprocess X_proc = subprocess.Popen(['java', 'Xstarter']) for line in Xproc.stdout: # do funky stuff pass -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 260 bytes Desc: OpenPGP digital signature URL: From bignose+hates-spam at benfinney.id.au Fri Jun 29 03:55:12 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 29 Jun 2007 17:55:12 +1000 Subject: Writing TGA image files? References: <7xir9cbm0g.fsf@ruckus.brouhaha.com> <7xejjzmk7u.fsf@ruckus.brouhaha.com> <7xy7i7xjl5.fsf@ruckus.brouhaha.com> <1183044721.683930.131920@x35g2000prf.googlegroups.com> <1183066741.069248.25070@i13g2000prf.googlegroups.com> Message-ID: <878xa3qjof.fsf@benfinney.id.au> "Adam Pletcher" writes: > Does anyone have Python code for writing Targa (TGA) image files? Please post your question as a new message, instead of a reply to an existing thread that has nothing to do with the question you're asking. Otherwise your message will be obscured among the many other messages in the same thread. -- \ "I have never made but one prayer to God, a very short one: 'O | `\ Lord, make my enemies ridiculous!' And God granted it." -- | _o__) Voltaire | Ben Finney From tn.pablo at gmail.com Wed Jun 27 22:04:58 2007 From: tn.pablo at gmail.com (ptn) Date: Thu, 28 Jun 2007 02:04:58 -0000 Subject: Reversing a string In-Reply-To: References: <20070627170755.GG30401@lass.lfod.us> Message-ID: <1182996298.816803.293730@g4g2000hsf.googlegroups.com> > > or one letter per line: > > >>> print "\n".join("spam"[::-1]) > > m > a > p > s > One liners rock ;) From horpner at yahoo.com Mon Jun 25 13:09:25 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Mon, 25 Jun 2007 17:09:25 GMT Subject: listing all property variables of a class instance References: <1182789455.818944.227660@g37g2000prf.googlegroups.com> Message-ID: On 2007-06-25, Andr? wrote: > Suppose I define a class with a number of variables defined as > properties. Something like: > > class MyClass(object): > > def __init__(self): > self.some_variable = 42 > self._a = None > self._b = "pi" > > def get_a(self): > return self._a > def set_a(self, value): > self._a = value > > def get_b(self): > return self._b > def set_b(self, value): > self._b = value > > a = property(get_a, set_a, None, "a is a property") > b = property(get_b, set_b, None, "b is a property") > > Is there a way to write a method that would list automatically > all the variables defined as a property (say by printing their > docstring and/ or their value), and only those variables? This is off the cuff. There's likely a better way. for k, v in MyClass.__dict__.iteritems(): if isinstance(v, property): print k, v.__doc__ -- Neil Cerutti 22 members were present at the church meeting held at the home of Mrs. Marsha Crutchfield last evening. Mrs. Crutchfield and Mrs. Rankin sang a duet, The Lord Knows Why. --Church Bulletin Blooper From rw at smsnet.pl Tue Jun 5 16:01:44 2007 From: rw at smsnet.pl (Rob Wolfe) Date: Tue, 05 Jun 2007 22:01:44 +0200 Subject: subprocess leaves child living References: <1181052375.551083.117390@p47g2000hsd.googlegroups.com> Message-ID: <874plmgogn.fsf@merkury.smsnet.pl> Thomas Dybdahl Ahle writes: > But you can't ever catch sigkill. There is no protection against sigkill. > Isn't there a way to make sure the os kills the childprocess when the > parrent dies? If the parent dies suddenly without any notification childprocesses become zombies and there is no way to avoid that. -- HTH, Rob From gagsl-py2 at yahoo.com.ar Tue Jun 26 21:18:46 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 26 Jun 2007 22:18:46 -0300 Subject: [Bulk] RE: Python changing the keywords name Message-ID: (Please keep posting on the list. You can reach a lot of helpful people, and I don't read this email account very often) At Sunday 24/06/2007 10:38, you wrote: >> Instead of changing Python grammar, you could convert your"translated" >> source into "original" Python using the code below, andcompile and run >> as usual; you can also reverse the process. Also, thislets you use the >> standard Python library and all other Python codearound the world. > This previously was very useful, thanks. But can you just help me more > something about that??? When I "translate" my code with your example I > get:e.g. Translated on english: > My croatian code >>> koristi os # koristi as importispisi "Bok kaj ima" # ispisi as print > after translate I get code: " koristi os ispisi " I want to this > translateget me full code: koristi os ispisi "Bok kaj ima" This is my original example stripped down and using a small translation dictionary: --- begin code --- from cStringIO import StringIO import token import tokenize trans_en2hr = { 'import': 'koristi', 'print': 'ispisi', } trans_hr2en = dict((v,k) for (k,v) in trans_en2hr.items()) def translate_tokens(source, tdict): for tok_num, tok_val, _, _, _ in tokenize.generate_tokens(source.readline): if tok_num==token.NAME: tok_val = tdict.get(tok_val, tok_val) yield tok_num, tok_val text = """ koristi os # koristi as import ispisi "Bok kaj ima" # ispisi as print """ print tokenize.untokenize(translate_tokens(StringIO(text),trans_hr2en)) --- end code --- And I get this output: import os # koristi as import print "Bok kaj ima"# ispisi as print Hope this helps, -- Gabriel Genellina From tjreedy at udel.edu Fri Jun 22 18:23:43 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 22 Jun 2007 18:23:43 -0400 Subject: Python's "only one way to do it" philosophy isn't good? References: <1181368143.874341.273140@r19g2000prf.googlegroups.com><7x3b0nmkk6.fsf@ruckus.brouhaha.com> Message-ID: "Douglas Alan" wrote in message news:lcy7ibj1xo.fsf at gaffa.mit.edu... | "Terry Reedy" writes: | > I think this points to where Sussman went wrong in his footnote and | > Alan in his defense thereof. Flexibility of function -- being able | > to do many different things -- is quite different from flexibility | > of syntax | | I think you are setting up a false dichotomy. I think this denial of reality is your way of avoiding admitting, perhaps to yourself, that your god Sussman made a mistake. | One that is related to | the false unification that annoying people used to always make when | they would perpetually argue that it wasn't important which | programming language you programmed in, as they are all Turing | equivalent anyway. Well, I sure as hell don't want to write all my | programs for a Turning machine, and a Turing machine is certainly | Turing equivalent! Diversionary crap unrelated to the previous discussion. Bye. From borud-news at borud.no Thu Jun 21 10:26:10 2007 From: borud-news at borud.no (Bjorn Borud) Date: 21 Jun 2007 16:26:10 +0200 Subject: The Modernization of Emacs References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182344981.372713.298580@w5g2000hsg.googlegroups.com> <1182370884.853838.321440@c77g2000hse.googlegroups.com> <2jpok4-ajt.ln1@zoogz.gregorie.org> Message-ID: [Martin Gregorie ] | | As for documentation, lets look at vi. Not a great editor, but every | *nix variation has it installed and any fool can learn to use it in | about 2 hours flat and it does at least have good pattern matching. there's also the "info" system in Emacs, which not only covers Emacs itself, but usually also a lot of documentation available for Emacs extensions and other programs. again, this predates a lot of things that people are used to today, so just because it seems (and sometimes is) a bit more fiddly, it must necessarily be inferior. the most common theme when people have to choose between products is that they are not really comparing what it is like to use the products like they were intended -- they are merely underlining that X is not Y. for instance, Linux has come a long way in addressing the needs of desktop users, yet some people refuse to use Linux because it doesn't behave *exactly* like Windows (as if that was a worthwhile goal) and they are too lazy or don't think they can manage, to learn a new system. -Bj?rn From jadamson at partners.org Tue Jun 19 13:06:43 2007 From: jadamson at partners.org (Joel J. Adamson) Date: Tue, 19 Jun 2007 13:06:43 -0400 Subject: The Modernization of Emacs: terminology buffer and keybinding References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182272495.990807.99110@a26g2000pre.googlegroups.com> Message-ID: <87bqfbeuvw.fsf@W0053328.mgh.harvard.edu> Xah Lee writes: > Here are some Frequently Asked Questions about The Modernization of > Emacs. > > They are slightly lengthy, so i've separated each item per post. The > whole article can be found at > > http://xahlee.org/emacs/modernization.html > ------------ > > Q: The Terminology ?buffer? and ?keybinding? is good as they are. > > A: The terminology ?buffer? or ?keybinding?, are technical terms > having to do with software programing. The term ?keybinding? refers to > the association of a keystroke with a command in a technical, software > application programing context. That is to say, a programer ?bind? a > keystroke to a command in a software application. The term ?buffer? > refers to a abstract, temporary area for storing data, in the context > of programing or computer science. > > These terms are irrelevant to the users of a software application. Bologna. Every computer user should see himself as a programmer. > Changes in society are always resisted by old timers, but it is also a > main element behind progress. This terminology issue may seem trivial, > but its importance lies in making emacs palpable to the vast number of > people who ever need to use a computer to write. I'm a young-timer. Joel -- Joel J. Adamson Biostatistician Pediatric Psychopharmacology Research Unit Massachusetts General Hospital Boston, MA 02114 (617) 643-1432 (303) 880-3109 A webpage of interest: http://www.gnu.org/philosophy/sylvester-response.html From sjmachin at lexicon.net Sun Jun 3 17:29:49 2007 From: sjmachin at lexicon.net (John Machin) Date: Sun, 03 Jun 2007 14:29:49 -0700 Subject: Is 1 large Regex faster than 3 smaller ones? In-Reply-To: <1180896727.419817.303960@p47g2000hsd.googlegroups.com> References: <1180896727.419817.303960@p47g2000hsd.googlegroups.com> Message-ID: <1180906189.863323.46770@j4g2000prf.googlegroups.com> On Jun 4, 4:52 am, erikcw wrote: > Hi, > > I need to match 3 small strings in a small text file (about 200 words > of text). > > Would it be faster to write 1 compiled regex that matches all 3 > substrings in one go, or to use 3 separate regular expressions to do > the same job? > Taking your question literally: we have no idea how long it might take you to write alternative versions of source code. Guessing that you mean "Which would run faster?": both should run over a 200-word text file in imperceptibly different time (unless of course you make a mistake), and the time should be tiny compared to the time required to open the file (again unless of course you make a mistake). I'd suggest that as a learning exercise you do both, check the accuracy of both (text e.g. matching only 2 out of 3, sought strings in different orders, etc), and then and only then worry about the time it takes. HTH, John From http Fri Jun 29 11:57:14 2007 From: http (Paul Rubin) Date: 29 Jun 2007 08:57:14 -0700 Subject: PEP 3107 and stronger typing (note: probably a newbie question) References: <1182369568.941307.316260@p77g2000hsh.googlegroups.com> <5dveb4F360un0U1@mid.individual.net> <467a9209$0$22165$426a74cc@news.free.fr> <1182858785.886469.93060@n60g2000hse.googlegroups.com> <46824d8d$0$2324$426a74cc@news.free.fr> <4682eddc$0$23164$426a74cc@news.free.fr> <5ehokpF38ov3jU2@mid.individual.net> <4683d5cd$0$8993$426a74cc@news.free.fr> Message-ID: <7xps3e3g9x.fsf@ruckus.brouhaha.com> Bruno Desthuilliers writes: > Nope, he just asserted something wrong. Static typing is for compiler > optimization. Type checking is at most a side effect, and in some > languages (at least C, C++ and Java) can be totally defeated (usually > using typecasting). "Definitions of type system vary, but the following one due to Benjamin C. Pierce roughly corresponds to the current consensus in the programming language theory community: [A type system is a] tractable syntactic method for proving the absence of certain program behaviors by classifying phrases according to the kinds of values they compute. (Pierce 2002)." -- http://en.wikipedia.org/wiki/Type_theory#Type_system C and C++ are basically untyped languages. Java casts can only partially defeat its type system, so it's not untyped. From doug at alum.mit.edu Wed Jun 20 17:23:42 2007 From: doug at alum.mit.edu (Douglas Alan) Date: Wed, 20 Jun 2007 17:23:42 -0400 Subject: Python's "only one way to do it" philosophy isn't good? References: <1181368143.874341.273140@r19g2000prf.googlegroups.com> <7x3b0nmkk6.fsf@ruckus.brouhaha.com> Message-ID: Steven D'Aprano writes: > All of which makes Douglas Alan's accusations of Not Invented Here > syndrome about Python seem rather silly. I've never made such an accusation about Python itself -- just about the apparent attitude of some pontiffs. > The point I was making isn't that Scheme/Lisp features are "bad", > but that there is no reason to slavishly follow Scheme just because > it is(?) technically the most "pure" programming language. I don't argue in favor of purity. I argue in favor of functionality that would help me write better programs more easily. Having a somewhat pure and minimalistic core language, however, probably does help to make a language easier to implement, maintain, and understand. > I'm glad somebody understands lambda calculus and closures and meta- > classes, and that those people have created Python so I don't have > to. And I suspect that for every Douglas Alan enamored with Scheme, > there are ten thousand programmers who just want to use a handful of > pre-built tools to get the work done, never mind using macros to > create the tools they need before they can even start. I don't typically want to write that many macros myself. I want to be part of a community where cool macro packages are actively developed that I can then use. For instance, in Common Lisp, the entire OO system is just a big macro package that was implemented entirely within the language. With macros and first class continuations, as Sussman points out in his essay, people can then implement very interesting features like backtracking. Again, I don't want to implement a backtracking macro package myself; I want to be able to use what the community might come up with. > But "Scheme has macros" isn't a justification for why Python should > have them. No one ever gave that justification. The justification is that they are *good*. Macros are a way to abstract syntax the way that objects are used to abstract data types and that iterators and generators abstract control, etc. |>oug From orsenthil at gmail.com Wed Jun 20 12:50:31 2007 From: orsenthil at gmail.com (Phoe6) Date: Wed, 20 Jun 2007 09:50:31 -0700 Subject: Reading multiline values using ConfigParser Message-ID: <1182358231.269388.250510@m36g2000hse.googlegroups.com> Hi, I have a configfile, in fact, I am providing a configfile in the format: [Information] Name: Foo Author: Bar Testcases: tct123 tct124 tct101 The last values is a multi-line. ConfigParser is unable to recognize a multi-line value and splits out error. C:\ATF-Tasks>python CreateTask.py Traceback (most recent call last): File "CreateTask.py", line 13, in ? config.read('TaskDetails.txt') File "C:\Python24\lib\ConfigParser.py", line 267, in read self._read(fp, filename) File "C:\Python24\lib\ConfigParser.py", line 490, in _read raise e ConfigParser.ParsingError: File contains parsing errors: TaskDetails.txt [line 15]: 'tct123\n' [line 16]: 'tct124\n' [line 17]: 'tct101\n' I am using ConfigParser in the following way: config = ConfigParser.ConfigParser() config.read('TaskDetails.txt') config.get("Information","Testcases"): Is there anyway, I can include multi-line value in the configfile? I was thinking of following option:value for a portion of the file and read the portion with multi-line as a normal file, but ConfigParser() is not allowing multi-line value itself. Any ideas/ Suggestions? : Ofcourse, throw away ConfigParser and use your own parser is there, but I would like to use that as the last option. Thanks, Senthil From iansan at gmail.com Fri Jun 8 16:52:33 2007 From: iansan at gmail.com (IamIan) Date: Fri, 08 Jun 2007 20:52:33 -0000 Subject: Splitting SAX results In-Reply-To: <4667A954.8070909@web.de> References: <1181187340.685296.284850@i38g2000prf.googlegroups.com> <4667A954.8070909@web.de> Message-ID: <1181335953.348151.57540@n15g2000prd.googlegroups.com> Well SAX isn't the problem... maybe I should repost this with a different title. The SAX part works just as I want, but the results I get back need to be manipulated. No matter what I try I can't split a result like 'Title 1:Description' on the colon without getting an IndexError. Ideas anyone? From eadmund42 at NOSPAMgmail.com Sat Jun 23 02:11:55 2007 From: eadmund42 at NOSPAMgmail.com (Robert Uhl) Date: Sat, 23 Jun 2007 00:11:55 -0600 Subject: The Modernization of Emacs References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182370894.001918.36590@k79g2000hse.googlegroups.com> <1182372821.298343.316860@g4g2000hsf.googlegroups.com> <1182375321.067664.190780@o61g2000hsh.googlegroups.com> <86hcp1l6hb.fsf@lola.quinscape.zz> Message-ID: Bjorn Borud writes: > > | The idea is to start Emacs once and use it for everything. > > ...which is fine as long as you are only fiddling around on one > machine or you have emacs windows running on all your machines. Tramp can be used to access files on other hosts. It even supports multi-hop stuff like 'ssh to $HOST and su to root.' One thing GNU emacs needs to support is the ability to open a new X or terminal window via a command. I think Xemacs can already do this. > also, I make extensive use of the readline and history features when > fiddling about in the shell. shells have a lot of context if you use > them effectively. context that isn't easy to transport between the > shell and emacs -- and it isn't really easy to explain either. M-x shell, or M-x terminal -- Robert Uhl That's just 'mostly dead.' What we are concerned with here is 'Pining for the Fjords' dead. --Mark Urbin From robin at reportlab.com Wed Jun 27 13:11:03 2007 From: robin at reportlab.com (Robin Becker) Date: Wed, 27 Jun 2007 18:11:03 +0100 Subject: 16bit hash In-Reply-To: References: Message-ID: <46829A27.6090609@chamonix.reportlab.co.uk> Josiah Carlson wrote: > Robin Becker wrote: >> Is the any way to get an efficient 16bit hash in python? > > hash(obj)&65535 > > - Josiah yes I thought of that, but cannot figure out if the internal hash really distributes the bits evenly. Particularly since it seems to treat integers etc as special cases >>> hash(1) 1 >>> hash(2) 2 >>> hash('1234') 1723328704 >>> -- Robin Becker From grante at visi.com Mon Jun 4 11:04:39 2007 From: grante at visi.com (Grant Edwards) Date: Mon, 04 Jun 2007 15:04:39 -0000 Subject: python for EE CAD program References: <1180964104.685598.21330@n4g2000hsb.googlegroups.com> Message-ID: <1368ag7sah2pd86@corp.supernews.com> On 2007-06-04, chewie54 wrote: > 1) Can I use py2exe or pyinstaller to produce an executable > for Linux, Windows, and Mac? If not, is there a way it can be > done? > > 2) Is there any way to protect the source code, like obfuscation? > > 3) Memory footprint of application seems large for python demo. Is > this typical for large python applications? I'm glad somebody asked these questions. I was getting worried. It's almost lunchime on Monday and they hadn't come up yet this week. :) -- Grant Edwards grante Yow! RHAPSODY in Glue! at visi.com From carsten at uniqsys.com Sat Jun 23 14:47:38 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Sat, 23 Jun 2007 14:47:38 -0400 Subject: C API: passing by reference In-Reply-To: <1182623135.952521.174410@w5g2000hsg.googlegroups.com> References: <1182623135.952521.174410@w5g2000hsg.googlegroups.com> Message-ID: <1182624458.3372.19.camel@dot.uniqsys.com> On Sat, 2007-06-23 at 18:25 +0000, stuart.tett at gmail.com wrote: > I'm writing my own python extension module with the C API. In python > all functions pass arguments by reference, "Pass by reference", while correct from a certain standpoint, is to be taken with a large grain of salt. It is correct in so far as the value is not copied. It is incorrect in so far as, in general, you may not be able to modify the object that's passed. The reference you receive can only be used to call methods of the referenced object, if it has any, or manipulate attributes of the object, if it has any. It can not be used to replace the object with another object. > but how can I make use of > this in C? Right now, I am using: You can't. > PyArg_ParseTuple(args, "(ii)(ii)", &faceId1, &vertId1, &faceId2, > &vertId2) > > I want the to change the faceId's in my function. From what I've seen > you can't do this safely with PyArg_ParseTuple. Not with PyArg_ParseTuple, not with anything. Your function receives a reference to an int object. Since int objects are immutable, you can't replace the number that's in the int object. > Do I have another option? Return the value instead of trying to produce side-effects in the caller's name space. HTH, -- Carsten Haese http://informixdb.sourceforge.net From mccredie at gmail.com Thu Jun 7 12:50:30 2007 From: mccredie at gmail.com (Matimus) Date: Thu, 07 Jun 2007 16:50:30 -0000 Subject: running a random function In-Reply-To: <1654405.LVbK4P6cM3@teancum> References: <1654405.LVbK4P6cM3@teancum> Message-ID: <1181235030.982036.198030@x35g2000prf.googlegroups.com> How are you making the list of functions? Something like this: [code] fs = [] for k,f in globals(): if callable(f): fs.append(f) [/code] Then to call a random one (assuming they all take no parameters): [code] import random random.choice(fs)() [/code] Or maybe you only have the name of the function, this should work: [code] globals()[name]() [/code] Does this help? I'm not really clear on what you are asking for. From steve at REMOVE.THIS.cybersource.com.au Sun Jun 3 02:50:13 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sun, 03 Jun 2007 16:50:13 +1000 Subject: How to control the creation of an instance? References: <1180851453.441872.107890@k79g2000hse.googlegroups.com> <1180851949.266727.272980@q69g2000hsb.googlegroups.com> Message-ID: On Sat, 02 Jun 2007 23:25:49 -0700, 7stud wrote: > Oops. This line: > >> temp = object.__new__(Sample, args, kwds) > > should be: > > temp = object.__new__(cls, args, kwds) > > although it would seem that cls is always going to be Sample, so I'm > not sure what practical difference that makes. What if you are calling it from a sub-class? -- Steven. From arkanes at gmail.com Wed Jun 27 11:35:54 2007 From: arkanes at gmail.com (Chris Mellon) Date: Wed, 27 Jun 2007 10:35:54 -0500 Subject: Python's "only one way to do it" philosophy isn't good? In-Reply-To: References: <7xir9cbm0g.fsf@ruckus.brouhaha.com> <7xejjzmk7u.fsf@ruckus.brouhaha.com> <7xy7i7xjl5.fsf@ruckus.brouhaha.com> Message-ID: <4866bea60706270835p7e154fb7x72f17dbff9836bde@mail.gmail.com> On 6/27/07, Douglas Alan wrote: > Paul Rubin writes: > > Gee, that's back to the future with 1975 Lisp technology. Destructors > are a much better model for dealing with such things (see not *all* > good ideas come from Lisp -- a few come from C++) and I am dismayed > that Python is deprecating their use in favor of explicit resource > management. Explicit resource management means needlessly verbose > code and more opportunity for resource leaks. > > The C++ folks feel so strongly about this, that they refuse to provide > "finally", and insist instead that you use destructors and RAII to do > resource deallocation. Personally, I think that's taking things a bit > too far, but I'd rather it be that way than lose the usefulness of > destructors and have to use "when" or "finally" to explicitly > deallocate resources. > This totally misrepresents the case. The with statement and the context manager is a superset of the RAII functionality. It doesn't overload object lifetimes, rather it makes the intent (code execution upon entrance and exit of a block) explicit. You use it in almost exactly the same way you use RAII in C++ (creating new blocks as you need new scopes), and it performs exactly the same function. Nobody in their right mind has ever tried to get rid of explicit resource management - explicit resource management is exactly what you do every time you create an object, or you use RAII, or you open a file. *Manual* memory management, where the tracking of references and scopes is placed upon the programmer, is what people are trying to get rid of and the with statement contributes to that goal, it doesn't detract from it. Before the with statement, you could do the same thing but you needed nested try/finally blocks and you had to carefully keep track of the scopes, order of object creation, which objects were created, all that. The with statement removes the manual, error prone work from that and lets you more easily write your intent - which is *precisely* explicit resource management. RAII is a good technique, but don't get caught up on the implementation details. The fact that it's implemented via stack objects with ctors and dtors is a red herring. The significant feature is that it's you've got explicit, predictable resource management with (and this is the important bit) a guarantee that code will be called in all cases of scope exit. The with statement does exactly the same thing, but is actually superior because a) It doesn't tie the resource managment to object creation. This means you can use, for example, with lock: instead of the C++ style Locker(lock) and b) You can tell whether you exited with an exception, and what that exception is, so you can take different actions based on error conditions vs expected exit. This is a significant benefit, it allows the application of context managers to cases where RAII is weak. For example, controlling transactions. > > Python object lifetimes are in fact NOT predictable because the ref > > counting doesn't (and can't) pick up cyclic structure. > > Right, but that doesn't mean that 99.9% of the time, the programmer > can't immediately tell that cycles aren't going to be an issue. > > I love having a *real* garbage collector, but I've also dealt with C++ > programs that are 100,000+ lines long and I wrote plenty of Python > code before it had a real garbage collector, and I never had any > problem with cyclic data structures causing leaks. Cycles are really > not all that common, and when they do occur, it's usually not very > difficult to figure out where to add a few lines to a destructor to > break the cycle. > They can occur in the most bizarre and unexpected places. To the point where I suspect that the reality is simply that you never noticed your cycles, not that they didn't exist. > > And the refcounts are a performance pig in multithreaded code, > > because of how often they have to be incremented and updated. > > I'm willing to pay the performance penalty to have the advantage of > not having to use constructs like "when". > "with". And if you think you won't need it because python will get "real" GC you're very confused about what GC does and how. > Also, I'm not convinced that it has to be a huge performance hit. > Some Lisp implementations had a 1,2,3, many (or something like that) > reference-counter for reclaiming short-lived objects. This bypassed > the real GC and was considered a performance optimization. (It was > probably on a Lisp Machine, though, where they had special hardware to > help.) > > > That's why CPython has the notorious GIL (a giant lock around the > > whole interpreter that stops more than one interpreter thread from > > being active at a time), because putting locks on the refcounts > > (someone tried in the late 90's) to allow multi-cpu parallelism > > slows the interpreter to a crawl. > > All due to the ref-counter? I find this really hard to believe. > People write multi-threaded code all the time in C++ and also use > smart pointers at the same time. I'm sure they have to be a bit > careful, but they certainly don't require a GIL. > A generic threadsafe smart pointer, in fact, is very nearly a GIL. The GIL isn't just for refcounting, though, it's also about access to the python interpreters internal state. For the record, the vast majority of multithreaded C++ code is incorrect or inefficient or both. > I *would* believe that getting rid of the GIL will require some > massive hacking on the Python interpreter, though, and when doing that > it may be significantly easier to switch to having only a real GC than > having two different kinds of automatic memory management. > > I vote, though, for putting in that extra work -- compatibility with > Jython be damned. > Get cracking then. You're hardly the first person to say this. However, of the people who say it, hardly anyone actually produces any code and the only person I know of who did dropped it when performance went through the floor. Maybe you can do better. > > Lisp may always be around in some tiny niche but its use as a > > large-scale systems development language has stopped making sense. > > It still makes perfect sense for AI research. I'm not sure that > Lisp's market share counts as "tiny". It's certainly not huge, at > only 0.669% according to the TIOBE metric, but that's still the 15th > most popular language and ahead of Cobol, Fortran, Matlab, IDL, R, and > many other languages that are still in wide use. (Cobol is probably > still around for legacy reasons, but that's not true for the other > languages I mentioned.) > There's no particular reason why Lisp is any better for AI research than anything. I'm not familiar with the TIOBE metric, but I can pretty much guarantee that regardless of what it says there is far more COBOL code in the wild, being actively maintained (or at least babysat) than there is lisp code. > > If you want to see something really pathetic, hang out on > > comp.lang.forth sometime. It's just amazing how unaware the > > inhabitants there are of how irrelevant their language has become. > > Lisp isn't that far gone yet, but it's getting more and more like that. > > Forth, eh. A chaque son gout, but I'd be willing to bet that most > Forth hackers don't believe that Forth is going to make a huge > resurgence and take over the world. And it still has something of a > place as the core of Postscript and maybe in some embedded systems. > > Re Lisp, though, there used to be a joke (which turned out to be > false), which went, "I don't know what the most popular programming > language will be in 20 years, but it will be called 'Fortran'". In > reality, I don't know what the most popular language will be called 20 > years from now, but it will *be* Lisp. > And everyone who still uses the language actually called Lisp will continue to explain how it isn't a "real" lisp for a laundry list of reasons that nobody who gets work done actually cares about. > |>oug > -- > http://mail.python.org/mailman/listinfo/python-list > From kylotan at gmail.com Thu Jun 21 07:05:39 2007 From: kylotan at gmail.com (Ben Sizer) Date: Thu, 21 Jun 2007 04:05:39 -0700 Subject: something similar to shutil.copytree that can overwrite? In-Reply-To: <1182336006.442871.287590@a26g2000pre.googlegroups.com> References: <1182331815.865344.190700@u2g2000hsc.googlegroups.com> <1182336006.442871.287590@a26g2000pre.googlegroups.com> Message-ID: <1182423939.466780.322230@c77g2000hse.googlegroups.com> On 20 Jun, 11:40, Justin Ezequiel wrote: > On Jun 20, 5:30 pm, Ben Sizer wrote: > > > I need to copy directories from one place to another, but it needs to > > overwrite individual files and directories rather than just exiting if > > a destination file already exists. > > What version of Python do you have? > Nothing in the source would make it exit if a target file exists. > (Unless perhaps you have sym-links or the like.) I have 2.5, and I believe the behaviour I saw was that it exits if a directory already exists and it skips any files that already exist. It certainly wouldn't overwrite anything. -- Ben Sizer From bblais at bryant.edu Thu Jun 7 10:03:05 2007 From: bblais at bryant.edu (Brian Blais) Date: Thu, 07 Jun 2007 10:03:05 -0400 Subject: pickling problem Message-ID: <46681019.3080305@bryant.edu> Hello, I have a somewhat nested dict that I want to pickle, but it (sometimes) contains some no-no's (specifically, in this case, functions). I know I can't pickle them, but I would like to be able to pickle the rest of the dict. Is there a good way to be able to walk through a dict, and take out all of the non-pickleable objects? I could replace them with something else (a tag of some sort, for me to reconstruct things later). thanks, Brian Blais -- ----------------- bblais at bryant.edu http://web.bryant.edu/~bblais From x31equsenet at gmail.com Wed Jun 27 00:38:32 2007 From: x31equsenet at gmail.com (Graham Breed) Date: Tue, 26 Jun 2007 21:38:32 -0700 Subject: Python's "only one way to do it" philosophy isn't good? References: <7x3b0nmkk6.fsf@ruckus.brouhaha.com> <1182738909.918893.92220@m37g2000prh.googlegroups.com> Message-ID: <1182919112.857740.228080@i13g2000prf.googlegroups.com> Douglas Alan wote: > Graham Breed writes: > > > Another way is to decorate functions with their local variables: > > >>>> from strict import my > >>>> @my("item") > > ... def f(x=1, y=2.5, z=[1,2,4]): > > ... x = float(x) > > ... w = float(y) > > ... return [item+x-y for item in z] > > Well, I suppose that's a bit better than the previous suggestion, but > (1) it breaks the style rule of not declaring variables until you need > them, and (2) it doesn't catch double initialization. (1) is a style rule that many style guides explicitly violate. What is (2) and why would it be a problem? A better way that I think is fine syntactically would be from strict import norebind, set @norebind def f(x=1, y=2.5, z=[1.2.4]): set(x=float(x)) set(w=float(y)) return [item+x-y for item in z] It won't work because the Python semantics don't allow a function to alter a nested namespace. Or for a decorator to get at the locals of the function it's decorating. It's an example of Python restricting flexibility, certainly. > > The best way to catch false rebindings is to stick a comment with > > the word "rebound" after every statement where you think you're > > rebinding a variable. > > No, the best way to catch false rebindings is to have the computers > catch such errors for you. That's what you pay them for. How does the computer know which rebindings are false unless you tell it? > > Then you can search your code for cases where there's a "rebound" > > comment but no rebinding. > > And how do I easily do that? And how do I know if I even need to in > the face of sometimes subtle bugs? In UNIX, you do it by putting this line in a batch file: egrep -H 'rebound' $* | egrep -v '^[^:]+:[[:space:]]*([.[:alnum:]]+) [[:space:]]*=(|.*[^."])\<\1\>' You don't know you need to do it, of course. Like you wouldn't know you needed to use the let and set macros if that were possible. Automated checks are only useful for problems you know you might have. > > Assuming you're the kind of person who knows that false rebindings > > can lead to perplexing bugs, but doesn't check apparent rebindings > > in a paranoid way every time a perplexing bug comes up, anyway. > > (They aren't that common in modern python code, after all.) > > They're not that uncommon, either. The 300-odd line file I happened to have open had no examples of the form x = f(x). There was one rebinding of an argument, such as: if something is None: something = default_value but that's not the case you were worried about. If you've decided it does worry you after all there may be a decorator/function pattern that can check that no new variables have been declared up to a certain point. I also checked a 400-odd file which has one rebinding that the search caught. And also this line: m, n = n, m%n which isn't of the form I was searching for. Neither would the set() solution above be valid, or the substitution below. I'm sure it can be done with regular expressions, but they'd get complicated. The best way would be to use a parser, but unfortunately I don't understand the current Python grammar for assignments. I'd certainly be interested to see how your proposed macros would handle this kind of thing. This is important because the Python syntax is complicated enough that you have to be careful playing around with it. Getting macros to work the way you want with results acceptable to the general community looks like a huge viper pit to me. That may be why you're being so vague about the implementation, and why no macro advocates have managed to get a PEP together. A preprocessor that can read in modified Python syntax and output some form of real Python might do what you want. It's something you could work on as a third-party extension and it should be able to do anything macros can. That aside, the short code sample I give below does have a rebinding of exactly the form you were worried about. It's still idiomatic for text substitutions and so code with a lot of text substitutions will likely have a lot of rebindings. You could give each substituted text a different name. I think that makes some sense because if you're changing the text you should give it a name to reflect the changes. But it's still error prone: you might use the wrong (valid) name subsequently. Better is to check for unused variables. > I've certainly had it happen to me on several occasions, and sometimes > they've been hard to find as I might not even see the mispeling even > if I read the code 20 times. With vim, all you have to do is go to the relevant line and type ^* to check that the two names are really the same. I see you use Emacs but I'm sure that has an equivalent. > (Like the time I spent all day trying to figure out why my assembly > code wasn't working when I was a student and finally I decided to ask > the TA for help, and while talking him through my code so that he > could tell me what I was doing wrong, I finally noticed the "rO" where > there was supposed to be an "r0". It's amazing how useful a TA can > be, while doing nothing at all!) Assembly then, not Python. > > And you're also the kind of person who's troubled by perplexing bugs > > but doesn't run a fully fledged lint. > > Maybe PyLint is better than Lint for C was (hated it!), but my idea of > RAD does not include wading through piles of useless warning messages > looking for the needle warning in the warning haystack. Or running > any other programs in the midst of my code, run, code, run, ..., loop. Well, that's the choice you have I'm afraid. Either the computer nannies you about spurious bugs in your code or you miss genuine bugs. I don't see why it makes a difference for an external tool to do the nannying. Checking for unused variables is the obvious way to check for spelling mistakes in Python. > > Maybe that's the kind of person who wouldn't put up with anything > > short of a macro as in the original proposal. All I know is that > > it's the kind of person I don't want to second guess. > > As it is, I code in Python the way that a normal Python programmer > would, and when I have a bug, I track it down through sometimes > painstaking debugging as a normal Python programmer would. Just as > any other normal Python programmer, I would not use the alternatives > suggested so far, as I'd find them cumbersome and inelegant. I'd > prefer not to have been bit by the bugs to begin with. Consequently, > I'd use let and set statements, if they were provided (or if I could > implement them), just as I have the equivalents to let and set in > every other programming language that I commonly program in other than > Python. Except that, unlike a normal Python programmer, you don't want to use Python syntax. I have, out of interest, written a Python script to convert from a Python-like language with let and set into real Python. It's really not that difficult. It's full of holes, of course, but I'm not convinced that macros would be any different. Here it is: import sys, re, os general_match = r"(?m)^(\s*)%s(\s+)(\w+)(\s*=)" general_insert = r"\1assert '\3' %s in locals()\n\1\3\4" let_spec = general_match % "let", general_insert % "not" set_spec = general_match % "set", general_insert % "" escape_spec = general_match % r"\\([ls]et)", r"\1\2\3\4\5" inputfile = sys.argv[1] outputfile = os.path.splitext(inputfile)[0] + os.path.extsep + 'py' code = open(inputfile).read() for match, insert in let_spec, set_spec, escape_spec: code = re.sub(match, insert, code) # rebound open(outputfile, 'w').write(code) Graham From iddw at hotmail.com Thu Jun 21 17:40:14 2007 From: iddw at hotmail.com (Dave Hansen) Date: Thu, 21 Jun 2007 14:40:14 -0700 Subject: The Modernization of Emacs In-Reply-To: References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182344981.372713.298580@w5g2000hsg.googlegroups.com> <86y7ieoiv7.fsf@lola.quinscape.zz> <1182347061.347199.133480@g4g2000hsf.googlegroups.com> <874pl2eg2j.fsf@W0053328.mgh.harvard.edu> <1182370016.986915.202150@u2g2000hsc.googlegroups.com> Message-ID: <1182462014.621775.176460@u2g2000hsc.googlegroups.com> On Jun 21, 9:49 am, Robert Uhl wrote: > Twisted writes: > > > Given that in its out-of-the-box configuration it's well-nigh unusable > > without a printed-out "cheat sheet" of some kind, of the sort that > > were supposed to have died out in the 80s, getting it customized poses > > something of a catch-22 for anyone trying to get started using it. > > I don't see that. C-h t is your friend if you're starting out. The > only keystrokes a user really needs to remember are C-x C-s and C-x C-c; > everything else simple text editing needs works as expected (arrow keys, > backspace and so forth). Granted, text-mode is friendlier than I'm not so sure C-h t is anybody's friend anymore. Every version of Emacs that I've used since 1984 has supported the arrow and page up/ down keys. And every version of the tutorial that I've read (the latest just a couple years back) insists on starting the user out with C-f, C-b, C-p, C-n, C-V, and ESC-V, with some lame explanation like "touch-typists shun the arrow and page keys, and besides, they might not be supported on the next terminal you use." Like ESC, I suppose. Furrfu. Regards, -=Dave From bcb at undisclosedlocation.net Sun Jun 10 20:50:00 2007 From: bcb at undisclosedlocation.net (BCB) Date: Sun, 10 Jun 2007 19:50:00 -0500 Subject: The Concepts and Confusions of Prefix, Infix, Postfix and Fully Functional Notations References: <1179936917.652372.24780@q69g2000hsb.googlegroups.com> <1180508453.226022.44230@q19g2000prn.googlegroups.com> <1181335574.107472.229370@x35g2000prf.googlegroups.com> <1181358616.792797.97720@k79g2000hse.googlegroups.com> <1181414625.121073.203940@g4g2000hsf.googlegroups.com> <0uHai.176367$nh4.13819@newsfe20.lga> <1181448558.120521.63250@g4g2000hsf.googlegroups.com> <0G_ai.1970$xg4.809@trnddc08> Message-ID: > > Neither APL nor Snobol nor J are toy or joke languages I wholeheartedly agree, and did not mean to imply as much in my original post, in which my intent was to emphasize the fact that, until you learn the language, a J program /does/ resemble line noise! :-) From afilash at gmail.com Tue Jun 19 06:05:31 2007 From: afilash at gmail.com (abhilash pp) Date: Tue, 19 Jun 2007 15:35:31 +0530 Subject: is it possible to write python scripts in mainframe like REXX ?? Message-ID: <9f9d35df0706190305s685e631r26f380afc57c1cfd@mail.gmail.com> hai folks , i am extremely new to this list can anybody tell me where can i find docs that are related to "sripting in mainframe using python" or how can we use python instered of REXX in mainframe how can i run python scripts in mainframe any help will be appreciated............. thanks in advance regards, abhilash -------------- next part -------------- An HTML attachment was scrubbed... URL: From thorsten at thorstenkampe.de Mon Jun 11 07:55:48 2007 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Mon, 11 Jun 2007 12:55:48 +0100 Subject: python-ldap for Python 2.5 on Windows? References: <1181323389.805143.236480@i38g2000prf.googlegroups.com> Message-ID: * Benedict Verheyen (Mon, 11 Jun 2007 11:32:26 +0200) > Thorsten Kampe schreef: > > * Benedict Verheyen (Mon, 11 Jun 2007 11:23:59 +0200) > >> Waldemar Osuch schreef: > >>> I have managed to build it for myself using MinGW: > >>> http://www.osuch.org-a.googlepages.com/python-ldap-2.3.win32-py2.5.exe > >>> > >>> See if it will work for you > >>> > >> thanks for the installation file. > >> When i installed it, i got an error stating "The setup files are corrupt". > > > > I downloaded and installed them. They work fine... > > I'm on Vista (boohoo :(), what's your platform? XP SP2 From anglozaxxon at gmail.com Mon Jun 4 20:54:39 2007 From: anglozaxxon at gmail.com (anglozaxxon) Date: Tue, 05 Jun 2007 00:54:39 -0000 Subject: "Plugin" architecture - how to do? In-Reply-To: References: <1175785055.668181.308140@b75g2000hsg.googlegroups.com> <1175867963.727762.321170@l77g2000hsb.googlegroups.com> <1176124020.074341.144740@o5g2000hsb.googlegroups.com> Message-ID: <1181004879.950774.6160@j4g2000prf.googlegroups.com> On Apr 10, 10:26 pm, c james wrote: > Take a look at Trac. This might give you some ideas. > > http://trac.edgewall.org/wiki/TracDev/ComponentArchitecture Thanks cJames, that's exactly what I'm looking for. From bruno.42.desthuilliers at wtf.websiteburo.oops.com Tue Jun 26 06:00:02 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Tue, 26 Jun 2007 12:00:02 +0200 Subject: [OT] can't start Apache on Mac OS X--no listening sockets available? In-Reply-To: <1182824632.015853.317970@g4g2000hsf.googlegroups.com> References: <1182824632.015853.317970@g4g2000hsf.googlegroups.com> Message-ID: <4680e39c$0$13209$426a74cc@news.free.fr> 7stud a ?crit : > I'm trying to get Apache set up on my system so I can use mod_python. > I installed Apache 2.2.4 according to the following instructions: > > http://switch.richard5.net/isp-in-a-box-v2/installing-apache-on-mac-os-x/#comment-30704 > > and everything seemed to install correctly, but I can't start Apache. > I typed in the following command: > > $ sudo /Library/Apache2/bin/apachectl start > Password: > > and I got this error message: > > httpd: Could not reliably determine the server's fully qualified > domain name, using tms-computer.local for ServerName > (48)Address already in use: make_sock: could not bind to address > 0.0.0.0:80 > no listening sockets available, shutting down > Unable to open logs > > Any ideas? > yes : please post on a Mac newsgroup. This has nothing to do with Python. This group is highly tolerant[1], but you'll probably find the best answers on a mac-related newsgroup, because that's where the Mac expert are (or at least are supposed to be). [1] as a matter of fact, you got some answers to a totally OT post not even labelled as such - on some ng you would have been shot down in flames instead... From Afro.Systems at gmail.com Sun Jun 17 03:07:38 2007 From: Afro.Systems at gmail.com (Tzury) Date: Sun, 17 Jun 2007 07:07:38 -0000 Subject: Comparing UTF-8 into USC-2 and vice versa (newbie :-) ) Message-ID: <1182064058.292960.319970@p77g2000hsh.googlegroups.com> I recently rewrote a .net application in python. The application is basically gets streams via TCP socket and handle operations against an existing database. The Database is SQLite3 (Encoded as UTF-8). The Networks streams are encoded as UCS-2. Since in UCS-2, 'A' = '0041' and when I check with the built-in functions I get for unicode("A", "utf-8") = u'A' = u'\u0041'. I wonder what is the difference, and how can I safely encode/decode UCS-2 streams and match them with the UTF-8 representation From aleax at mac.com Sat Jun 2 21:07:03 2007 From: aleax at mac.com (Alex Martelli) Date: Sat, 2 Jun 2007 18:07:03 -0700 Subject: Python rocks References: <4661700a$0$19261$da0feed9@news.zen.co.uk> Message-ID: <1hz3dq5.1ujabwt1n1e6mfN%aleax@mac.com> Mark Carter wrote: > I picked Chicken Scheme for OS X. Things started well, and even the web ... > that; but I found that it ultimately depended on gmp, which turned out a > pain to compile. Yes, GMP is a pain to compile (especially on Mac OS X), but I believe that the Universal Binary library version I've put among the gmpy downloads (see http://code.google.com/p/gmpy/downloads/list) works fine (at least it seems to work fine for gmpy, which is my Python extension that wraps GMP, and gmpy exposes and copiously unit-tests essentially all of GMP's functionality). Just mentioning this in case you want to give Scheme another chance (which it may well deserve, although closures are hardly unique to it; I wonder if you meant continuations). Python may enjoy better tools and libraries than Scheme, but then Java enjoys better ones yet, yet I prefer to stick with Python because I like it better *as a language*... Alex From jstroud at mbi.ucla.edu Mon Jun 11 18:06:29 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Mon, 11 Jun 2007 15:06:29 -0700 Subject: Properties for modules? In-Reply-To: References: Message-ID: Ed Leafe wrote: > I have a simple module that reads in values from disk when > imported, and stores them in attributes, allowing for code like: > > >>> import moduleFoo > >>> print moduleFoo.someSetting > 'the value' > > What I'd like to do is have a more property-like behavior, so that > if they try to set the value of moduleFoo.someSetting, it also persists > it to disk. But properties are really only useful in instances of > classes; if I define 'someSetting' as a property at the module level, I > get: > > >>> import moduleFoo > >>> print moduleFoo.someSetting > > > Does anyone know any good tricks for getting property-like behavior > here? > > -- Ed Leafe > -- http://leafe.com > -- http://dabodev.com Most pythonic and recommended would be to create a class inside moduleFoo that has the functionality you describe, instantiate an instance, and then import reference to the instance into the local namespace. This will be essentially equivalent to "module level properties" as you describe them. # moduleFoo.py def get_setting(self, name): return do_whatever(name) def set_setting(self, name, arg): return do_whatever_else(name, arg) class Foo(object): someSetting = property(set_setting, get_setting) foo = Foo() # program.py from moduleFoo import foo foo.someSetting = some_value # etc. Of course, its probably better to move the getters and setters into Foo if they will only be used in foo context. James From cgwalters at gmail.com Mon Jun 4 10:19:14 2007 From: cgwalters at gmail.com (cgwalters at gmail.com) Date: Mon, 04 Jun 2007 14:19:14 -0000 Subject: another thread on Python threading In-Reply-To: References: <1180906374.041535.296410@k79g2000hse.googlegroups.com> Message-ID: <1180966754.725123.122890@m36g2000hse.googlegroups.com> On Jun 3, 9:10 pm, Josiah Carlson wrote: > > If you are doing string searching, implement the algorithm in C, and > call out to the C (remembering to release the GIL). I considered that, but...ick! The whole reason I'm writing this program in Python in the first place is so I don't have to deal with the mess that is involved when you do string matching and data structure traversal in C. On the other hand, there are likely C libraries out there for searching the kinds of data structures I use; I'll investigate. > > There's a lot of past discussion on this, and I want to bring it up > > again because with the work on Python 3000, I think it is worth trying > > to take a look at what can be done to address portions of the problem > > through language changes. > > Not going to happen. All Python 3000 PEPs had a due-date at least a > month ago (possibly even 2), so you are too late to get *any* > substantial change in. =( Too bad. It might be possible to do these changes in a backwards compatible way, though less elegantly. For example, the object change could be denoted by inheriting from "fixedobject" or something. From S.Mientki-nospam at mailbox.kun.nl Sun Jun 17 07:39:35 2007 From: S.Mientki-nospam at mailbox.kun.nl (Stef Mientki) Date: Sun, 17 Jun 2007 13:39:35 +0200 Subject: Inserting breakpoints ... In-Reply-To: References: <1393$4673e30a$d443bb3a$26599@news.speedlinq.nl> Message-ID: <44c88$46751c65$d443bb3a$14472@news.speedlinq.nl> Gabriel Genellina wrote: > En Sat, 16 Jun 2007 10:22:34 -0300, Stef Mientki > escribi?: > >> for the simulation of some micro language (JAL), >> the original language is (with a minimal effort) translated into Python, >> after which the code is run in Python. >> >> I want to add a call to a debug routine, >> called JSM(linenr), which performs task like wait, update user >> feedback, etc. >> This works, but doesn't give a nice output >> >> for xxx in xrange ( 16 * hardware_column ): >> JSM(78) >> Write_LCD_2Bytes ( write_text , 0 ) ;JSM(79) >> > > Try sys.settrace() > thanks Gabriel, that might be a good way to go, I'll study that in the near feature, (can't find the easy to read details right now :-( cheers, Stef Mientki From simonkagwe at yahoo.com Sat Jun 23 08:47:54 2007 From: simonkagwe at yahoo.com (simon kagwe) Date: Sat, 23 Jun 2007 12:47:54 +0000 (UTC) Subject: Changing sound volume Message-ID: Hi, I am playing sounds using the winsound module. Is there a way I can change the volume? From bignose+hates-spam at benfinney.id.au Tue Jun 19 03:04:35 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Tue, 19 Jun 2007 17:04:35 +1000 Subject: Python and (n)curses References: <1182211133.956524.160020@g4g2000hsf.googlegroups.com> Message-ID: <87y7igzapo.fsf@benfinney.id.au> "pinkfloydhomer at gmail.com" writes: > The obvious choice, I thought, was ncurses. But as far as I can > tell, it is not available for Python on Windows? More precisely, curses doesn't work natively on Windows, regardless of whether Python is involved. As with many "how do I get Unix feature foo on Windows?", one answer is to download and install Cygwin . This gives you a Unix-like environment where you can run a great many applications, including ones that depend on curses. For working with curses in Python you might find the Urwid library helpful. -- \ "I was in a bar the other night, hopping from barstool to | `\ barstool, trying to get lucky, but there wasn't any gum under | _o__) any of them." -- Emo Philips | Ben Finney From jadamson at partners.org Thu Jun 21 13:12:29 2007 From: jadamson at partners.org (Joel J. Adamson) Date: Thu, 21 Jun 2007 13:12:29 -0400 Subject: The Modernization of Emacs References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182344981.372713.298580@w5g2000hsg.googlegroups.com> <86y7ieoiv7.fsf@lola.quinscape.zz> <1182347061.347199.133480@g4g2000hsf.googlegroups.com> <874pl2eg2j.fsf@W0053328.mgh.harvard.edu> <1182370016.986915.202150@u2g2000hsc.googlegroups.com> <87k5tx7444.fsf@W0053328.mgh.harvard.edu> Message-ID: <87wsxx9qpu.fsf@W0053328.mgh.harvard.edu> Lew writes: > Joel J. Adamson wrote: >> My point is that I'm the sort of person that has a mind set up for >> Emacs. I had none of the difficulties that someone else might have, >> who's used to other kinds of software. >> >> However, I'll also point out that my wife has used Emacs a couple >> times, and she's never done more than point and click with a computer, >> and she's had no frustration whatsoever. > > A new user of two hours' experience. A father of a six-year old whose > child hums along happily with emacs. A computer widow who "had no > frustration whatsoever" with it. > I'll add that the words "Oh, cool" came out of her mouth during one Emacs session, as they did when I showed it to a coworker. Joel -- Joel J. Adamson Biostatistician Pediatric Psychopharmacology Research Unit Massachusetts General Hospital Boston, MA 02114 (617) 643-1432 (303) 880-3109 A webpage of interest: http://www.gnu.org/philosophy/sylvester-response.html From aleax at mac.com Sat Jun 16 20:14:36 2007 From: aleax at mac.com (Alex Martelli) Date: Sat, 16 Jun 2007 17:14:36 -0700 Subject: Want to learn Python References: <1181907696.878873.214760@i13g2000prf.googlegroups.com> <1181950960.793735.304570@c77g2000hse.googlegroups.com> <1hzrppt.1i3pamvoxog4rN%aleax@mac.com> <1182011078.358795.151590@c77g2000hse.googlegroups.com> Message-ID: <1hzt7iz.1s2iz1hlvanlvN%aleax@mac.com> 7stud wrote: > > I'm curious, have you tried _Python for Dummies_? > > No, I haven't. Unfortunately, I don't ever consider Dummies books. > That type of marketing appeals to certain people and not others. I'm > one of the others. I'll definitely take a look at it the next time > I'm in the bookstore. Aahz's book is really good, in my opinion. So are many others in the "for Dummies" series that I've had occasion to try (including the one with the delightfully unintended pun in its title, "Bridge for Dummies": despite the title it applies to declarers and defenders just as well:-). Judging a book by its cover (and, by extension, by how its publisher markets a series) is the proverbial epitome of superficiality. > >We didn't wait for Wiley to offer, we simply insisted on providing a > >list of index terms. > > It's nice to hear about an author who cares enough about the end > product that bears their name to insist on quality. I'm so tired of > hearing authors whine that the publisher screwed up the book. Oh, I'm SO awfully sorry to add to your tiredness! But the "whining" that so saps your energy is a simple statement of fact, at least in my case -- my publisher just didn't allow me sensible options for providing the index myself. Oh, I could have "provided a list of index terms", separate and floating in a vacuum (but "genexps" is in the index anyway, as is "generator expressions":-), but there was no way I could do it _right_, simply tying each index term to all the pages/page-ranges it should point to by including suitable tags in my manuscript. I won't tire you further with a tirade about my unpleasant tools experiences with both the Cookbook and the Nutshell, but they're a good part of what's holding me back from writing another book with the same publisher (including a third edition of either). I believe (and it seems the generally good reviews of the book support me in this) that the Python community is better off with a Nutshell with an imperfect index than it would be with no Nutshell at all, which would likely be the case if I had "insisted on quality" as you apparently would have preferred. Alex From mail at timgolden.me.uk Sun Jun 3 05:13:19 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Sun, 03 Jun 2007 10:13:19 +0100 Subject: Trouble killing a process on windows In-Reply-To: <1180838961.492129.28960@q66g2000hsg.googlegroups.com> References: <1180801625.231797.158370@p77g2000hsh.googlegroups.com> <1180838961.492129.28960@q66g2000hsg.googlegroups.com> Message-ID: <4662862F.9080409@timgolden.me.uk> Thomas Nelson wrote: [... re Access Denied error on trying to TerminateProcess ...] [Tim Golden] >> I suppose you might have to adjust your token privs to include, >> say the Debug priv. This is designed to let you take control >> of any process (and terminate it, or whatever). If it looks >> like you need to do that, post back and I -- or someone else -- >> can try to run up an example. [Thomas Nelson] > I Tried the PID method, and the Taskkill method, and neither worked. > This is what I get for trying to work on a windows machine. If you > could explain how to add the debug privilege, that would be great. OK, this being Windows security, there's a couple of hoops to jump through, but nothing too bad. import win32api import win32security as sec # # This function is merely window-dressing # to make it easier to see whether the # code has worked or not. # def priv_status (hToken, priv): for p, status in sec.GetTokenInformation ( hToken, sec.TokenPrivileges ): if p == priv: if status == 0: return "disabled" else: return "enabled" else: return "disabled" process = win32api.GetCurrentProcess () token_access_flags = sec.TOKEN_ADJUST_PRIVILEGES | sec.TOKEN_QUERY hToken = sec.OpenProcessToken (process, token_access_flags) debug_priv = sec.LookupPrivilegeValue (None, sec.SE_DEBUG_NAME) print "Debug is", priv_status (hToken, debug_priv) privs = [(debug_priv, sec.SE_PRIVILEGE_ENABLED)] sec.AdjustTokenPrivileges (hToken, 0, privs) print "Debug is", priv_status (hToken, debug_priv) > Just out of curiosity, is there a reason a python module like os > couldn't have a universal terminateProcess type function, that works > on all systems? Something like os.listdir seems to work really well > everywhere. Maybe killing processes is too complicated for this? Not to say that there could never be one, but I suspect that the difference of APis and the number of corner cases makes it a daunting task for maintenance. The code would have to work on every platform Python works on -- which is no small number -- and would have to be maintained across the many and varied changes on each of those platforms. Still, if you think you're in with a chance, go ahead and offer :) Let us know if the DEBUG priv thing works or not. TJG From kyosohma at gmail.com Mon Jun 4 10:35:33 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Mon, 04 Jun 2007 07:35:33 -0700 Subject: Using pyTTS with other languages. In-Reply-To: References: Message-ID: <1180967733.566489.128430@h2g2000hsg.googlegroups.com> On Jun 4, 8:17 am, simon kagwe wrote: > Hi, > > I would like to create a TTS program for a local (Kenyan) language. I have > installed pyTTS on my computer and it works perfectly with English sentences. > However, my language is very different from English (sylabbles, pronounciation > etc.) How can I go about having a TTS program that correctly speaks my language? > Can pyTTS do this? > > I need all the help I can get. > > Regards, > Simon. Hi Simon, I am pretty sure pyTTS can do this. It has a method to tell it how to pronounce words. See the following article: http://www.cs.unc.edu/~parente/tech/tr02.shtml It describes how to use mis-spelled words to force correct pronunciation as well as how to do it with XML. Mike From jimxu at google.com Tue Jun 12 14:13:31 2007 From: jimxu at google.com (Yongjian Xu) Date: Tue, 12 Jun 2007 11:13:31 -0700 Subject: Forgetting an import In-Reply-To: References: <1181666164.640868.225130@i38g2000prf.googlegroups.com> Message-ID: <9c09a1210706121113q49a17994teb9283b9d10225c4@mail.gmail.com> ipython supports deepreload which will recompile the bytecode from the file no matter what. You can set the option up in ipython and use it. It requires no exit to the current env. Jim On 6/12/07, Larry Bates wrote: > > HMS Surprise wrote: > > I imported a set of functions from a file I wrote to interpreter > > shell: > > > > from myFile import * > > > > Now if I change functions in this file how can I make python forget it > > so I can force a fresh import? > > > > thanx, > > > > jh > > > While there may be ways of doing this, I have found that you are much > better off opening another window and run your script from the bare > OS. It will help you catch problems that you may miss in the > interpreter shell. It also solves this problem completely. > > -Larry > -- > http://mail.python.org/mailman/listinfo/python-list > -- Yongjian (Jim) Xu =========== Sysops -------------- next part -------------- An HTML attachment was scrubbed... URL: From cam.ac.uk at mh391.invalid Sat Jun 23 07:52:16 2007 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Sat, 23 Jun 2007 12:52:16 +0100 Subject: PEP 3107 and stronger typing (note: probably a newbie question) In-Reply-To: References: <1182448413.966430.299590@m36g2000hse.googlegroups.com> <7xhcp0fom4.fsf@ruckus.brouhaha.com> <87tzt0tgol.fsf@benfinney.id.au> <1182533987.715191.159850@m36g2000hse.googlegroups.com> Message-ID: Eduardo "EdCrypt" O. Padoan wrote: > On 6/22/07, John Nagle wrote: >> Paul Boddie wrote: >> > P.S. I agree with the sentiment that the annotations feature of Python >> > 3000 seems like a lot of baggage. Aside from some benefits around >> > writing C/C++/Java wrappers, it's the lowest common denominator type >> > annotation dialect that dare not be known as such, resulting from a >> > lack of consensus about what such a dialect should really do, haunted >> > by a justified fear of restrictive side-effects imposed by a more >> > ambitious dialect (eg. stuff you get in functional languages) on >> > dynamically-typed code. I don't think the language should be modified >> > in ways that only provide partial, speculative answers to certain >> > problems when there's plenty of related activity going on elsewhere >> > that's likely to provide more complete, proven answers to those >> > problems. >> >> I agree. It's a wierd addition to the language. It looks like >> a compromise between the "no declarations" position and the "make >> the language strongly typed" position. But it's so ill-defined that >> it's not helpful, and worse than either extreme. The whole >> approach is antithetical to the "only one way to do it" concept. >> This could lead to misery when different libraries use >> incompatible type annotation systems, which is not going to be fun. >> >> Python made it this far without declarations, and programmers >> seem to like that. We need to get Python performance up, and >> the ShedSkin/Psyco restrictions seem to be enough to allow that. >> Type annotations don't seem to solve any problem that really needs >> to be solved. >> >> The main advantage of strongly typed systems is that more errors >> are detected at compile time. You pay for this in additional language >> baggage. PEP 3107 adds the excess baggage without providing the benefit >> of compile time checks. > > Remember that pure CPython has no different "compile time" and > runtiime. Yes, it does. -- Michael Hoffman From aahz at pythoncraft.com Mon Jun 11 22:16:25 2007 From: aahz at pythoncraft.com (Aahz) Date: 11 Jun 2007 19:16:25 -0700 Subject: Python's "only one way to do it" philosophy isn't good? References: <1181368143.874341.273140@r19g2000prf.googlegroups.com> Message-ID: In article , Terry Reedy wrote: > >"James Stroud" wrote in message >news:E5vai.858$TC1.722 at newssvr17.news.prodigy.net... >| Terry Reedy wrote: >| > In Python, you have a choice of recursion (normal or tail) >| >| Please explain this. > >I am working on a paper for Python Papers that will. It was inspired by >the question 'why doesn't Python do tail-recursion optimization'. ...with the proof contained in the margins? -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "as long as we like the same operating system, things are cool." --piranha From rustompmody at gmail.com Tue Jun 26 14:13:38 2007 From: rustompmody at gmail.com (Rustom Mody) Date: Tue, 26 Jun 2007 23:43:38 +0530 Subject: Indenting in Emacs In-Reply-To: <874pkvvn7g.fsf@pobox.com> References: <1182415666.423187.274240@u2g2000hsc.googlegroups.com> <87bqf8nagp.fsf@pobox.com> <874pkvvn7g.fsf@pobox.com> Message-ID: Ive been struggling with this same question -- which python mode -- for a while but not getting anywhere! I understand (from the emacs list) that the new python mode has better support for debugging (pdbtrack in addition to pdb) but dont know much more. On 6/26/07, John J. Lee wrote: > Michael Hoffman writes: > > > John J. Lee wrote: > >> Eugene Morozov writes: > >> > >>> Steven W. Orr ?????: > >>> > Ok. I'm not stupid but I do not see a 4.78 anywhere even though I > >>> see refs > >>>> from google. I have 4.75 The SVN tree doesn't seem to even have > >>>> that. > >>>> > >>>> I checked the latest copy out from sourceforge and that was 4.75 too. > >>>> > >>>> Can someone please tell me where to find the latest? > >>>> > >>> It's from Emacs 22. > >> > >> Note that's a different python-mode to the old one that lives on SF. > >> Yes, there are now two of them. > > > > Which one is better? > > I've not noticed a big difference in usability. > > I find indentation with the new mode very mildly more annoying than > the old mode. YMMV on that. There are probably annoyances with the > old mode that I've now forgotten about. > > I'm told by an emacs developer at work that the new mode is more > emacsy in its implementation -- I don't know in what ways exactly, but > presumably that, plus the fact that the new mode is included with > emacs 22, will mean that it's likely to work better with other emacs > code (not that I ever had much problem with the old mode -- but then I > didn't push it very far). > > > John > -- > http://mail.python.org/mailman/listinfo/python-list From m_tayseer82 at yahoo.com Wed Jun 20 17:58:13 2007 From: m_tayseer82 at yahoo.com (Mohammad Tayseer) Date: Wed, 20 Jun 2007 14:58:13 -0700 (PDT) Subject: For Python programmers in Egypt Message-ID: <917152.24081.qm@web31103.mail.mud.yahoo.com> Dear Pythonistas My company, Silverkey, is going to hold a demo day on 07/07/2007. We are going to make a comparison between static languages and dynamic languages. I'm going to represent the dynamic languages side. If you are in Egypt, we will be happy to meet you. http://www.demoday.us/ Thanks Mohammad Tayseer http://spellcoder.com/blogs/tayseer --------------------------------- It's here! Your new message! Get new email alerts with the free Yahoo! Toolbar. -------------- next part -------------- An HTML attachment was scrubbed... URL: From gregpinero at gmail.com Mon Jun 25 15:17:40 2007 From: gregpinero at gmail.com (gregpinero at gmail.com) Date: Mon, 25 Jun 2007 19:17:40 -0000 Subject: Python SVN down? Message-ID: <1182799060.612115.75490@n60g2000hse.googlegroups.com> Going to this URL: http://svn.python.org/view/ It gives me an error: Unable to connect Firefox can't establish a connection to the server at svn.python.org. And using SVN as so: $ svn checkout http://svn.python.org/projects/python/trunk/ ~/ python_work/ svn: PROPFIND request failed on '/projects/python/trunk' svn: PROPFIND of '/projects/python/trunk': could not connect to server (http://svn.python.org) Gives me the above error. Any ideas? I didn't see an announcement about this anywhere. -Greg From doug at alum.mit.edu Fri Jun 29 09:33:45 2007 From: doug at alum.mit.edu (Douglas Alan) Date: Fri, 29 Jun 2007 09:33:45 -0400 Subject: Python's "only one way to do it" philosophy isn't good? References: <7x3b0nmkk6.fsf@ruckus.brouhaha.com> <7xejjzmk7u.fsf@ruckus.brouhaha.com> <7xy7i7xjl5.fsf@ruckus.brouhaha.com> <1182872972.417776.78650@o11g2000prd.googlegroups.com> <7xtzsuy7fe.fsf@ruckus.brouhaha.com> <1182955743.076746.114790@i38g2000prf.googlegroups.com> <877ipn9gff.fsf@mulj.homelinux.net> Message-ID: Hrvoje Niksic writes: > Douglas Alan writes: >> I think you overstate your case. Lispers understand iteration >> interfaces perfectly well, but tend to prefer mapping fuctions to >> iteration because mapping functions are both easier to code (they >> are basically equivalent to coding generators) and efficient (like >> non-generator-implemented iterators). The downside is that they are >> not quite as flexible as iterators (which can be hard to code) and >> generators, which are slow. > Why do you think generators are any slower than hand-coded iterators? Generators aren't slower than hand-coded iterators in *Python*, but that's because Python is a slow language. In a fast language, such as a Lisp, generators are like 100 times slower than mapping functions. (At least they were on Lisp Machines, where generators were implemented using a more generator coroutining mechanism [i.e., stack groups]. *Perhaps* there would be some opportunities for more optimization if they had used a less general mechanism.) CLU, which I believe is the language that invented generators, limited them to the power of mapping functions (i.e., you couldn't have multiple generators instantiated in parallel), making them really syntactic sugar for mapping functions. The reason for this limitation was performance. CLU was a fast language. |>oug From kennerly at finegamedesign.com Mon Jun 18 22:49:04 2007 From: kennerly at finegamedesign.com (Ethan Kennerly) Date: Mon, 18 Jun 2007 19:49:04 -0700 Subject: Does altering a private member decouple the property's value? Message-ID: <20070619025553.EDCA71E4007@bag.python.org> Hello, There are a lot of Python mailing lists. I hope this is an appropriate one for a question on properties. I am relatively inexperienced user of Python. I came to it to prototype concepts for videogames. Having programmed in C, scripted in Unix shells, and scripted in a number of proprietary game scripting languages, I'm impressed at how well Python meets my needs. In almost all respects, it does what I've been wishing a language would do. One example is properties. I really like properties for readonly attributes, and their ability to make the interface more elegant, by hiding uninteresting methods (like dumb get/set accessors). As a user interface designer, I respect how this may prevent the programmer's deluge of unimportant information. I also value the ease of refactoring, which is a frequent task in my prototypes. But a gotcha bit me in the behavior of properties that I didn't expect. If another function accesses an underlying data member of a property, then the data member returned by the property is no longer valid. Here is a session example. PythonWin 2.4.3 - Enthought Edition 1.0.0 (#69, Aug 2 2006, 12:09:59) [MSC v.1310 32 bit (Intel)] on win32. Portions Copyright 1994-2004 Mark Hammond (mhammond at skippinet.com.au) - see 'Help/About PythonWin' for further copyright information. >>> class a_class: ... def __init__( self ): self.__p = None ... def __set_p( self, new_p ): self.__p = new_p ... def reset( self ): self.__p = None ... p = property( lambda self: self.__p, __set_p ) ... >>> a = a_class() >>> a.p >>> a.p = 1 >>> a.p 1 >>> a.reset() >>> a.p 1 Although the underlying value was reset, the property was not reset! Instead, if the property is edited, then all is fine. >>> class a_class: ... def __init__( self ): self.__p = None ... def __set_p( self, new_p ): self.__p = new_p ... def reset( self ): self.p = None # Property, not the private member ... p = property( lambda self: self.__p, __set_p ) ... >>> a = a_class() >>> a.p >>> a.p = 1 >>> a.reset() >>> a.p I had wanted to access the private data member in the class to avoid side-effects of the set method. Can someone show me how to reference the data member underlying a property and update the property without calling the property set method? By the way, I thought maybe that a variable outside of an __init__ method would be static, but as far as I can tell, it is dynamic. For example, the following class appeared equivalent to the above for tests. >>> class a_class: ... __p = None # No __init__ ... def __set_p( self, new_p ): self.__p = new_p ... def reset( self ): self.p = None ... p = property( lambda self: self.__p, __set_p ) ... >>> a = a_class() >>> a.p >>> a.p = 1 >>> a.reset() >>> a.p >>> I preferred not having the __init__ for this example and my prototype, because I wasn't doing anything fancy, and it meant one less method that the programmer needed to see. Again, the interface is cleaner. But does this cause an error for derived classes that would use the private data member? Without the __init__ method, is the derived class' __p equal to the base class' __p? I thought maybe the class was being referenced instead of the instance, but a second object had a different value. >>> b = a_class() >>> b.p >>> b.p = 2 >>> b.p 2 >>> b.reset() >>> a.p >>> a.p = 1 >>> a.p 1 >>> b.p >>> b.p = 2 >>> b.reset() >>> a.p 1 >>> b.p >>> Also properties don't show up in the dictionary if no assignment has been made, but once a property's assignment has been called, the property appears. An example follows: >>> import pprint >>> pprint.pprint( a.__dict__ ) {'p': 1} >>> pprint.pprint( b.__dict__ ) {'p': None} >>> c = a_class() >>> pprint.pprint( c.__dict__ ) {} >>> c.p >>> pprint.pprint( c.__dict__ ) {} Is that dictionary population behavior for detecting an uninitialized property? Thanks for your help. When my feet are properly wet, I look forward to contributing to the community. -- Ethan Kennerly From chokshi.jaydeep at gmail.com Mon Jun 25 13:02:57 2007 From: chokshi.jaydeep at gmail.com (Mozis) Date: Mon, 25 Jun 2007 10:02:57 -0700 Subject: How to change default behavior Message-ID: <1182790977.163231.179040@m37g2000prh.googlegroups.com> Greetings, I am using pyuniit for my test cases. I want to change the default behavior to report the errors. I believe it calls TextTestRunner class before calling my test_class(which is child of TestCase class) to set up the framework for error reporting and so on. I can see that it makes the "result" variable of type _TextTestResult class. So while reporting errors, it calls functions of this class. I want to overload the TextTestRunner class and want to make result of type my class, so in further linage of function calls it should call functions of my class instead of _TextTestResult. But I was not able to find out how does python test framework calls TextTestRunner automatically. Somehow I want to make it call my overloaded class. Could anybody help me out. Thanks in anticipation. JD From horpner at yahoo.com Mon Jun 25 11:27:25 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Mon, 25 Jun 2007 15:27:25 GMT Subject: Collections of non-arbitrary objects ? References: <1182449993.223262.229500@z28g2000prd.googlegroups.com> <87k5twx4hf.fsf@benfinney.id.au> <1182559502.069773.321620@i38g2000prf.googlegroups.com> <87wsxvrzsj.fsf@benfinney.id.au> <1182620734.940718.196520@e16g2000pri.googlegroups.com> <467ed491$0$27132$426a34cc@news.free.fr> <1182780863.067601.89320@d30g2000prg.googlegroups.com> Message-ID: On 2007-06-25, walterbyrd wrote: > BTW: I think polymorphism is great and all. But it does have > (and IMO should have) it's limitations. For example, I don't > think you can divide a string by another string. It might be a pointless new spelling for the .split method. x = 'Smith, Ted, 15 Smedly Rd." last, first, street = x / ', ' Tongue-in-cheekily-yours, -- Neil Cerutti Strangely, in slow motion replay, the ball seemed to hang in the air for even longer. --David Acfield From NunezD at gmail.com Fri Jun 22 14:00:27 2007 From: NunezD at gmail.com (hiro) Date: Fri, 22 Jun 2007 18:00:27 -0000 Subject: comparing two lists and returning "position" In-Reply-To: <1182535097.054481.296050@p77g2000hsh.googlegroups.com> References: <1182481876.028589.71710@x35g2000prf.googlegroups.com> <7xvedg4n2d.fsf@ruckus.brouhaha.com> <467b624e$0$16271$c30e37c6@lon-reader.news.telstra.net> <1182493019.795629.108860@w5g2000hsg.googlegroups.com> <1182534010.884992.119690@u2g2000hsc.googlegroups.com> <1182535097.054481.296050@p77g2000hsh.googlegroups.com> Message-ID: <1182535227.400136.199590@m36g2000hse.googlegroups.com> On Jun 22, 1:58 pm, hiro wrote: > On Jun 22, 1:56 pm, Marc 'BlackJack' Rintsch wrote: > > > > > In <1182534010.884992.119... at u2g2000hsc.googlegroups.com>, hiro wrote: > > > Hi once again, Charles.. I have tried your approach in my data set l2 > > > and it keeps crashing on me, > > > bare in mind that I have a little over 10 million objects in my list > > > (l2) and l1 contains around 4 thousand > > > objects.. (i have enough ram in my computer so memory is not a > > > problem) > > > > python 2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit > > > (Intel)] on win32 > > > > error is : ValueError: list.index(x): x not in list > > > So you are saying you get this error with the value of `x` actually in the > > list!? Somehow hard to believe. > > > Ciao, > > Marc 'BlackJack' Rintsch > > yes I do I doubled, trippled check my data already (even doing a search by hand using vim) and the data is fine. Still looking into it though From deets at nospam.web.de Wed Jun 6 08:59:00 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 06 Jun 2007 14:59:00 +0200 Subject: PATH or PYTHONPATH under Windows ??? References: <90155$4665db45$d443bb3a$16812@news.speedlinq.nl> Message-ID: <5cnpckF324q4iU1@mid.uni-berlin.de> > but why is everybody alwasy talking about the "environment variable > PYTHONPATH" ?? Because that variable can be used to additionally customize the search path. But that doesn't imply that it is _all_ there is about python search paths - and it would be pretty crappy if it was, because you can have different installations of python on one machine, and having one PYTHONPATH alone would break them, making just one run properly. Diez From erikwickstrom at gmail.com Sat Jun 2 13:20:51 2007 From: erikwickstrom at gmail.com (erikcw) Date: Sat, 02 Jun 2007 17:20:51 -0000 Subject: SMTPlib Sender Refused? Message-ID: <1180804851.201748.215890@k79g2000hse.googlegroups.com> Hi, I'm trying to send an email message with python, and I'm getting this error: Traceback (most recent call last): File "wa.py", line 430, in ? main() File "wa.py", line 425, in main smtp.sendmail(fromaddr, to, msg.encode('utf-8')) File "/usr/local/lib/python2.4/smtplib.py", line 680, in sendmail raise SMTPSenderRefused(code, resp, from_addr) smtplib.SMTPSenderRefused: (503, 'sender already given', 'me at mydomain.com') What is causing this? Thanks! Erik From winter at biotec.tu-dresden.de Fri Jun 15 14:46:01 2007 From: winter at biotec.tu-dresden.de (Christof Winter) Date: Fri, 15 Jun 2007 20:46:01 +0200 Subject: Want to learn Python In-Reply-To: <1181907696.878873.214760@i13g2000prf.googlegroups.com> References: <1181907696.878873.214760@i13g2000prf.googlegroups.com> Message-ID: <5dg53rF34cjujU1@mid.dfncis.de> Amol wrote: > Hi, I want to learn Python in less than a month which resources should > I use. I prefer to read books . Please give me a list of *recognized* > resources. Thank You all This is an excellent resource: http://rgruet.free.fr/PQR24/PQR2.4.html Although it's quite different from a book, I must admit. Cheers, Christof From nagle at animats.com Sat Jun 9 13:58:57 2007 From: nagle at animats.com (John Nagle) Date: Sat, 09 Jun 2007 17:58:57 GMT Subject: Python's "only one way to do it" philosophy isn't good? In-Reply-To: <5cvf62F32relhU1@mid.individual.net> References: <1181368143.874341.273140@r19g2000prf.googlegroups.com> <5cvf62F32relhU1@mid.individual.net> Message-ID: Bjoern Schliessmann wrote: > Gabriel Genellina wrote: > > >>For what I can >>remember of my first love (Physics): if you have a small ball >>moving inside a spherical cup, it would be almost crazy to use >>cartesian orthogonal coordinates and Newton's laws to solve it - >>the "obvious" way would be to use spherical coordinates and the >>Lagrangian formulation (or at least I hope so Having actually solved that problem in simulation, I can report that it's easier in Cartesian coordinates. I used to use this as a test of Falling Bodies, one of the first physics engines that really worked on the hard cases. Spherical coordinates seem attractive until you have to deal with friction between the ball and cup. The ball is rotating, too, and may be slipping with respect to the cup. Then the simple Physics 101 approach isn't so simple any more. John Nagle Animats From jhon1875 at yahoo.com Sat Jun 9 10:37:48 2007 From: jhon1875 at yahoo.com (jhon1875 at yahoo.com) Date: Sat, 09 Jun 2007 07:37:48 -0700 Subject: Search Profiles - FREE! Intimate Dating. Start Chatting within seconds Message-ID: <1181399868.175180.80410@q19g2000prn.googlegroups.com> Meet Local Hotties Tonight! Check out the hot photo galleries... It is one of the most popular and respectable Dating Place filled with quality and sexy singles. Join us to hook up with them in your area for Romance, Flirt and Sexy Dating by online chat, cyber-fun, webcam, real- life hook-ups.... You won't be disappointed. Totally FREE ACCESS http://offr.biz/HLMAT302181UUAFBRV From apatheticagnostic at gmail.com Mon Jun 25 21:41:51 2007 From: apatheticagnostic at gmail.com (kaens) Date: Mon, 25 Jun 2007 21:41:51 -0400 Subject: Looking for an interpreter that does not request internet access In-Reply-To: References: Message-ID: <163f0ce20706251841o74cec5d8r559e9874f176d3cf@mail.gmail.com> On 6/25/07, James Alan Farrell wrote: > Hello, > I recently installed new anti-virus software and was surprised the > next time I brought up IDLE, that it was accessing the internet. > > I dislike software accessing the internet without telling me about it, > especially because of my slow dial up connection (there is no option > where I live), but also because I feel it unsafe. > > Can anyone recommend an interpreter that does not access the internet > when it starts (or when it is running, unless I specifically write a > program that causes it to do so, so as a browser)? > > James Alan Farrell > -- > http://mail.python.org/mailman/listinfo/python-list > On windows . . . hmm. Eclipse with pydev, python from the command-line, Crimson Editor (I think it has python support). I'm surprised that IDLE is accessing the internet - it's probably looking for updates or something, and you can probably turn it off. Eclipse checks for updates unless you tell it not to. FYI, although IDLE runs an interpreter, it is not an interpreter - it is an editor (I think so anyhow, I don't use it (find it clunky) and could be wrong) From "sergio\" at (none) Tue Jun 19 10:27:00 2007 From: "sergio\" at (none) (none) Date: Tue, 19 Jun 2007 15:27:00 +0100 Subject: HTMLParser.HTMLParseError: EOF in middle of construct In-Reply-To: References: <1182195498.16548.5.camel@localhost.localdomain> Message-ID: <4677e790$0$2840$a729d347@news.telepac.pt> Gabriel Genellina wrote: > En Mon, 18 Jun 2007 16:38:18 -0300, Sergio Monteiro Basto > escribi?: > >> Can someone explain me, what is wrong with this site ? >> >> python linkExtractor3.py http://www.noticiasdeaveiro.pt > test >> >> HTMLParser.HTMLParseError: EOF in middle of construct, at line 1173, >> column 1 >> >> at line 1173 of test file is perfectly normal . > > That page is not valid HTML - http://validator.w3.org/ finds 726 errors > in it. ok but my problem is not understand what is the specific problem at line 1173 > HTMLParser expects valid HTML - try a different tool, like > BeautifulSoup, which is specially designed to handle malformed pages. > > --Gabriel Genellina > From nagle at animats.com Sun Jun 10 12:20:10 2007 From: nagle at animats.com (John Nagle) Date: Sun, 10 Jun 2007 09:20:10 -0700 Subject: Python's "only one way to do it" philosophy isn't good? In-Reply-To: <1181475395.749525.185520@m36g2000hse.googlegroups.com> References: <1181368143.874341.273140@r19g2000prf.googlegroups.com> <1181475395.749525.185520@m36g2000hse.googlegroups.com> Message-ID: <%rVai.7520$u56.2110@newssvr22.news.prodigy.net> bruno.desthuilliers at gmail.com wrote: > On Jun 9, 12:16 pm, James Stroud wrote: > >>Terry Reedy wrote: >> >>>In Python, you have a choice of recursion (normal or tail) >> >>Please explain this. I remember reading on this newsgroup that an >>advantage of ruby (wrt python) is that ruby has tail recursion, implying >>that python does not. Does python have fully optimized tail recursion as >>described in the tail recursion Wikipedia entry? Under what >>circumstances can one count on the python interpreter recognizing the >>possibility for optimized tail recursion? >> > > > I'm afraid Terry is wrong here, at least if he meant that CPython had > tail recursion *optimization*. > > (and just for those who don't know yet, it's not a shortcoming, it's a > design choice.) > > From vinjvinj at gmail.com Tue Jun 26 11:17:06 2007 From: vinjvinj at gmail.com (vj) Date: Tue, 26 Jun 2007 08:17:06 -0700 Subject: Help needed with translating perl to python In-Reply-To: <1182870250.890390.28970@g37g2000prf.googlegroups.com> References: <1182870250.890390.28970@g37g2000prf.googlegroups.com> Message-ID: <1182871026.250669.296590@q69g2000hsb.googlegroups.com> I posted too soon: > Statement 1: > my $today = sprintf("%4s%02s%02s", [localtime()]->[5]+1900, > [localtime()]->[4]+1, [localtime()]->[3]) ; 1. is localtime the same as time in python? 2. What does -> ? do in perl? 3. What is 'my' > Statement 2: > my $password = md5_hex("$today$username") ; is md5_hex the same as md5.new(key).hexdigest() in python? > $msglen = bcdlen(length($msg)) ; 1. here the funciton is being called with the length of variable msg. However the function def below does not have any args > sub bcdlen { > my $strlen = sprintf("%04s", shift) ; > my $firstval = substr($strlen, 2, 1)*16 + substr($strlen, 3, 1) ; > my $lastval = substr($strlen, 0, 1)*16 + substr($strlen, 1, 1) ; > return chr($firstval) . chr($lastval) ; > > } 2. What does shift do above? 3. is the '.' operator just + in python? Thanks, Vineet From steve at holdenweb.com Fri Jun 1 07:12:13 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 01 Jun 2007 07:12:13 -0400 Subject: Delete a file from a CGI In-Reply-To: References: Message-ID: Matias Surdi wrote: > HI! > > I want to delete a file from a CGI, but I always get a Permission denied > error. > > I've tryed this after creating the file (from a normal script): > > os.chmod(".lock",stat.S_IMODE(stat.S_IRWXU | stat.S_IRWXO | stat.S_IRWXG)) > os.chown(".lock",pwd.getpwnam("nobody")[2],pwd.getpwnam("nobody")[3]) > > but the CGI still can't delete the file. > > I will appreciate very much your help. > > Thanks a lot. > > How was the file created in the first place? If you don't have permissions to delete it you may well not have permissions to reown it or change its permissions either! regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden ------------------ Asciimercial --------------------- Get on the web: Blog, lens and tag your way to fame!! holdenweb.blogspot.com squidoo.com/pythonology tagged items: del.icio.us/steve.holden/python All these services currently offer free registration! -------------- Thank You for Reading ---------------- From gagsl-py2 at yahoo.com.ar Mon Jun 11 16:50:36 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 11 Jun 2007 17:50:36 -0300 Subject: Link Dictionary References: <1181593466.934730.299660@i38g2000prf.googlegroups.com> Message-ID: En Mon, 11 Jun 2007 17:24:26 -0300, anush shetty escribi?: > Hi, > I have two dictionaries > > dict1={'B8': set(['I8', 'H8', 'B2', 'B7', 'F8', 'C9', 'G8', 'B4', > 'B5', 'B6', 'C8', 'E8', 'D8', 'B3', 'A9', 'A8', 'C7', 'B9', 'A7', > 'B1']), 'B9': set(['I9', 'H9', 'A7', 'F9', 'B3', 'B6', 'G9', 'B4', > 'B5', 'C9', 'B7', 'E9', 'B1', 'B2', 'D9', 'A9', 'A8', 'C8', 'B8', > 'C7']), ... > > and > dict2= > {'I6': '0', 'H9': '9', 'I2': '0', 'E8': '0', 'H3': '0', 'H7': '0', > 'I7': '3', 'I4': '0', 'H5': '0', 'F9': '0', 'G7': '5', 'G6': '9', [...] > 'B2': '0', 'B3': '0', 'D6': '2', 'D7': '9', 'D4': '1', 'D5': '0', > 'B8': '0', 'B9': '1', 'D1': '0'} > > Now I want to create a dict which would have both the keys and values > to be of the corresponding values of dict2. > > Something like this: > > Eg. The first key in dict1 i.e. B8 as 0 (0 is the value of B8 in > dict2) mapped as set(['0','0','0',...]). Sets can't have duplicate elements, so set(['0','0','0'])==set(['0']) And dictionaries can't have duplicate keys either. What do you want to do exactly? How would your desired structure look like? -- Gabriel Genellina From rohitsethidce at gmail.com Sun Jun 3 14:54:21 2007 From: rohitsethidce at gmail.com (rohit) Date: Sun, 03 Jun 2007 11:54:21 -0700 Subject: monitoring the filesystem for changes In-Reply-To: <1180839676.119233.199860@x35g2000prf.googlegroups.com> References: <1180796900.356829.31050@i13g2000prf.googlegroups.com> <1180839676.119233.199860@x35g2000prf.googlegroups.com> Message-ID: <1180896861.674525.296550@o11g2000prd.googlegroups.com> hello well in my implementation of readdirectorychangesw i am using threading that is multiple programs run simultaneously each program monitoring one drive for changes. is their a way around this...one program for all drives? thanks rohit From tjreedy at udel.edu Thu Jun 7 14:18:13 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 7 Jun 2007 14:18:13 -0400 Subject: Integer division References: <1181207216.890336.99990@r19g2000prf.googlegroups.com> Message-ID: "Sion Arrowsmith" wrote in message news:Y9z*GPFMr at news.chiark.greenend.org.uk... | jm.suresh at no.spam.gmail.com wrote: | > 3/2 => 1 # Usual behavior | > some_func(3, 2) => 2 # Wanted | | def some_func(a, b): | return -(-a/b) | | And people complain about Python's behaviour regarding division of | negative integers. Nice. This goes on my 'why didn't I think of that' list;-) I was thinking of the rather pedestrian d,r = divmod(a,b) if r: d+=1 tjr From squabbit8 at gmail.com Sat Jun 30 02:31:26 2007 From: squabbit8 at gmail.com (felix seltzer) Date: Sat, 30 Jun 2007 00:31:26 -0600 Subject: good matlab interface Message-ID: Does any one know of a good matlab interface? I would just use scipy or numpy, but i also need to use the matlab neural network functions. I have tried PyMat, but am having a hard time getting it to install correctly. For that mater, a good neural net module for python would work just as well as a good matlab interface. Any suggestions? -felix -------------- next part -------------- An HTML attachment was scrubbed... URL: From peter.mosley at talk21.com Wed Jun 20 06:59:27 2007 From: peter.mosley at talk21.com (peter) Date: Wed, 20 Jun 2007 03:59:27 -0700 Subject: DFW Pythoneers Meeting THIS Saturday In-Reply-To: References: <1182325553.232470.205970@q75g2000hsh.googlegroups.com> Message-ID: <1182337167.504241.131530@m36g2000hse.googlegroups.com> > It says right in the subject line! DFW. If you don't know what DFW > means, then it's probably not your local area. Precisely From twisted0n3 at gmail.com Wed Jun 20 16:49:52 2007 From: twisted0n3 at gmail.com (Twisted) Date: Wed, 20 Jun 2007 20:49:52 -0000 Subject: The Modernization of Emacs: terminology buffer and keybinding In-Reply-To: <85zm2ufjpb.fsf@lola.goethe.zz> References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182272495.990807.99110@a26g2000pre.googlegroups.com> <87tzt3ihev.fsf@kobe.laptop> <1182370216.961241.6960@n60g2000hse.googlegroups.com> <85zm2ufjpb.fsf@lola.goethe.zz> Message-ID: <1182372592.803332.288260@u2g2000hsc.googlegroups.com> On Jun 20, 4:35 pm, David Kastrup wrote: > Twisted writes: > > On the other hand, being actively beginner-hostile leads to nobody > > adopting the tool. Then again, if you don't mind being the last > > generation that'll ever use it, then I guess you're okay with > > that. If it suits its existing users, the rest of us will just > > continue to use something else. > > > I continue to suspect that there's an ulterior motive for making and > > keeping certain software actively beginner-hostile; a certain macho > > elitism also seen with light aircraft pilots and commented on at > >www.asktog.com(exact URL escapes me; sorry). > > You are babbling. No, I am not. You, however, are being gratuitously insulting. > Emacs is amazingly beginner-friendly for the power and flexibility it > provides. [snip] That's a joke, right? I tried it a time or two. Every time it was rapidly apparent that doing anything non-trivial would require consulting a cheat sheet. The printed-out kind, since navigating to the help and back without already having the help displayed and open to the command reference was also non-trivial. Four hours of wasted time later, with zero productivity to show for it, I deleted it. The same thing happened again, so it wasn't a bad day or a fluke or a one-off or the particular version, either. From mccredie at gmail.com Fri Jun 22 13:44:41 2007 From: mccredie at gmail.com (Matimus) Date: Fri, 22 Jun 2007 17:44:41 -0000 Subject: howto run a function w/o text output? In-Reply-To: <1182531384.017220.218070@w5g2000hsg.googlegroups.com> References: <1182531384.017220.218070@w5g2000hsg.googlegroups.com> Message-ID: <1182534281.251770.62790@a26g2000pre.googlegroups.com> On Jun 22, 9:56 am, dmitrey wrote: > hi all, > I have a > y = some_func(args) > statement, and the some_func() produces lots of text output. Can I > somehow to suppress the one? > Thx in advance, D. [code] import sys import os sys.stdout = open(os.devnull,"w") [/code] From dfabrizio51 at gmail.com Mon Jun 4 12:16:11 2007 From: dfabrizio51 at gmail.com (chewie54) Date: Mon, 04 Jun 2007 16:16:11 -0000 Subject: python for EE CAD program In-Reply-To: <5cinkhF30nk9aU1@mid.uni-berlin.de> References: <1180964104.685598.21330@n4g2000hsb.googlegroups.com> <5cik0mF30e4avU1@mid.uni-berlin.de> <1180967112.693545.64270@p77g2000hsh.googlegroups.com> <5cinkhF30nk9aU1@mid.uni-berlin.de> Message-ID: <1180973771.580717.63840@m36g2000hse.googlegroups.com> On Jun 4, 10:58 am, "Diez B. Roggisch" wrote: > > Hello Diez, > > > I did look at PythonCad but the distribution and install methods for > > Windows is not user freindly. Since the public domain software, I > > don't think they protect the source code either. > > The subject of code obfuscation in python has been beaten to death quite a > few times on this list, do a search to find anything you want to know. > > In a nutshell: forget about it. it's not worth it, difficult to accomplish > due to the dynamic nature of python and to be brutally honest: more or less > nothing you can come up with in your own code is really worth looking at > anyway. That's not saying that you can't code, just that more or less > everything one programs is trivial and only of value in the actual context > it was written in. So nobody is really interested in ripping stuff out. > > diez Your opinions are noted, thank you, but I don't agree with you. There are portions of the code that are under review for patents and as such need to be protected. I'm investigating whether Python is the right language to use for a commercial CAD application. While I think Python is a great scripting language, there seems to limitations with regards to packaging and distributing programs. From python at jayloden.com Tue Jun 19 01:17:38 2007 From: python at jayloden.com (Jay Loden) Date: Tue, 19 Jun 2007 01:17:38 -0400 Subject: Does altering a private member decouple the property's value? In-Reply-To: <46776119.20008@jayloden.com> References: <1hzx8yb.t6r2y71wuilpzN%aleax@mac.com> <46776119.20008@jayloden.com> Message-ID: <467766F2.4090302@jayloden.com> Jay Loden wrote: > Can you elaborate (or just point me to a good doc) on what > you mean by an "old style" class versus the new style? I > learned Python (well, am still learning) from an older book, > and I just want to make sure that I'm using the preferred method. Answering my own question, I know, but Google and the right keywords is a wonderful thing. In case anyone else is interested: http://www.python.org/doc/newstyle.html -Jay From sebastien.abeille at gmail.com Fri Jun 29 07:30:19 2007 From: sebastien.abeille at gmail.com (sebastien.abeille at gmail.com) Date: Fri, 29 Jun 2007 11:30:19 -0000 Subject: It is not possible to create a recursive function over a pyGTK treeStore Message-ID: <1183116619.785972.175720@k29g2000hsd.googlegroups.com> Hello, I would like to create a minimalist file browser using pyGTK. Having read lot of tutorials, it seems to me that that in my case, the best solution is to have a gtk.TreeStore containing all the files and folders so that it would map the file system hierarchy. I wrote a recursive function that would go through the file system tree. My problem is that a sub-node of a gtk.TreeStore is not a gtk.TreeStore, but a gtk.TreeIter. And gtk.treeter has almost no functions I would be able to use (like "append") Therefore I can not explore the whole file system. Do you have another way so that I would be able to put all the file system hierarchy into a gtk.TreeStore? I was quite happy with my recursive solution ... =================================== code : #!/usr/bin/env python import pygtk pygtk.require('2.0') import gtk, gobject, os prefdir="/tmp/a" class InfoModele: def matchPathTreetoModelTree(self, path, treeStoreNode): files = [f for f in os.listdir(path) if f[0] <> '.'] for i in range(len(files)): if os.path.isfile(path+'/'+files[i]): print path+'/'+files[i]+" is a file" treeStoreNode.append( None, (path+'/'+files[i], None) ) if os.path.isdir(path+'/'+files[i]): #is a directory, go recursively print path+'/'+files[i]+" is a directory" mother = self.tree_store.append( None, (path+'/'+files[i], None) ) self.matchPathTreetoModelTree(path+'/'+files[i], mother) def __init__(self): self.tree_store = gtk.TreeStore( gobject.TYPE_STRING, gobject.TYPE_STRING) path=prefdir self.matchPathTreetoModelTree(prefdir, self.tree_store) if __name__ == "__main__": i=InfoModele() ================================= file system : a |-ab/ |-abc/ |-abcd ================================ Program output : /tmp/a/ab is a directory /tmp/a/ab/abc is a file Traceback (most recent call last): File "question.py", line 28, in i=InfoModele() File "question.py", line 25, in __init__ self.matchPathTreetoModelTree(prefdir, self.tree_store) File "question.py", line 20, in matchPathTreetoModelTree self.matchPathTreetoModelTree(path+'/'+files[i], mother) File "question.py", line 16, in matchPathTreetoModelTree treeStoreNode.append( None, (path+'/'+files[i], None) ) AttributeError: 'gtk.TreeIter' object has no attribute 'append' From papalagi.pakeha at gmail.com Tue Jun 12 07:03:21 2007 From: papalagi.pakeha at gmail.com (Papalagi Pakeha) Date: Tue, 12 Jun 2007 23:03:21 +1200 Subject: Autocompletion in interactive mode doesn't work in 2.5.1 In-Reply-To: <1181637926.874587.150270@a26g2000pre.googlegroups.com> References: <1181637926.874587.150270@a26g2000pre.googlegroups.com> Message-ID: <343d1bca0706120403y15900af3uc07bd7211d087e62@mail.gmail.com> On 6/12/07, jitudon at hotmail.com wrote: > On Jun 12, 9:36 am, "Papalagi Pakeha" wrote: > > Hi all, > > > > How can I turn on autocompletion when I push in python 2.5.1 > > interactive mode? E.g. to give me a list of all methods and attributes > > of a given object. > > http://docs.python.org/lib/module-rlcompleter.html That's it! Thanks heaps :-) PaPa From stefan.behnel-n05pAM at web.de Tue Jun 26 02:06:36 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Tue, 26 Jun 2007 08:06:36 +0200 Subject: Python Info. In-Reply-To: <1182836595.006152.87320@j4g2000prf.googlegroups.com> References: <1182836595.006152.87320@j4g2000prf.googlegroups.com> Message-ID: <4680ACEC.7060500@web.de> Brandon wrote: > Check it out: www.BrandonsMansion.com Why? Stefan From lucaberto at libero.it Wed Jun 20 11:44:59 2007 From: lucaberto at libero.it (luca72) Date: Wed, 20 Jun 2007 08:44:59 -0700 Subject: QPainter Message-ID: <1182354299.328151.193300@j4g2000prf.googlegroups.com> Hello using qt3 i do the follow for paint some line in a frame gr = QPainter(self.frame3) gr drawLine(30,10,30,490) and the line is draw. Whit qt4 : gr = QtGui.QPainter(self.frame3) #gr.setPen(QtGui.QPen(QtCore.Qt.black, 1, QtCore.Qt.SolidLine)) gr.drawLine(30,10,30,490) and nothing is draw but i have no error The frame is the same with the same dimension and relative dimension. where is the error? Regards Luca From steve at REMOVE.THIS.cybersource.com.au Fri Jun 22 07:46:32 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Fri, 22 Jun 2007 21:46:32 +1000 Subject: configparser shuffles all sections ? References: Message-ID: On Fri, 22 Jun 2007 09:28:42 +0200, stef wrote: > hello, > > I just used configparser for the first time and discovered that it > shuffled all my sections, > and the contents of the sections too. > > This makes human manipulation of the file impossible. Having read the rest of this thread, I think Stef is not worried about *human* manipulation. There is nothing stopping a human from editing the INI file in a text editor, except perhaps the sheer size of the file. But what I think is the actual problem is that, having read the INI file into dictionaries, the order is lost. For that matter, so are comments, and probably whitespace. That makes it impractical to generate an INI file, then read it with configparser, make changes to the configparser data, then write it back to the INI file. Unfortunately, I don't think configparser can deal with that, and I'm not aware of any libraries that will. -- Steven From bdesth.quelquechose at free.quelquepart.fr Sat Jun 30 15:55:13 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sat, 30 Jun 2007 21:55:13 +0200 Subject: noob question How do I run a Python script. In-Reply-To: <1183051059.795931.299900@q75g2000hsh.googlegroups.com> References: <1183051059.795931.299900@q75g2000hsh.googlegroups.com> Message-ID: <4686448d$0$24956$426a74cc@news.free.fr> CarlP a ?crit : > How do I run a Python script. usually, it's: $ python /path/to/somescript.py arg1 argN on a command line prompt. > I have one that gmail loader needs to > run on my email box. Here's the script > > http://www.marklyon.org/gmail/cleanmbox.py > > I can't seem to find what I need to run it. I installed python, run > the interpreter and the script , but all it will do is say invalid > syntax. Am I right if I guess you did something like : bruno at bibi ~ $ python Python 2.4.3 (#1, Mar 12 2007, 23:32:01) [GCC 3.3.4 20040623 (Gentoo Linux 3.3.4-r1, ssp-3.3.2-2, pie-8.7.6)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> cleanmbox.py testmbox File "", line 1 cleanmbox.py testmbox ^ SyntaxError: invalid syntax >>> ?-) FWIW, I ran the script (the correct way) on a copy of a mozilla mbox dir, and it seemed to work. From doug at alum.mit.edu Thu Jun 28 01:20:49 2007 From: doug at alum.mit.edu (Douglas Alan) Date: Thu, 28 Jun 2007 01:20:49 -0400 Subject: Python's "only one way to do it" philosophy isn't good? References: <1182750077.570603.160240@q69g2000hsb.googlegroups.com> <7xir9cbm0g.fsf@ruckus.brouhaha.com> <7xejjzmk7u.fsf@ruckus.brouhaha.com> <7xy7i7xjl5.fsf@ruckus.brouhaha.com> <7x4pkt4xuz.fsf@ruckus.brouhaha.com> Message-ID: Dennis Lee Bieber writes: > But if these "macros" are supposed to allow one to sort of extend > Python syntax, are you really going to code things like > > macrolib1.keyword > everywhere? No -- I would expect that macros (if done the way that I would like them to be done) would work something like so: from setMacro import macro set, macro let let x = 1 set x += 1 The macros "let" and "set" (like all macro invocations) would have to be the first tokens on a line. They would be passed either the strings "x = 1" and "x += 1", or some tokenized version thereof. There would be parsing libraries to help them from there. For macros that need to continue over more than one line, e.g., perhaps something like let x = 1 y = 2 z = 3 set x = y + z y = x + z z = x + y print x, y, z the macro would parse up to when the indentation returns to the previous level. For macros that need to return values, a new bracketing syntax would be needed. Perhaps something like: while $(let x = foo()): print x |>oug From http Sun Jun 10 01:31:29 2007 From: http (Paul Rubin) Date: 09 Jun 2007 22:31:29 -0700 Subject: urllib2 - iteration over non-sequence References: <1181427526.996101.75230@m36g2000hse.googlegroups.com> <466B2AA7.3040704@websafe.com> <1181429903.533207.105730@p77g2000hsh.googlegroups.com> <7x3b10pnwq.fsf@ruckus.brouhaha.com> Message-ID: <7xtztggytq.fsf@ruckus.brouhaha.com> Gary Herron writes: > For simplicity, I'd still suggest my original use of readlines. If > and when you find you are downloading web pages with sizes that are > putting a serious strain on your memory footprint, then one of the other > suggestions might be indicated. If you know in advance that the page you're retrieving will be reasonable in size, then using readlines is fine. If you don't know in advance what you're retrieving (e.g. you're working on a crawler) you have to assume that you'll hit some very large pages with difficult construction. From http Tue Jun 26 13:03:33 2007 From: http (Paul Rubin) Date: 26 Jun 2007 10:03:33 -0700 Subject: Python's "only one way to do it" philosophy isn't good? References: <7x3b0nmkk6.fsf@ruckus.brouhaha.com> <1182750077.570603.160240@q69g2000hsb.googlegroups.com> <7xir9cbm0g.fsf@ruckus.brouhaha.com> <7xejjzmk7u.fsf@ruckus.brouhaha.com> <7xy7i7xjl5.fsf@ruckus.brouhaha.com> <1182872972.417776.78650@o11g2000prd.googlegroups.com> Message-ID: <7xtzsuy7fe.fsf@ruckus.brouhaha.com> Andy Freeman writes: > And he's wrong, at least as far as common lisp is concerned - map does > exactly that. > > http://www.lispworks.com/documentation/HyperSpec/Body/f_map.htm "sequence" there just means vectors and lists. > Map doesn't work on generators or iterators because they're not part > of the common lisp spec, but if someone implemented them as a library, > said library could easily include a map that handled them as well. Right, more scattered special purpose kludges instead of a powerful uniform interface. From oscartheduck at gmail.com Mon Jun 25 00:48:53 2007 From: oscartheduck at gmail.com (oscartheduck) Date: Mon, 25 Jun 2007 04:48:53 -0000 Subject: regular expressions eliminating filenames of type foo.thumbnail.jpg Message-ID: <1182746933.413693.103860@p77g2000hsh.googlegroups.com> Hi folks, I'm trying to alter a program I posted about a few days ago. It creates thumbnail images from master images. Nice and simple. To make sure I can match all variations in spelling of jpeg, and different cases, I'm using regular expressions. The code is currently: ----- #!/usr/bin/env python from PIL import Image import glob, os, re size = 128, 128 def thumbnailer(dir, filenameRx): for picture in [ p for p in os.listdir(dir) if os.path.isfile(os.path.join( dir,p)) and filenameRx.match(p) ]: file, ext = os.path.splitext(picture) im = Image.open (picture) im.thumbnail(size, Image.ANTIALIAS) im.save(file + ".thumbnail" + ext) jpg = re.compile(".*\.(jpg|jpeg)", re.IGNORECASE) thumbnailer(".", jpg) ----- The problem is this. This code outputs foo.thumbnail.jpg when ran, and when ran again it creates foo.thumbnail.thumbnail.jpg and so on, filling a directory. The obvious solution is to filter out any name that contains the term "thumbnail", which I can once again do with a regular expression. My problem is the construction of this expression. The relevant page in the tutorial docs is: http://docs.python.org/lib/re-syntax.html It lists (?>> m = re.search('(? References: <4662675b$1_5@news.bluewin.ch> <1180890214.317409.85100@w5g2000hsg.googlegroups.com> <4662FDC8.9080407@islandtraining.com> <46634BDC.7090104@freakmail.de> Message-ID: <49c87$4663c85e$83aef404$27480@news1.tudelft.nl> Gary Herron wrote: > Wildemar Wildenburger wrote: > >> Gary Herron wrote: >> >> >>> Of course not! Angles have units, commonly either degrees or radians. >>> >>> However, sines and cosines, being ratios of two lengths, are unit-less. >>> >>> >>> >>>> To understand it: sin() can't have dimensioned argument. It is can't >>>> to be - sin(meters) >>>> >>>> >>>> >>>> >>> No it's sin(radians) or sin(degrees). >>> >>> >>> >> NO! >> The radian is defined as the ratio of an arc of circumfence of a circle >> to the radius of the circle and is therefore *dimensionless*. End of story. >> http://en.wikipedia.org/wiki/Radian and esp. >> http://en.wikipedia.org/wiki/Radian#Dimensional_analysis >> >> *grunt* >> >> > No, not end-of-story. Neither of us are being precise enough here. To > quote from your second link: > "Although the radian is a unit of measure, it is a dimensionless > quantity." > > But NOTE: Radians and degrees *are* units of measure., however those > units are dimensionless quantities , i.e., not a length or a time etc. > > The arguments to sine and cosine must have an associated unit so you > know whether to interpret sin(1.2) as sine of an angle measured in > degrees or radians (or whatever else). > > Gary Herron > > > Sorry about entering the discussion so late, and not sure I repeat one of the messages. But can't we see it this way: radians / degrees (which one 360 or 400) are just mathematical scaling factors, like kilo, mega etc. If a wheel is turning around at 2*pi*100 [rad /sec] does something physical change is we leave the radian out the wheeel is turning at 100 [1/sec] No it's now called frequency, and has just some different scaling. SQRT of "rad/sec" ? Yes, in electronics the noise density is often expressed in [nV/SQRT(Hz)] cheers, Stef Mientki From showell30 at yahoo.com Wed Jun 20 08:02:51 2007 From: showell30 at yahoo.com (Steve Howell) Date: Wed, 20 Jun 2007 05:02:51 -0700 (PDT) Subject: SimplePrograms challenge In-Reply-To: Message-ID: <960689.22526.qm@web33512.mail.mud.yahoo.com> --- Pete Forman wrote: > Andr? writes: > > > Ok, doctest-based version of the Unit test > example added; so much > > more Pythonic ;-) > > Sorry for being a bit picky but there are a number > of things that I'm > unhappy with in that example. > Your pickiness is appreciated. :) > 1) It's the second example with 13 lines. Though I > suppose that the > pragmatism of pairing the examples overriding an > implicit goal of > the page is itself Pythonic. > Since you looked at the page, I have corrected that by making the example above it 12 lines, so that's no longer an issue. > 2) assert is not the simplest example of doctest. > The style should be > > >>> add_money([0.13, 0.02]) > 0.15 > >>> add_money([100.01, 99.99]) > 200.0 > >>> add_money([0, -13.00, 13.00]) > 0.0 > That's not clear cut to me. I think vertical conciseness has an advantage for readability, as it means you get to keep more "real" code on the screen. > 3) which fails :-( So both the unittest and doctest > examples ought to > be redone to emphasize what they are doing > without getting bogged > down by issues of floating point representations. > I was the one who originally posted the floating point example (with yet another style of unit testing, BTW), and I agree that the subtleties of floating point do kind of cloud the issue. I welcome a better example. What I didn't realize is that there's an actual error. Are you saying the program fails? On which test? ___________________________________________________________________________________ You snooze, you lose. Get messages ASAP with AutoCheck in the all-new Yahoo! Mail Beta. http://advision.webevents.yahoo.com/mailbeta/newmail_html.html From msj at infoserv.dk Wed Jun 20 07:55:53 2007 From: msj at infoserv.dk (Martin Skou) Date: Wed, 20 Jun 2007 13:55:53 +0200 Subject: Internationalised email subjects In-Reply-To: <1182337500.638044.63470@e9g2000prf.googlegroups.com> References: <1182337500.638044.63470@e9g2000prf.googlegroups.com> Message-ID: <46791592$0$5719$edfadb0f@dread14.news.tele.dk> From: http://docs.python.org/lib/module-email.header.html >>> from email.message import Message >>> from email.header import Header >>> msg = Message() >>> h = Header('p\xf6stal', 'iso-8859-1') >>> msg['Subject'] = h >>> print msg.as_string() Subject: =?iso-8859-1?q?p=F6stal?= /Martin From byte8bits at gmail.com Wed Jun 6 09:01:45 2007 From: byte8bits at gmail.com (brad) Date: Wed, 06 Jun 2007 09:01:45 -0400 Subject: which "GUI module" you suggest me to use? In-Reply-To: References: Message-ID: ZioMiP wrote: > I know that WxPython work only under Windows WxPython works everywhere for me. I have some screenshots from Windows 98 - Vista, Mac OSX, and Debian GNU/Linux... all running the exact same Python & wxPython code: http://filebox.vt.edu/users/rtilley/public/find_ssns/index.html From sergio at sergiomb.no-ip.org Fri Jun 15 09:16:49 2007 From: sergio at sergiomb.no-ip.org (Sergio Monteiro Basto) Date: Fri, 15 Jun 2007 14:16:49 +0100 Subject: Want to learn Python In-Reply-To: <1181907696.878873.214760@i13g2000prf.googlegroups.com> References: <1181907696.878873.214760@i13g2000prf.googlegroups.com> Message-ID: <1181913410.10607.5.camel@localhost.localdomain> On Fri, 2007-06-15 at 11:41 +0000, Amol wrote: > Hi, I want to learn Python in less than a month which resources should > I use. I prefer to read books . Please give me a list of *recognized* > resources. Thank You all > Books : Learning Python 2nd Edition (ISBN 0-596-00281-5) or above Python in a nutshell (I guess). both O'Reilly (r) -- S?rgio M. B. -------------- next part -------------- A non-text attachment was scrubbed... Name: smime.p7s Type: application/x-pkcs7-signature Size: 2192 bytes Desc: not available URL: From doug at alum.mit.edu Mon Jun 25 01:01:04 2007 From: doug at alum.mit.edu (Douglas Alan) Date: Mon, 25 Jun 2007 01:01:04 -0400 Subject: Python's "only one way to do it" philosophy isn't good? References: <7x3b0nmkk6.fsf@ruckus.brouhaha.com> <1182738909.918893.92220@m37g2000prh.googlegroups.com> Message-ID: Graham Breed writes: > Another way is to decorate functions with their local variables: >>>> from strict import my >>>> @my("item") > ... def f(x=1, y=2.5, z=[1,2,4]): > ... x = float(x) > ... w = float(y) > ... return [item+x-y for item in z] Well, I suppose that's a bit better than the previous suggestion, but (1) it breaks the style rule of not declaring variables until you need them, and (2) it doesn't catch double initialization. > The best way to catch false rebindings is to stick a comment with > the word "rebound" after every statement where you think you're > rebinding a variable. No, the best way to catch false rebindings is to have the computers catch such errors for you. That's what you pay them for. > Then you can search your code for cases where there's a "rebound" > comment but no rebinding. And how do I easily do that? And how do I know if I even need to in the face of sometimes subtle bugs? > Assuming you're the kind of person who knows that false rebindings > can lead to perplexing bugs, but doesn't check apparent rebindings > in a paranoid way every time a perplexing bug comes up, anyway. > (They aren't that common in modern python code, after all.) They're not that uncommon, either. I've certainly had it happen to me on several occasions, and sometimes they've been hard to find as I might not even see the mispeling even if I read the code 20 times. (Like the time I spent all day trying to figure out why my assembly code wasn't working when I was a student and finally I decided to ask the TA for help, and while talking him through my code so that he could tell me what I was doing wrong, I finally noticed the "rO" where there was supposed to be an "r0". It's amazing how useful a TA can be, while doing nothing at all!) > And you're also the kind of person who's troubled by perplexing bugs > but doesn't run a fully fledged lint. Maybe PyLint is better than Lint for C was (hated it!), but my idea of RAD does not include wading through piles of useless warning messages looking for the needle warning in the warning haystack. Or running any other programs in the midst of my code, run, code, run, ..., loop. > Maybe that's the kind of person who wouldn't put up with anything > short of a macro as in the original proposal. All I know is that > it's the kind of person I don't want to second guess. As it is, I code in Python the way that a normal Python programmer would, and when I have a bug, I track it down through sometimes painstaking debugging as a normal Python programmer would. Just as any other normal Python programmer, I would not use the alternatives suggested so far, as I'd find them cumbersome and inelegant. I'd prefer not to have been bit by the bugs to begin with. Consequently, I'd use let and set statements, if they were provided (or if I could implement them), just as I have the equivalents to let and set in every other programming language that I commonly program in other than Python. |>oug From els24 at cornell.edu Wed Jun 13 10:19:51 2007 From: els24 at cornell.edu (Eric Spaulding) Date: Wed, 13 Jun 2007 10:19:51 -0400 Subject: passing arguments to tcpserver classes Message-ID: <466FFD07.5060000@cornell.edu> Is there an easy way to pass arguments to a handler class that is used by the standard TCPServer? normally --> srvr =SocketServer.TCPServer(('',port_num), TCPHandlerClass) I'd like to be able to: srvr =SocketServer.TCPServer(('',port_num), TCPHandlerClass, (arg1,arg2)) And have arg1, arg2 available via TCPHandlerClass.__init__ or some other way. Where TCPHandlerClass: class TCPHandlerClass(SocketServer.StreamRequestHandler): def handle(self): #handle stream events here# Thanks for any advice. From mensanator at aol.com Mon Jun 11 23:49:56 2007 From: mensanator at aol.com (mensanator at aol.com) Date: Mon, 11 Jun 2007 20:49:56 -0700 Subject: SimplePrograms challenge In-Reply-To: References: Message-ID: <1181620196.117116.146240@j4g2000prf.googlegroups.com> On Jun 11, 4:56?pm, Steve Howell wrote: > Hi, I'm offering a challenge to extend the following > page by one good example: > > http://wiki.python.org/moin/SimplePrograms > > Right now the page starts off with 15 examples that > cover lots of ground in Python, but they're still > scratching the surface. (There are also two Eight > Queens implementations, but I'm looking to fill the > gap in lines-of-code, and they're a little long now.) > > I'm looking for a good 16-line code example with the > following qualities: > > 1) It introduces some important Python concept that > the first 15 programs don't cover. > > 2) It's not too esoteric. Python newbies are the > audience (but you can assume they're not new to > programming in general). > > 3) It runs on Python 2.4. > > 4) It doesn't just demonstrate a concept; it solves > a problem at face value. (It can solve a whimsical > problem, like counting rabbits, but the program itself > should be "complete" and "suitably simple" for the > problem at hand.) > > 5) You're willing to have your code reviewed by the > masses. > > 6) No major departures from PEP 8. > > Any takers? > > -- Steve > > ___________________________________________________________________________ _________ > Looking for a deal? Find great prices on flights and hotels with Yahoo! FareChase.http://farechase.yahoo.com/ I just posted a 30-line generator function on your site. Should I have posted it here first? Also, why do you count comments and blank lines instead of lines of executable code? Are you trying to encourage obfuscation? From arkanes at gmail.com Wed Jun 6 10:45:48 2007 From: arkanes at gmail.com (Chris Mellon) Date: Wed, 6 Jun 2007 09:45:48 -0500 Subject: which "GUI module" you suggest me to use? In-Reply-To: References: <136bvigp2ps99bc@corp.supernews.com> Message-ID: <4866bea60706060745y13d9a3dbha04739083ec1b08d@mail.gmail.com> On 6/6/07, Samuel wrote: > On Wed, 06 Jun 2007 00:22:40 +0000, Grant Edwards wrote: > > >> I know that WxPython work only under Windows and PyGTK work only under > >> Linux... > > > > You 'know' wrong. > > > > wxPython works fine under Windows, Linux and OSX. > > wxPython emulates Gtk (though using some native widgets, it also uses > some of its own) and in many cases it looks non-native compared to Gtk. > If your target platform includes Unix systems, you'll have to decide > whether inconsistencies with the look and feel of the desktop are an > issue for you. > In the general case, wxWidgets wraps (not emulates) Gtk. I don't believe that there are any common controls left which are still emulated (maybe the list control? I'm not sure - I don't follow the bleeding edge of wx anymore). wxPython (as opposed to wxWidgets, the C++ core) has a sizeable library of custom controls as part of its standard lib. Most of these are owner-drawn for various reasons and often won't appear native (Andrea Gavin, probably the most prolific custom control author, works primarily on Windows). > > PyGTK works under Linux and Windows, but doens't use native widgets > > under Windows, so it won't look like a "normal" windows app. > > Gtk on Win32 can be themed to looked like Windows, AFAIK the Win32 > installer does this by default since a couple of months. > That stretches the truth rather significantly. While the win32 theme does use the windows theme apis for drawing, it still has slightly different colors (especially window backgrounds and menus), and (more importantly) vastly and notably different behavior. Shortcuts are different, renderings are different, the Gtk drawing model is used instead of the windows one (leads to quite jarring repainting differences), different fonts, etc, etc. It looks okay in a screenshot but is clearly non-native and foreign in use. From python at jayloden.com Mon Jun 18 13:17:12 2007 From: python at jayloden.com (Jay Loden) Date: Mon, 18 Jun 2007 13:17:12 -0400 Subject: Parsing HTML, extracting text and changing attributes. In-Reply-To: <4676B809.2010307@web.de> References: <1182175239.122827.4150@g4g2000hsf.googlegroups.com> <4676B809.2010307@web.de> Message-ID: <4676BE18.6070306@jayloden.com> Stefan Behnel wrote: > Jay Loden wrote: >> Someone else mentioned lxml but as I understand it lxml will only work if >> it's valid XHTML that they're working with. > > No, it was meant as the OP requested. It even has a very good parser from > broken HTML. > > http://codespeak.net/lxml/dev/parsing.html#parsing-html I stand corrected, I missed that whole part of the LXML documentation :-) From blockrockin at verizon.net Sat Jun 23 06:12:58 2007 From: blockrockin at verizon.net (Fran Duffy) Date: Sat, 23 Jun 2007 06:12:58 -0400 Subject: looking for scott from Glassboro State Message-ID: <000301c7b57f$13dc0990$2e01a8c0@Duffyer> I am looking for a friend of mine that I havent seen in a long time. If you are Scott that went to Glassboro as a music major, please send me an Email: Fran Duffy at: Blockrockin at verizon.net. If you are not that Scott, disregard, and sorry to take up your time. Thanks Fran Duffy From cam.ac.uk at mh391.invalid Sat Jun 2 20:42:46 2007 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Sun, 03 Jun 2007 01:42:46 +0100 Subject: __getslice__ depreciation In-Reply-To: <1180721533.851070.309770@w5g2000hsg.googlegroups.com> References: <1180720203.950209.260610@w5g2000hsg.googlegroups.com> <1180721533.851070.309770@w5g2000hsg.googlegroups.com> Message-ID: Screamingfirst at gmail.com wrote: > On Jun 1, 7:50 pm, Screamingfi... at gmail.com wrote: >> If __getslice__ is depreciated (since version 2.0) why are neither >> __setslice__ or __delslice__ depreciated?http://docs.python.org/ref/sequence-methods.html > > Sorry disregard that, I should have RTFA A request to have the docs changed so that "Deprecated since release 2.0." in bold appears next to all three would not go amiss. -- Michael Hoffman From josiah.carlson at sbcglobal.net Sat Jun 2 16:32:06 2007 From: josiah.carlson at sbcglobal.net (Josiah Carlson) Date: Sat, 02 Jun 2007 20:32:06 GMT Subject: Python rocks In-Reply-To: <4661adda$0$19256$da0feed9@news.zen.co.uk> References: <4661adda$0$19256$da0feed9@news.zen.co.uk> Message-ID: Mark Carter wrote: > Not that I'm particularly knowledgeable about language design issues, > but maybe closures and slightly different scoping rules would be nice. Python has had closures for years. What kind of scoping did you desire? > A > pitfall of Python is knowing whether an operation is destructive or not. If it returns None, it probably changes the content of an object. > I guess if it was a purely functional language, that particular question > wouldn't arise. You can certainly do your programming in a functional style with Python. List comprehensions and generator expressions are very good for this kind of thing. > Oh, and when I read a line, I'd like it to get rid > of the trailing line-ending characters. Refuse the temptation to guess. As many people want to keep the newlines as not (it disambiguates the case of end of file and blank line), and it is a simple thing to deal with: line.rstrip('\r\n') . - Josiah From showell30 at yahoo.com Sun Jun 3 19:39:23 2007 From: showell30 at yahoo.com (Steve Howell) Date: Sun, 3 Jun 2007 16:39:23 -0700 (PDT) Subject: *Naming Conventions* In-Reply-To: <1180912853.513564.84060@p77g2000hsh.googlegroups.com> Message-ID: <775162.87869.qm@web33514.mail.mud.yahoo.com> --- Dan Bishop wrote: > > * Loop indices often have single-letter names > (typically i/j/k or x/ > y), or names that are the singular form of the list > name (e.g., "for > ballot in self._ballots"). For iterating over > files, I use "line". > You are in good company with "i" and "line." They are among the 15 most used tokens in the Python standard library, which includes reserved words if, def, return, in, not, else, and for. 16610 self 7347 if 5222 def 4686 return 2818 None 2235 in 1799 not 1723 else 1637 name 1499 i 1226 os 1224 line 1203 for 1183 data 1181 path I sampled /usr/local/lib/python2.5 with tokenizer. ____________________________________________________________________________________ Got a little couch potato? Check out fun summer activities for kids. http://search.yahoo.com/search?fr=oni_on_mail&p=summer+activities+for+kids&cs=bz From steve at laniels.org Thu Jun 21 10:30:50 2007 From: steve at laniels.org (Stephen R Laniel) Date: Thu, 21 Jun 2007 10:30:50 -0400 Subject: PEP 3107 and stronger typing (note: probably a newbie question) In-Reply-To: <20070621141156.GG6145@slaniel-laptop.itasoftware.com> References: <1182369568.941307.316260@p77g2000hsh.googlegroups.com> <5dveb4F360un0U1@mid.individual.net> <20070621141156.GG6145@slaniel-laptop.itasoftware.com> Message-ID: <20070621143048.GH6145@slaniel-laptop.itasoftware.com> On Thu, Jun 21, 2007 at 10:11:57AM -0400, Stephen R Laniel wrote: > "Use another language" is not a technical answer. "Python > could not adopt static typing without substantially changing > the language and destroying what everyone loves about it, > and here are examples of where the problem shows up" is. The best dynamic-versus-static-typing discussion I've ever seen, by the way, was Mark-Jason Dominus's (he of "Higher-Order Perl"): http://perl.plover.com/yak/typing/notes.html -- Stephen R. Laniel steve at laniels.org Cell: +(617) 308-5571 http://laniels.org/ PGP key: http://laniels.org/slaniel.key From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Mon Jun 25 16:05:07 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Mon, 25 Jun 2007 22:05:07 +0200 Subject: Python SVN down? References: <1182799060.612115.75490@n60g2000hse.googlegroups.com> Message-ID: <5ealfjF37mjlvU1@mid.individual.net> gregpinero at gmail.com wrote: > Going to this URL: > http://svn.python.org/view/ > > It gives me an error: > Unable to connect > Firefox can't establish a connection to the server at > svn.python.org. > [...] > Any ideas? Clear case. $ nc -v svn.python.org 80 svn.python.org [82.94.237.220] 80 (www) : Connection refused $ It _is_ down. Probably server maintenance. Regards, Bj?rn -- BOFH excuse #37: heavy gravity fluctuation, move computer to floor rapidly From half.italian at gmail.com Mon Jun 25 01:43:40 2007 From: half.italian at gmail.com (half.italian at gmail.com) Date: Mon, 25 Jun 2007 05:43:40 -0000 Subject: regular expressions eliminating filenames of type foo.thumbnail.jpg In-Reply-To: <1182747645.092002.68800@x35g2000prf.googlegroups.com> References: <1182746933.413693.103860@p77g2000hsh.googlegroups.com> <1182747645.092002.68800@x35g2000prf.googlegroups.com> Message-ID: <1182750220.486035.298890@o11g2000prd.googlegroups.com> On Jun 24, 10:00 pm, Justin Ezequiel wrote: > Why not ditch regular expressions altogether for this problem? > > [ p for p in os.listdir(dir) > if os.path.isfile(os.path.join(dir,p)) > and p.lower().find('.thumbnail.')==-1 ] I like `and '.thumbnail.' not in p]` as a better ending. :) ~Sean From jim.hefferon at gmail.com Thu Jun 7 09:10:50 2007 From: jim.hefferon at gmail.com (Jim) Date: Thu, 07 Jun 2007 06:10:50 -0700 Subject: subprocess call acts differently than command line call? Message-ID: <1181221850.923908.178800@q75g2000hsh.googlegroups.com> Hello, I need a program that will traverse a directory tree to ensure that there are unix-style line endings on every file in that tree that is a text file. To tell text files from others I want to use the unix "file" command (Python's "mimetypes" is not so good for me). But I am stuck on something about getting that output, and I'd greatly appreciate any pointers. Both the command line "file" and the python libmagic binding give the same behavior, but I'll illustrate with "file". It sometimes acts differently when run from the command line than when run using the subprocess module (with the same user). For example, it sometimes gives output when run from the command line but no output when run as a subprocess. Below is a short program to demo. (I use this on a test file tree that is at ftp://joshua.smcvt.edu/pub/hefferon/a.zip if anyone is interested.) ............................................ import subprocess import glob for fn in glob.glob('a*/*'): cmd=['/usr/bin/file',fn] cmdStr=" ".join(cmd) try: p=subprocess.Popen(cmdStr,shell=True,stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE,close_fds=True) (child_stdin, child_stdout, child_stderr)=(p.stdin,p.stdout,p.stderr) stdoutContent=child_stdout.read() except Exception, err: mesg=u"unable to execute %s" % (repr(cmdStr),) raise StandardError, mesg+": "+str(err) if (p.returncode): mesg=u"trouble executing %s" % (repr(cmdStr),) raise StandardError, mesg+": "+repr(p.returncode) print "result: ",stdoutContent print "done" ............................................ I've put a transcript of what happens at the bottom of this message. One file (in the test tree it is "eqchange.txt") gives no output from the above program, but does give an output when I use "file" at the command line. Specifying "-m/usr/share/file/magic" in the "file" call doesn't change that the command line and subprocess calls act differently, so it is not just a question of different environments causing the system to use different "magic" files. Changing the PIPE's to files, then closing and reopening them also does not matter, I believe. In short I expected subprocess to just mimic my typing it in. Is there some reason "file" doesn't act this way, and is there some way to make it do so? I have Python 2.4.4 running on Ubuntu. Thank you for any suggestions, Jim -----transcript (edited to shorten)------------ $ python test.py result: acrotex/readme.txt: ASCII English text, with CRLF line terminators result: acrotex/eq2db.ins: ASCII English text, with CRLF line terminators result: acrotex/eqchange.txt: result: acrotex/exerquiz.dtx: ISO-8859 English text, with CRLF line terminators result: acrotex/doc: directory done $ file acrotex/eqchange.txt acrotex/eqchange.txt: ISO-8859 English text, with CRLF line terminators $ file acrotex/eqchange.txt 1> test.out $ cat test.out acrotex/eqchange.txt: ISO-8859 English text, with CRLF line terminators $ file acrotex/eqchange.txt 2> test.out acrotex/eqchange.txt: ISO-8859 English text, with CRLF line terminators $ cat test.out $ From jstroud at mbi.ucla.edu Fri Jun 22 21:55:08 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Fri, 22 Jun 2007 18:55:08 -0700 Subject: Adding method to a class on the fly In-Reply-To: <1182538969.522044.209560@q19g2000prn.googlegroups.com> References: <1182538969.522044.209560@q19g2000prn.googlegroups.com> Message-ID: John Henry wrote: > Hi list, > > I have a need to create class methods on the fly. For example, if I > do: > > class Dummy: > def __init__(self): > exec '''def method_dynamic(self):\n\treturn > self.method_static("it's me")''' > return > > def method_static(self, text): > print text > return Where is the text for the exec statement coming from? A file? User input? What you are doing above makes absolutely no sense. You confuse everyone who attempts to understand what you want to do with the above because no one in his right mind would do anything like it. > I like that to be the same as: > > class Dummy: > def __init__(self): > return > > def method_dynamic(self): > return self.method_static("it's me") > > def method_static(self, text): > print text > return Are you looking to fill in text and create new methods for Dummy based on the text and method_static() such that these will become true instance methods for instances of Dummy? def add_dynamic(cls_name, f, name, *args, **kwargs): cls = globals()[cls_name] def _f(self): return getattr(cls, f)(self, *args, **kwargs) setattr(cls, name, _f) e.g. py> class Dummy: ... def method_static(self, text): ... print text ... return ... py> def add_dynamic(cls_name, f, name, *args, **kwargs): ... cls = globals()[cls_name] ... def _f(self): ... return getattr(cls, f)(self, *args, **kwargs) ... setattr(cls, name, _f) ... py> add_dynamic('Dummy', 'method_static', 'method_dynamic', 'abc xyz') py> Dummy.method_dynamic py> d = Dummy() py> d.method_dynamic() abc xyz Note that this is "completely dynamic" in that all arguments to add_dynamic() are strings. This may or may not be what you want--in such a case, you will want to study the code to see how it works and fix it yourself. Note also that methods added to classes after instances are made will be available to said instances: py> add_dynamic('Dummy', 'method_static', 'method2_dynamic', 'asdf jkl') py> d.method2_dynamic() asdf jkl > so that I can do: > > dum=Dummy.method_dynamic() Here you confuse everyone. This last line is not the same as you describe in the above example. Here you imply the dynamic creation of a "static method" (not a "method_static"--don't be confused by the names you invent as they may already have a meaning to everyone else). Static methods are different from unbound class methods that are later bound to instances of a class upon instantiation. Here is an analagous solution for static methods: def add_static(cls_name, f, name, *args, **kwargs): cls = globals()[cls_name] def _f(): return getattr(cls, f)(*args, **kwargs) setattr(cls, name, staticmethod(_f)) class Dummy: @staticmethod def method_static(text): print text e.g.: py> def add_static(cls_name, f, name, *args, **kwargs): ... cls = globals()[cls_name] ... def _f(): ... return getattr(cls, f)(*args, **kwargs) ... setattr(cls, name, staticmethod(_f)) ... py> class Dummy: ... @staticmethod ... def method_static(text): ... print text ... py> add_static('Dummy', 'method_static', 'real_static', 'aaa bbb') py> Dummy.real_static py> Dummy.real_static() aaa bbb Again, this will do what you want, but if it doesn't do *exactly* what you want, you need to study and modify the code. Also, creating static methods from unbound methods requires trickery. If this is what you want, you should be very clear about it. > and see "it's me" printed. > > Can that be done? Yes. Anything is possible with python. That's why I use it. James From nogradi at gmail.com Fri Jun 29 11:38:59 2007 From: nogradi at gmail.com (Daniel Nogradi) Date: Fri, 29 Jun 2007 17:38:59 +0200 Subject: Voluntary Abstract Base Classes Message-ID: <5f56302b0706290838j377ed7dct2cd2807394f791cf@mail.gmail.com> Hi list, Well, the short question is: what are they? I've read Guido's python 3000 status report on http://www.artima.com/weblogs/viewpost.jsp?thread=208549 where he mentions ABC's but don't quite understand what the whole story is about. Anyone has good use cases? Daniel From tjreedy at udel.edu Wed Jun 13 16:49:04 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 13 Jun 2007 16:49:04 -0400 Subject: Python's "only one way to do it" philosophy isn't good? References: <725498.90657.qm@web33511.mail.mud.yahoo.com> Message-ID: "Steve Howell" wrote in message news:725498.90657.qm at web33511.mail.mud.yahoo.com... | | You would just change the language definition to say | that once you enter f(), any call to f() from within | f() behaves as if the recursively called f() still | points to the originally bound version of f. I am pretty sure such a context-dependent rule cannot be written as a context-free grammar rule. In any case, the function object does not exist when code is being compiled to a code object. So this requires implementation-dependent post-patching of the code object. R. Hetchinger(sp?) posted a Cookbook recipe for doing this for CPython. Anyone wanting the speedup (with CPython) can use it. tjr From sk8in_zombi at yahoo.com.au Fri Jun 8 18:23:38 2007 From: sk8in_zombi at yahoo.com.au (Mr SZ) Date: Sat, 9 Jun 2007 08:23:38 +1000 (EST) Subject: Dealing with dictionary like strings Message-ID: <457848.7849.qm@web54506.mail.re2.yahoo.com> Hello all, I'm using the urllib module to fetch pages from the web.The returned response is in the structure of a dictionary .For eg: {"":"","label": [ ] ,"torrents": [ ["F0666BDCCBFD01A52535759C044485E2E1CCE3C3",136,"AAA",1250164864,651,646185088,606208,0,0,0,-1,"",0,0,0,0,33564,7,342884352], ["46683EA1C950CB020DD6DD3007120EAB9966FA79",201,"tpg",4153995264,305,841170944,758087680,901,0,0,103109046,"",4,23,0,0,64080,2,2887053312]] ,"torrentc": "2001899868"} This response as we can see is not just like a dictionary but it's values are in the form of lists.Now,is there a way I can deal with this string as a dictionary .I'm only interested in the value field of torrents key which again is a list of lists. --------------------------------- How would you spend $50,000 to create a more sustainable environment in Australia? Go to Yahoo!7 Answers and share your idea. -------------- next part -------------- An HTML attachment was scrubbed... URL: From martin at v.loewis.de Thu Jun 28 17:24:55 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Thu, 28 Jun 2007 23:24:55 +0200 Subject: Vista 64 + Python2.5 + wxpython 28 issue In-Reply-To: <000001c7b9c5$e70a0d40$b51e27c0$@com> References: <4684150e$0$24850$9b622d9e@news.freenet.de> <000001c7b9c5$e70a0d40$b51e27c0$@com> Message-ID: <46842727.6070202@v.loewis.de> > Is there any 64 version installer or do I need to build myself ? There are hardly AMD64 versions of *anything* but the base Python distribution. I strongly advise to use the 32-bit version on AMD64 (in fact, I see little reason to run Win64 at all unless you have more that 4GiB in the box, or unless you are developing a software product that you explicitly target for Win64). If you absolutely need to run 64-bit code, be prepared to compile everything for yourself, and be prepared that it won't work out of the box, and cost you many person days to fix and debug. Never forget to feed back the fixes you make to the respective authors of the open source software. Notice that you won't just need a 64-bit version of wxpython, but also such versions of all underlying libraries wxpython happens to be build on. Regards, Martin From http Fri Jun 22 01:31:24 2007 From: http (Paul Rubin) Date: 21 Jun 2007 22:31:24 -0700 Subject: "assert" annoyance Message-ID: <7xmyys368j.fsf_-_@ruckus.brouhaha.com> So I have some assert statements in my code to verify the absence of some "impossible" conditions. They were useful in debugging and of course I left them in place for "real" runs of the program. Umpteen hours into a run, an assertion failed, and of course since failure was "impossible", I didn't catch the exception so the whole program crashed. I don't know what I'd have done with the exception anyway, since it would have had to be caught at an outer scope where the data I cared about was no longer around, or else I'd have had to predict in advance what I needed to examine and pass that as a an arg to the assert statement. What I really want is for any assertion failure, anywhere in the program, to trap to the debugger WITHOUT blowing out of the scope where the failure happened, so I can examine the local frame. That just seems natural, but I don't see an obvious way to do it. Am I missing something? I guess I could replace all the assertions with function calls that launch pdb, but why bother having an assert statement? From gagsl-py2 at yahoo.com.ar Mon Jun 11 15:30:58 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 11 Jun 2007 16:30:58 -0300 Subject: Accessing global namespace from module References: <1181577768.728377.262720@m36g2000hse.googlegroups.com> <1181583469.562064.29440@p77g2000hsh.googlegroups.com> <1181585938.144294.119790@w5g2000hsg.googlegroups.com> Message-ID: En Mon, 11 Jun 2007 15:18:58 -0300, reubendb escribi?: > The problem is I don't define the functions AddPlot() and DrawPlots(). > It's built into the python interpreter of the CLI version of the > program I mentioned, and they are defined on the main script. I load > the main script using something like "software -cli -s > mainscript.py". > In the mainscript.py I import myModule, but of course myModule does > not have access to the functions defined in the global namespace of > mainscript.py. Don't you have some import statements at the top of mainscript.py that are responsible for bringing AddPlot and DrawPlots into the current namespace? Import the same things in your second module. -- Gabriel Genellina From notbob at nothome.com Thu Jun 21 16:49:51 2007 From: notbob at nothome.com (notbob) Date: Thu, 21 Jun 2007 15:49:51 -0500 Subject: The Modernization of Emacs: terminology buffer and keybinding References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182272495.990807.99110@a26g2000pre.googlegroups.com> <87tzt3ihev.fsf@kobe.laptop> <1182370216.961241.6960@n60g2000hse.googlegroups.com> <85zm2ufjpb.fsf@lola.goethe.zz> <1182372592.803332.288260@u2g2000hsc.googlegroups.com> <1182373919.262388.100740@c77g2000hse.googlegroups.com> <85r6o6fhkb.fsf@lola.goethe.zz> <1182375045.626510.188170@m36g2000hse.googlegroups.com> <1182453375.531950.141460@m36g2000hse.googlegroups.com> <1182456618.763414.219080@g4g2000hsf.googlegroups.com> Message-ID: <5ZSdnYAchqLyeefbnZ2dnUVZ_vqdnZ2d@comcast.com> On 2007-06-21, Kaldrenon wrote: > Feel free to disagree with what I'm about to say. [...] > And if you disagree with me, or if you think I expressed my point > poorly.... I think you expressed it well. I'll add that using one does not necessarilly exclude using the other. I tend to use whatever makes the job easiest FOR ME! ...be it a gui or the command line. Also, ease of learning emacs has absolutely zero to do with mental prowess and not everyone using it is a code whiz. Except for some html and shell scripting, I do almost zero developement because it bores me to freakin' tears. That's not to say I can't like the command line and emacs. All types of user interface have their pros and cons and it's senseless to limit one's self to one or the other. Some tasks benefit from using both simultaneously, acad and gimp/p-shop being prime examples. Sure, everyone loves the camaraderie of belonging to a group. That's just being human. But, choosing a preference doesn't require fanatical loyalty to the exclusion of all other options, or at least it shouldn't. Use the one that's best for the job. nb From fsckedagain at gmail.com Tue Jun 12 16:23:15 2007 From: fsckedagain at gmail.com (fscked) Date: Tue, 12 Jun 2007 13:23:15 -0700 Subject: set IP in linux with python Message-ID: <1181679795.639380.163380@z28g2000prd.googlegroups.com> I have a text file with some network info like IP, mask, gateway, etc, that I want to set on a linux box. This script will run on the host that will be getting the new info. I can parse the data in the text file and get my data in a list, but I can't figure out how to put it in the right place of the config file. Any ideas? From henrik.garbergs at telia.com Wed Jun 20 05:12:03 2007 From: henrik.garbergs at telia.com (henrik.garbergs at telia.com) Date: Wed, 20 Jun 2007 11:12:03 +0200 (MEST) Subject: Invisible processes in Win2K Message-ID: <3929709.1182330723118.JavaMail.tomcat@pne-ps1-sn1> Hi! I'm running a Python program on M$ Windows 2000 as a test monitor. The program should close various processes, mostly "Application error"-windows, as they are created. This works fine until the screensaver gets active or until I press Ctrl-Alt-Del and choose "Lock my computer". At that point, my Python program cannot see any change when a "Application error" pops up. Without locked computer, it can identify these windows and close them, but I want it to do this with the computer locked as well. (My company has a policy that says you have to lock the computer or activate a password protected screensaver when you leave your desk) The code I'm using to list processes looks like this: # ------------------------------------ def process_callback_function(hwnd, resultdict): ....# Callback-function for win32gui.EnumWindows ....wtext = win32gui.GetWindowText(hwnd) ....if wtext != '' and wtext != 'Default IME': ........resultdict.update( {wtext:hwnd} ) # ------------------------------------ def getProcessDictionary(w): ....try: ........win32gui.EnumWindows(process_callback_function, w) ....except Exception, message: ........logAndPrint('Error in getProcessDictionary: ' + str(message)) # -------------------------------- def getProcessList(): ....# Flush old cache ....win32pdh.EnumObjects(None, None, 0, 1) ....# Get a list of processes running on the system: ....try: ........junk, instances = win32pdh.EnumObjectItems(None,None,'Process', win32pdh.PERF_DETAIL_WIZARD) ....except win32api.error, message: ........logAndPrint('Error in getProcessList(): ' + str(message)) ........return [] ....else: ........return instances # -------------------------------- # Code in main loop: topWindows = {} getProcessDictionary(topWindows) for w in topWindows.iteritems(): ...if 'Application Error' in w[0]: .......closeProcess(w[1]) I'm using two functions to receive process info: getProcessList and getProcessDictionary. I have tried to save the result of these, compare them at different times in the main loop and print newly started processes. This works great outside "locked computer"-mode where it prints all new processes found, including Application errors. But when the computer is locked and Application errors pops up, the Python program shows no new processes. It's not hanged or freezed, since it can identify the screensaver and also keep doing other work. So what is so special about the error windows? Any help with this is greatly appreciated! Best regards, /Henrik From __peter__ at web.de Mon Jun 4 05:34:10 2007 From: __peter__ at web.de (Peter Otten) Date: Mon, 04 Jun 2007 11:34:10 +0200 Subject: int vs long References: <1180839659.196587.194200@p77g2000hsh.googlegroups.com> <7xr6otiv4l.fsf@ruckus.brouhaha.com> <1180895701.813483.326780@k79g2000hse.googlegroups.com> <7xabvgj33p.fsf@ruckus.brouhaha.com> <1hz4uas.7jeyyu192pb8tN%aleax@mac.com> Message-ID: Douglas Woodrow wrote: > On Mon, 4 Jun 2007 10:50:14, Peter Otten <__peter__ at web.de> wrote >>>> >>>> This is fixed in Python2.5: >>>> >>> Hm, my test above was from 2.5!? >> >>Then your installation is broken. What does >> >>>>> import itertools >>>>> itertools >>>'/usr/local/lib/python2.5/lib-dynload/itertools.so'> >> >>print? > > > Maybe it's a problem with the Windows build of Python 2.5 > > ,---- > | Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 > | 32 bit (Intel)] on win32 > | Type "help", "copyright", "credits" or "license" for more information. > | >>> import sys > | >>> import itertools > | >>> itertools > | > | >>> c = itertools.count(sys.maxint) > | >>> c.next() > | Traceback (most recent call last): > | File "", line 1, in > | OverflowError: cannot count beyond LONG_MAX > | >>> > `---- > Revision 51950 check-in message: """ * regression bug, count_next was coercing a Py_ssize_t to an unsigned Py_size_t which breaks negative counts * added test for negative numbers will backport to 2.5.1 """ Turns out I was wrong, count() does not escalate from int to long correctly. It just had an unsigned internal counter in 2.5. Sorry for the confusion. Peter From bignose+hates-spam at benfinney.id.au Thu Jun 21 19:38:52 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 22 Jun 2007 09:38:52 +1000 Subject: Collections of non-arbitrary objects ? References: <1182449993.223262.229500@z28g2000prd.googlegroups.com> Message-ID: <87k5twx4hf.fsf@benfinney.id.au> walterbyrd writes: > Python seems to have a log of ways to do collections of arbitrary > objects: lists, tuples, dictionaries. But what if I want a > collection of non-arbitrary objects? A list of records, or something > like that? Then collect them in a non-arbitrary way. That's a flippant response, but I don't understand the question. What are you asking for that you don't already have? A list can contain a sequence of objects of the same type already. What are you expecting that a list does not provide? -- \ "Faith may be defined briefly as an illogical belief in the | `\ occurrence of the improbable." -- Henry L. Mencken | _o__) | Ben Finney From jason at tishler.net Mon Jun 25 12:49:10 2007 From: jason at tishler.net (Jason Tishler) Date: Mon, 25 Jun 2007 12:49:10 -0400 Subject: socket on cygwin python In-Reply-To: References: <1182748882.617588.190230@c77g2000hse.googlegroups.com> Message-ID: <20070625164910.GA4012@tishler.net> On Mon, Jun 25, 2007 at 01:53:18PM +0100, Michael Hoffman wrote: > bacon.chao at gmail.com wrote: > > I've installed cygwin with latest python 2.5.1, but it seems that the > > socket lib file do NOT support IPv6(cygwin\lib\python2.5\lib-dynload > > \_socket.dll), what can I do if I want to use IPv6? > > I don't think Cygwin supports IPv6. That was my impression too and seems to be substantiated by the following: http://win6.jp/Cygwin/index.html 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 steve at holdenweb.com Mon Jun 4 20:20:39 2007 From: steve at holdenweb.com (Steve Holden) Date: Mon, 04 Jun 2007 20:20:39 -0400 Subject: Delete a file from a CGI In-Reply-To: References: Message-ID: Matias Surdi wrote: > Steve Holden escribi?: > >> Matias Surdi wrote: >>> Thanks for your reply. >>> >>> This is the code that creates the file: >>> lock_file = open(".lock","w") >>> lock_file.write("test") >>> lock_file.close() >>> #Change permissions so that CGI can write lock file >>> os.chmod(".lock",stat.S_IMODE(stat.S_IRWXU | stat.S_IRWXO | >>> stat.S_IRWXG)) >>> >>> This script was run as root. >>> >>> Now, the code of the CGI that should delete the file: >>> >>> #As you see, I can write to the file >>> lock_file = open(".lock","w") >>> lock_file.write("") >>> lock_file.close() >>> # But the following line raises a "permission denied" OSError >>> os.remove(".lock") >>> >>> I've seen that the script is running as "nobody", but, the file is rwx by >>> everybody. I've also tryed changing the owner of the file to "nobody" >>> also, but no luck anyway. >>> >>> Thanks a lot. >>> >>> >>> Steve Holden wrote: >>> >>>> Matias Surdi wrote: >>>>> HI! >>>>> >>>>> I want to delete a file from a CGI, but I always get a Permission >>>>> denied error. >>>>> >>>>> I've tryed this after creating the file (from a normal script): >>>>> >>>>> os.chmod(".lock",stat.S_IMODE(stat.S_IRWXU | stat.S_IRWXO | >>>>> stat.S_IRWXG)) >>>>> os.chown(".lock",pwd.getpwnam("nobody")[2],pwd.getpwnam("nobody")[3]) >>>>> >>>>> but the CGI still can't delete the file. >>>>> >>>>> I will appreciate very much your help. >>>>> >>>>> Thanks a lot. >>>>> >>>>> >>>> How was the file created in the first place? If you don't have >>>> permissions to delete it you may well not have permissions to reown it >>>> or change its permissions either! >>>> >> Most likely, your problem is that to delete a file you need write >> permissions on the directory that contains it [1]. Apparently the web >> user (nobody, or apache, or whatever) doesn't have those permissions. >> >> regards >> Steve >> >> [1]: Unless the sticky bit is set on the containing directory, when >> other tests are applied instead. If this makes no sense to you, ignore it. > > > Hi! > > I feel so s**id.... it's very likely to be that the problem.... I'll try > this next week at work. > > Thanks a lot for the cold water on the face! > Hey, it's just information: no need to overreact! regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From p at ulmcnett.com Thu Jun 14 20:25:34 2007 From: p at ulmcnett.com (Paul McNett) Date: Thu, 14 Jun 2007 17:25:34 -0700 Subject: OS X install confusion In-Reply-To: <1hzpj69.1k6hn46vkidfkN%johnmfisher@comcast.net> References: <1hzp0kw.4i0y5i1cqnlwoN%johnmfisher@comcast.net> <6b03b$46717b5e$4275d90a$18801@FUSE.NET> <1181842656.810802.24810@x35g2000prf.googlegroups.com> <1hzpj69.1k6hn46vkidfkN%johnmfisher@comcast.net> Message-ID: <4671DC7E.8080208@ulmcnett.com> John Fisher wrote: > Ted wrote: > >> On Jun 14, 1:31 pm, Kevin Walzer wrote: >>> John Fisher wrote: >>>> Hi Groupies, >>>> I have an Intel Macbook running OS X 10.4. >>>> It came installed with Python 2.3.5. I have since installed MacPython >>>> with version 2.4.4, cool. >>>> When I open a bash terminal session and type python, it brings up >>>> version 2.3.5. If I type IDLE it brings up version 2.4.4. >>>> My question: what do I have to do to get it to bring up 2.4.4 with the >>>> "python" command? >>>> Thanks for bringing light to my ignorance. >>>> JF >>> Sounds like a path problem. Apple's system Python is installed in >>> /usr/bin. Your installation is probably in /usr/local/bin. Edit your >>> profile or use the full path. >>> >>> -- >>> Kevin Walzer >>> Code by Kevinhttp://www.codebykevin.com >> The default python on tiger (2.3.5) is sym-linked to /usr/bin/python >> and /usr/bin/pythonw. >> >> I found it easier to relink to the new installation path. This also >> leaves /usr/bin/python23 and /usr/bin/pythonw23 still linked to the >> original version if you want to quickly check something. >> >> Cheers, >> Ted > > OK, please give a little more information how I can accomplish this > "re-link". Your Python 2.5 is likely installed here: /Library/Frameworks/Python.framework/Versions/Current/bin But OS X comes with a "system Python", version 2.3.5, likely installed here: /usr/bin If you look at /usr/bin, you'll see: lrwxr-xr-x 1 root wheel 9 Jan 31 17:24 python -> python2.3 lrwxr-xr-x 1 root wheel 72 Jan 31 17:24 python2.3 -> ../../System/Library/Frameworks/Python.framework/Versions/2.3/bin/python lrwxr-xr-x 1 root wheel 10 Jan 31 17:24 pythonw -> pythonw2.3 -rwxr-xr-x 1 root wheel 29704 Aug 19 2006 pythonw2.3 So, python is linked to python2.3, and python2.3 is in turn linked to /System/Library/Frameworks/Python.framework/Versions/2.3/bin/python You need to (warning: watch for line wrap): sudo -s cd /usr/bin ln -s /Library/Frameworks/Python.framework/Versions/Current/bin/python python_current ln -s /Library/Frameworks/Python.framework/Versions/Current/bin/pythonw pythonw_current rm python rm pythonw ln -s python python_current ln -s pythonw pythonw_current However, that isn't what I did. I like the system being able to find and use the system-installed python, but I like my scripts to use the python version I installed (2.5). To get that, skip the above symlinking and instead edit your .bash_profile file (hidden file inside your home directory) and put these lines at the top: PATH="/Library/Frameworks/Python.framework/Versions/Current/bin:${PATH} export PATH -- pkm ~ http://paulmcnett.com From steve at holdenweb.com Thu Jun 28 20:47:03 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 28 Jun 2007 20:47:03 -0400 Subject: Collections of non-arbitrary objects ? In-Reply-To: <7xodj18fja.fsf@ruckus.brouhaha.com> References: <1182449993.223262.229500@z28g2000prd.googlegroups.com> <87k5twx4hf.fsf@benfinney.id.au> <1182559502.069773.321620@i38g2000prf.googlegroups.com> <87wsxvrzsj.fsf@benfinney.id.au> <1182620734.940718.196520@e16g2000pri.googlegroups.com> <467ed491$0$27132$426a34cc@news.free.fr> <1182780863.067601.89320@d30g2000prg.googlegroups.com> <46801791$0$32172$426a34cc@news.free.fr> <1182863704.364272.5950@i13g2000prf.googlegroups.com> <46812159$0$24920$426a74cc@news.free.fr> <1182961835.134162.311670@x35g2000prf.googlegroups.com> <7xodj18fja.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > Steve Holden writes: >> Think of a tuple as an ordered collection. A given element's ordinal >> position indicates its semantics (meaning, significance), and >> generally it won't make sense to iterate over the elements of a tuple >> (though naturally that doesn't stop people, and neither does the >> interpreter). > > def f(*a): ... > > is a fundamental language feature and really only makes sense in > the context of iterating over tuples. That's true, but given that individual arguments are bound to names in the local namespace I'd have to argue (if I wanted to argue at all) that the choice of a tuple over a list was pretty arbitrary, and that it would actually be "more Pythonic" to allow modification of the argument list in the same way as sys.argv is mutable. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From mcPas.De.Spam at mclaveauPas.De.Spam.com Fri Jun 8 22:51:04 2007 From: mcPas.De.Spam at mclaveauPas.De.Spam.com (Michel Claveau) Date: Sat, 09 Jun 2007 04:51:04 +0200 Subject: PythonS? Message-ID: Hi! Python, Iron-Python, Jython, StackLess-Python, Monty-Python, Movable-Python, etc. Shouldn't add a "S" to the end of "Python"? See: http://www.jfwilliam.com/Sites/1473/Python.jpg The fact of adding a "S" could constitute a PEP. for classification, I propose: PEP'S -- @-salutations Michel Claveau From josiah.carlson at sbcglobal.net Sun Jun 24 17:23:02 2007 From: josiah.carlson at sbcglobal.net (Josiah Carlson) Date: Sun, 24 Jun 2007 14:23:02 -0700 Subject: high performance/threaded applications in Python - your experiences? In-Reply-To: References: Message-ID: Ivan Voras wrote: > Jay Loden wrote: > >> I was hoping for some experiences that some of you on the list may have had in dealing with Python in a high performance and/or threaded environment. In essence, I'm wondering how big of a deal the GIL can be in a real-world scenario where you need to take advantage of multiple processor machines, thread pools, etc. How much does it get in the way (or not), and how difficult have you found it to architect applications for high performance? I have read a number of articles and opinions on whether or not the GIL is a good thing, and how it affects threaded performance on multiple processor machines, but what I haven't seen is experiences of people who have actually done it and reported back "it was a nightmare" or "it's no big deal" ;) > > The theory: If your threads mostly do IO, you can get decent CPU usage > even with Python. If the threads are CPU-bound (e.g. you do a lot of > computational work), you'll effectively only make use of one processor. > > In practice, I've noticed that Python applications don't scale very much > across CPUs even if they're doing mostly IO. I blame cache trashing or > similar effect caused by too many global synchronization events. I > didn't measure but the speedup may even be negative with large-ish > number of CPUs (>=4). > > OTOH, if you can get by with using forking instead of threads (given > enough effort) you can achieve very good scaling. Also, see the 'processing' package in the Python cheeseshop. It allows you to use processes rather than threads with most of the same abstractions. I hear it recently acquired the ability to pass file handles between processes on the same machine :) - Josiah From vinay_sajip at yahoo.co.uk Tue Jun 5 18:13:15 2007 From: vinay_sajip at yahoo.co.uk (Vinay Sajip) Date: Tue, 05 Jun 2007 15:13:15 -0700 Subject: Logging: how to suppress default output when adding handlers? In-Reply-To: References: <1181054185.267953.181050@p47g2000hsd.googlegroups.com> Message-ID: <1181081595.267993.266940@m36g2000hse.googlegroups.com> On Jun 5, 8:38 pm, Chris Shenton wrote: > Yeah, I think this is the cause. Unfortunately I'm using a couple > dozen files and a bunch more libraries and if they're doing a logging.debug() or whatnot they're creating this. I wouldn't have thought that well-written third party libraries (like SQLAlchemy) would log to the root logger. It's by logging to an application or library-specific logger that people can see where the events are being generated - logging to the root logger means a lot of useful information is lost. > Do you have any ideas how I can trace where the first call is made? > This seems a newbie question but if I have a bunch of other files > which do stuff like "from sqlalchemy import *" they might be invoking > a logging call so I'm not sure how to chase these down. I presume you are starting the ball rolling using one or more scripts. As long as you are not making logging calls at import time, then you can configure logging in your main script, e.g. if __name__ == "__main__": logging.basicConfigure(...) > > I'm dreading having to be so verbose with my (copious) loggers, which > is why I was curious if there was a way to nuke any auto-created > ones. I thought callinglogging.shutdown() before configuring my > loggers might do this but it didn't. > No need to be particularly verbose. One convention is for each module to: # for module foo/bar/baz.py # Near the top of the module... import logging logger = logging.getLogger("foo.bar.baz") # Then, in the rest of the module... logger.debug("Test debug output") # No more verbose than logging.debug("Test debug output") Even if you have a dozen files, it should be easy to do search/replace across them without too much trouble. Regards, Vinay Sajip From alexteo21 at yahoo.com Fri Jun 8 07:18:14 2007 From: alexteo21 at yahoo.com (alexteo21) Date: Fri, 08 Jun 2007 04:18:14 -0700 Subject: Does python 2.3.3 pty module has a bug? Message-ID: <1181301494.396782.295990@d30g2000prg.googlegroups.com> Hi, System: Solaris Python version: 2.3.3 For a automation job, I used pexpect module together with python for creating a ftp session automatically and downloading the file. I notice that after closing the child. The file descriptor is not closed (check /proc//fd) After running the script for a while, I start seeing too many files open error. I have a development machine running Linux using python 2.3.3. I execute the same code on it. The file descriptor is closed everytime after the pexpect child is closed. My question is - Is this a bug with pty module for solaris for python 2.3.3? Appreciate your comments Thanks, Alex From alvaro.nieto at gmail.com Fri Jun 1 08:00:33 2007 From: alvaro.nieto at gmail.com (=?iso-8859-1?q?=C1lvaro_Nieto?=) Date: Fri, 01 Jun 2007 05:00:33 -0700 Subject: logging module: log file with datetime Message-ID: <1180699233.916275.279330@u30g2000hsc.googlegroups.com> Hi I have this logging config file; ==================================================================== [loggers] keys=cdmto [handlers] keys=cdmtoHandler [formatters] keys=mtoFormatter [logger_cdmto] level=DEBUG handlers=cdmtoHandler qualname=cdmto propagate=0 [handler_cdmtoHandler] class=handlers.TimedRotatingFileHandler level=DEBUG formatter=mtoFormatter args=('./Logs/cdmto.log',) [formatter_mtoFormatter] format=%(asctime)s %(levelname)-8s %(filename)s[%(lineno)d]: % (message)s datefmt= ==================================================================== How could I define a log file with datetime in his name?. Now the name for log file is './Logs/cdmto.log' and I'd like it would be './ Logs/cdmto_20070601.log', for example. Thanks. From mail at timgolden.me.uk Sat Jun 2 14:47:32 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Sat, 02 Jun 2007 19:47:32 +0100 Subject: Python 2.3 ODBC Datetime limitations In-Reply-To: <4661A4A9.60805@holdenweb.com> References: <33cd6d8d0706011112w554ee6darea56f0977e9e3216@mail.gmail.com> <4661A4A9.60805@holdenweb.com> Message-ID: <4661BB44.1040005@timgolden.me.uk> Steve Holden wrote: > YuePing Lu wrote: >> Hello, >> >> Has any of you ever used Python odbc to retrieve data from a relational DB? >> >> I encountered a problem where it can't handle datetime _earlier than >> _*1969*, and _later than _*2040*. It just returned some garbage strings >> when I call str(my_date_object). >> >> When I call strptime to convert the value I got ValueError exception: >> >> # Table records >> for record in self._records: >> columns = [] >> for i in range(len(self._description)): >> if self._description[i][1]=='DATE': >> strDate=str(record[i]) >> try: >> #convert the date format to be mm/dd/yyyy: >> oDate=time.strptime(strDate) #convert to struct_time object >> strfDate=time.strftime("%m/%d/%Y", oDate) >> >> columns.append(strfDate) >> except ValueError, msg: >> raise "Date converstion error", msg >> >> ... >> Any other solutions that you've heard? >> >> Thanks very much in advance, >> > Reading the documentation for the time module, you will see: > > > The epoch is the point where the time starts. On January 1st of that > year, at 0 hours, the ``time since the epoch'' is zero. For Unix, the > epoch is 1970. To find out what the epoch is, look at gmtime(0). > > The functions in this module do not handle dates and times before the > epoch or far in the future. The cut-off point in the future is > determined by the C library; for Unix, it is typically in 2038. Maybe this is of use? http://timgolden.me.uk/python/win32_how_do_i/use-a-pytime-value.html (I think the dbidate values are pytime vals; if not, at least the principle is the same) TJG From me at privacy.net Sat Jun 2 16:59:57 2007 From: me at privacy.net (Mark Carter) Date: Sat, 02 Jun 2007 21:59:57 +0100 Subject: Python rocks In-Reply-To: References: <4661adda$0$19256$da0feed9@news.zen.co.uk> Message-ID: <4661da4f$0$19227$fa0fcedb@news.zen.co.uk> Josiah Carlson wrote: > Mark Carter wrote: >> Not that I'm particularly knowledgeable about language design issues, >> but maybe closures and slightly different scoping rules would be nice. > > Python has had closures for years. I just looked up http://www.secnetix.de/~olli/Python/lambda_functions.hawk and was amazed to discover that you were right. Nice one. > What kind of scoping did you desire? Well, I had in mind so that if you defined a function, but wanted to access a global var, that you didn't have to use the global keyword. Not much of a biggie, I guess. > Refuse the temptation to guess. As many people want to keep the > newlines as not (it disambiguates the case of end of file and blank > line), and it is a simple thing to deal with: line.rstrip('\r\n') . I guess that about wraps it up, then. Python pretty much has it all. Except for macros - which is not necessarily a dealbreaker, anyway. From tjreedy at udel.edu Fri Jun 8 12:57:42 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 8 Jun 2007 12:57:42 -0400 Subject: python integration References: <5452402.1181318335220.JavaMail.dasbury@mymail.indstate.edu> Message-ID: "Dee Asbury" wrote in message news:5452402.1181318335220.JavaMail.dasbury at mymail.indstate.edu... |I am looking for a method to integrate in Python, my problem is that I | do not want the summed up result. I need the result in the form of a | list (or array) with the x-values (or ranges) and the volume beneath | that section of the curve only. Run the integrator for each range you want an integration for. tjr From twisted0n3 at gmail.com Sun Jun 10 21:29:52 2007 From: twisted0n3 at gmail.com (Twisted) Date: Mon, 11 Jun 2007 01:29:52 -0000 Subject: The Concepts and Confusions of Prefix, Infix, Postfix and Fully Functional Notations In-Reply-To: References: <1179936917.652372.24780@q69g2000hsb.googlegroups.com> <1180508453.226022.44230@q19g2000prn.googlegroups.com> <1181335574.107472.229370@x35g2000prf.googlegroups.com> <1181358616.792797.97720@k79g2000hse.googlegroups.com> <1181414625.121073.203940@g4g2000hsf.googlegroups.com> <0uHai.176367$nh4.13819@newsfe20.lga> <1181448558.120521.63250@g4g2000hsf.googlegroups.com> <0G_ai.1970$xg4.809@trnddc08> Message-ID: <1181525392.369255.138460@h2g2000hsg.googlegroups.com> On Jun 10, 8:50 pm, "BCB" wrote: > I wholeheartedly agree, and did not mean to imply as much in my original > post, in which my intent was to emphasize the fact that, until you learn the > language, a J program /does/ resemble line noise! :-) Eh. This isn't right. The whole discussion was supposed to have died after the original Perl joke, certainly after the subsequent exclusion of joke and toy languages. I think I made it clear also that an editor's command set, Turing-complete though it may be, constitutes a toy language. Anyway I amend the original claim to cover joke languages, toy languages, and any write-only languages that mysteriously aren't considered to fall into either of the former two categories. After all, you can't really take a language seriously if it's either impossible to write unmaintainable code in it OR impossible to write maintainable code in it. The one is necessarily trivial, and the other unsuitable for anything serious, except as a machine-compiled intermediate format or a mechanism for assuring job security. From borud-news at borud.no Tue Jun 26 10:40:21 2007 From: borud-news at borud.no (Bjorn Borud) Date: 26 Jun 2007 16:40:21 +0200 Subject: The Modernization of Emacs: terminology buffer and keybinding References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182272495.990807.99110@a26g2000pre.googlegroups.com> <87tzt3ihev.fsf@kobe.laptop> <1182370216.961241.6960@n60g2000hse.googlegroups.com> <85zm2ufjpb.fsf@lola.goethe.zz> <1182372592.803332.288260@u2g2000hsc.googlegroups.com> <5dtk4tF34jrimU1@mid.dfncis.de> <1182375388.814275.227380@n2g2000hse.googlegroups.com> <87645h73ei.fsf@W0053328.mgh.harvard.edu> <1182548563.561252.82480@i13g2000prf.googlegroups.com> <1182666078.511962.280030@w5g2000hsg.googlegroups.com> Message-ID: [Twisted ] | | Really? None of this happens if you just do the straightforward file- | open command, which should obviously at least provide a navigable | directory tree, but definitely does not. well, if you insist on using Emacs in the most clumsy way possible, then of course, not it won't be easy. it is very obvious to any Emacs user that you haven't bothered learning Emacs at all. go away, troll. -Bj?rn From grahn+nntp at snipabacken.dyndns.org Wed Jun 20 13:08:56 2007 From: grahn+nntp at snipabacken.dyndns.org (Jorgen Grahn) Date: 20 Jun 2007 17:08:56 GMT Subject: Python and (n)curses References: <1182211133.956524.160020@g4g2000hsf.googlegroups.com> <87y7igzapo.fsf@benfinney.id.au> <1182246189.210723.16280@w5g2000hsg.googlegroups.com> <1182325869.237652.157800@c77g2000hse.googlegroups.com> Message-ID: On Wed, 20 Jun 2007 00:51:09 -0700, peter wrote: > >> > For me, introducing similar commands in Python would be by far the biggest single improvement that could be made to the language. > >> If it should be done, it should be done as a compatible subset of >> curses, IMHO. It has such a long history as the standard "GUI toolkit" > > But curses doesn't run under Windows - thats the whole point! I meant to say "as a compatible subset of the Python 'curses' module API". I don't know what's so difficult about porting curses. Maybe it's that the DOS console is too broken, or maybe too many Unixisms are exposed by the API (can you get a signal when the DOS console window is resized?). (Alex Martelli simply wrote something like this in his Python book: "I hear about curses ports to Windows now and then, but I've never seen one that worked". Something like that.) /Jorgen -- // Jorgen Grahn R'lyeh wgah'nagl fhtagn! From doulos05 at gmail.com Tue Jun 5 08:27:58 2007 From: doulos05 at gmail.com (JonathanB) Date: Tue, 05 Jun 2007 05:27:58 -0700 Subject: *args and **kwargs Message-ID: <1181046478.824231.117300@q75g2000hsh.googlegroups.com> Ok, this is probably definitely a newbie question, but I have looked all over the Python library reference material and tutorials which I can find online and I cannot find a clear definition of what these are and more importantly how to use them. From what I can tell from their use in the examples I've seen, they are for passing a variable number of arguments to a function (which I need to do in a program I am working on). But how do you use them? Is there a fixed order in which the arguments within *arg or **kwarg should be passed or will be called within a function? I realize this probably involves a long- winded answer to a very simple and common programming problem, so if someone has a link to TFM, I'll gladly go RTFM. I just can't find it. From NunezD at gmail.com Fri Jun 22 15:28:49 2007 From: NunezD at gmail.com (hiro) Date: Fri, 22 Jun 2007 19:28:49 -0000 Subject: comparing two lists and returning "position" In-Reply-To: <1182535227.400136.199590@m36g2000hse.googlegroups.com> References: <1182481876.028589.71710@x35g2000prf.googlegroups.com> <7xvedg4n2d.fsf@ruckus.brouhaha.com> <467b624e$0$16271$c30e37c6@lon-reader.news.telstra.net> <1182493019.795629.108860@w5g2000hsg.googlegroups.com> <1182534010.884992.119690@u2g2000hsc.googlegroups.com> <1182535097.054481.296050@p77g2000hsh.googlegroups.com> <1182535227.400136.199590@m36g2000hse.googlegroups.com> Message-ID: <1182540529.025958.136110@i13g2000prf.googlegroups.com> On Jun 22, 2:00 pm, hiro wrote: > On Jun 22, 1:58 pm, hiro wrote: > > > > > On Jun 22, 1:56 pm, Marc 'BlackJack' Rintsch wrote: > > > > In <1182534010.884992.119... at u2g2000hsc.googlegroups.com>, hiro wrote: > > > > Hi once again, Charles.. I have tried your approach in my data set l2 > > > > and it keeps crashing on me, > > > > bare in mind that I have a little over 10 million objects in my list > > > > (l2) and l1 contains around 4 thousand > > > > objects.. (i have enough ram in my computer so memory is not a > > > > problem) > > > > > python 2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit > > > > (Intel)] on win32 > > > > > error is : ValueError: list.index(x): x not in list > > > > So you are saying you get this error with the value of `x` actually in the > > > list!? Somehow hard to believe. > > > > Ciao, > > > Marc 'BlackJack' Rintsch > > > yes I do > > I doubled, trippled check my data already (even doing a search by hand > using vim) and the data is fine. Still looking into it though hahaha, K found out what was wrong.. in the function computing the data for l1 there was extra space was being put in. ie: l1 = [ 'abc ' 'ghi ' 'mno ' ] and I didn't strip it properly after splitting it.. silly me, well.. live and learn.. thanks guys Cheers, -h From grante at visi.com Thu Jun 7 18:42:17 2007 From: grante at visi.com (Grant Edwards) Date: Thu, 07 Jun 2007 22:42:17 -0000 Subject: Running a process every N days References: <1181255261.648057.184930@x35g2000prf.googlegroups.com> Message-ID: <136h2e9ko14b966@corp.supernews.com> On 2007-06-07, danmcleran at yahoo.com wrote: > What's the best way to run either an entire python process or a python > thread every N days. man cron man 5 crontab -- Grant Edwards grante Yow! It don't mean a at THING if you ain't got visi.com that SWING!! From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Thu Jun 28 08:38:23 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Thu, 28 Jun 2007 14:38:23 +0200 Subject: Too many 'self' in python.That's a big flaw in this language. References: <1182942154.185461.89620@e9g2000prf.googlegroups.com> <5efe34F37shinU1@mid.individual.net> <1i0e2aq.1db0o2mbi0je1N%aleax@mac.com> Message-ID: <5ehodvF38ov3jU1@mid.individual.net> Alex Martelli wrote: > Bjoern Schliessmann > wrote: >> Mh, strange, I personally like to use "this.a" in C++, to make >> clear I use an instance variable. > That would be nice, unfortunately your C++ compiler will refuse > that, and force you to use this->a instead;-). Sure, thanks. Before I last used C++ I was forced to use Java -- where I would write "this.". ;) > Many programming shops use naming conventions instead, such as > my_a or a_ (trailing underscore for member-variables) -- I've even > seen the convention this_a which IMHO is silly (at that point you > might as well use this->a and avoid the 'convention'!-). ACK. > For the curious: the explicit-self idea is essentially taken from > Modula-3, a sadly now forgotten language which still had an impact > on the history of programming. Mh, I'm going to read some about this one. Regards, Bj?rn -- BOFH excuse #4: static from nylon underwear From gherron at islandtraining.com Sun Jun 10 00:06:43 2007 From: gherron at islandtraining.com (Gary Herron) Date: Sat, 09 Jun 2007 21:06:43 -0700 Subject: urllib2 - iteration over non-sequence In-Reply-To: <7x3b10pnwq.fsf@ruckus.brouhaha.com> References: <1181427526.996101.75230@m36g2000hse.googlegroups.com> <466B2AA7.3040704@websafe.com> <1181429903.533207.105730@p77g2000hsh.googlegroups.com> <7x3b10pnwq.fsf@ruckus.brouhaha.com> Message-ID: <466B78D3.3000300@islandtraining.com> Paul Rubin wrote: > Erik Max Francis writes: > >> This is really wasteful, as there's no point in reading in the whole >> file before iterating over it. To get the same effect as file >> iteration in later versions, use the .xreadlines method:: >> >> for line in aFile.xreadlines(): >> ... >> > > Ehhh, a heck of a lot of web pages don't have any newlines, so you end > up getting the whole file anyway, with that method. Something like > > for line in iter(lambda: aFile.read(4096), ''): ... > > may be best. > Certainly there's are cases where xreadlines or read(bytecount) are reasonable, but only if the total pages size is *very* large. But for most web pages, you guys are just nit-picking (or showing off) to suggest that the full read implemented by readlines is wasteful. Moreover, the original problem was with sockets -- which don't have xreadlines. That seems to be a method on regular file objects. For simplicity, I'd still suggest my original use of readlines. If and when you find you are downloading web pages with sizes that are putting a serious strain on your memory footprint, then one of the other suggestions might be indicated. Gary Herron From nagle at animats.com Tue Jun 19 15:08:40 2007 From: nagle at animats.com (John Nagle) Date: Tue, 19 Jun 2007 12:08:40 -0700 Subject: The Modernization of Emacs In-Reply-To: <878xag1gu3.fsf@mail.eng.it> References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <873b0p9vpm.fsf@W0053328.mgh.harvard.edu> <878xag1gu3.fsf@mail.eng.it> Message-ID: Gian Uberto Lauri wrote: >>>>>>"GB" == Galen Boyer writes: > > > GB> Most other environments will be for those just trying to perform > GB> their tasks and staying even with the average proficiency chart. Oh, please. The "I'm so l33t" thing. I used EMACS back in the LISP era, but really, that approach is mostly of historical interest at this late date. John Nagle From warren at muse.com Sat Jun 9 12:37:16 2007 From: warren at muse.com (Warren Stringer) Date: Sat, 9 Jun 2007 09:37:16 -0700 Subject: Hooking exceptions outside of call stack Message-ID: <001f01c7aab4$71153940$240110ac@Muse> Here is what I would like to do: #------------------------------------------------------------ a = Tr3() # implements domain specific language a.b = 1 # this works, Tr3 overrides __getattr__ a.__dict__['b'] = 2 # just so you know that b is local a[b] = 3 # I want to resolve locally, but get: Traceback (most recent call last): ... exec cmd in globals, locals ... NameError: global name 'b' is not defined #------------------------------------------------------------ So far, I've tried capturing exceptions in __getattr__, __setitem__, and __setattr__, with no luck. I do NOT want to put `a[b]=3` inside a try...except block because I want to enable a command line `>>>a[b]=3` Is there a way to hook a NameError exception outside of the call stack? Perhaps, inside Tr3.__init__ ? Is there a way of putting back unhandled NameError exceptions, so that they unwind the stack normally? This is intended for production code. Many thanks! Warren From bruno.42.desthuilliers at wtf.websiteburo.oops.com Wed Jun 27 10:03:39 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Wed, 27 Jun 2007 16:03:39 +0200 Subject: PEP 3107 and stronger typing (note: probably a newbie question) In-Reply-To: References: <1182369568.941307.316260@p77g2000hsh.googlegroups.com> <5dveb4F360un0U1@mid.individual.net> <467a9209$0$22165$426a74cc@news.free.fr> <1182858785.886469.93060@n60g2000hse.googlegroups.com> <46824d8d$0$2324$426a74cc@news.free.fr> Message-ID: <46826e38$0$2818$426a74cc@news.free.fr> Stephen R Laniel a ?crit : > On Wed, Jun 27, 2007 at 01:44:17PM +0200, Bruno Desthuilliers wrote: >> Indeed - static typing is for compilers, not for programmers. > > When done well, static typing helps the programmer The closer thing to "well done static typing" I know is type inference (? la O'Caml). And I don't find it that helpfull to the programmer - here again, it's mainly to allow compile-time optimizations. (snip) > The example toward the end of how ML actually spots an > infinite loop at compile time seems to me to be "for > programmers" rather than "for compilers." It's been a long time since I last got into such a problem. Which BTW was very quickly spotted and fixed. Compared to what I would loose, I don't think this kind of "help" is so useful. Stephen, you may not know yet, but Python is *dynamic*. This defeats almost all compile-time checking. Of what help would type inference be when you can dynamically add/remove/replace attributes (including methods and class) at runtime ? From bj_666 at gmx.net Fri Jun 1 03:20:11 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Fri, 01 Jun 2007 09:20:11 +0200 Subject: strange PyLint configuration References: <1180613790.317480.314600@p47g2000hsd.googlegroups.com> <5c8glhF2tra7sU1@mid.individual.net> <5c8q4eF2vg743U1@mid.individual.net> Message-ID: In <5c8q4eF2vg743U1 at mid.individual.net>, Bjoern Schliessmann wrote: > [ripped out of context :-)] > Has this been updated recently? I could've sworn I had read that > stuff like has_key was "old". Yes, `has_key()` is "old", it's spelled ``in`` these days. :-) if mapping.has_key(ham): pass # -> if ham in mapping: pass Ciao, Marc 'BlackJack' Rintsch From wildemar at freakmail.de Tue Jun 5 08:42:04 2007 From: wildemar at freakmail.de (Wildemar Wildenburger) Date: Tue, 05 Jun 2007 14:42:04 +0200 Subject: *args and **kwargs In-Reply-To: <1181046478.824231.117300@q75g2000hsh.googlegroups.com> References: <1181046478.824231.117300@q75g2000hsh.googlegroups.com> Message-ID: <46655A1C.9030401@freakmail.de> JonathanB wrote: > Ok, this is probably definitely a newbie question, but I have looked > all over the Python library reference material and tutorials which I > can find online and I cannot find a clear definition of what these are > and more importantly how to use them. From what I can tell from their > use in the examples I've seen, they are for passing a variable number > of arguments to a function (which I need to do in a program I am > working on). But how do you use them? Is there a fixed order in which > the arguments within *arg or **kwarg should be passed or will be > called within a function? I realize this probably involves a long- > winded answer to a very simple and common programming problem, so if > someone has a link to TFM, I'll gladly go RTFM. I just can't find it. > > http://www.python.org/doc/faq/programming/#how-can-i-pass-optional-or-keyword-parameters-from-one-function-to-another (the first hit when you search python.org for *args and **kwargs) Basically 'args' is a tuple with all the positional arguments, kwargs is a dictionary with all the named arguments. Likewise you can pass a tuple to a function like func(*tuple), or a dict like func(**dictionary) or both, where the zuple has to come first. From python at jayloden.com Mon Jun 18 15:16:42 2007 From: python at jayloden.com (Jay Loden) Date: Mon, 18 Jun 2007 15:16:42 -0400 Subject: avoid script running twice In-Reply-To: <4676AB35.7060500@chamonix.reportlab.co.uk> References: <4676AB35.7060500@chamonix.reportlab.co.uk> Message-ID: <4676DA1A.4090508@jayloden.com> Robin Becker wrote: > I wish to prevent a python script from running twice; it's an hourly job, but > can take too long. > > My simplistic script looks like > > > ....... > def main(): > fn = 'MARKER' > if os.path.isfile(fn): > log('%s: hourly job running already' % formatTime()) > else: > f = open(fn,'w') > f.write(str(os.getpid())) > f.close() > try: > work() > finally: > os.remove(fn) > > if __name__=='__main__': > main() > > but it occurs to me that I might be killed with prejudice during the long > running work(). Is there a smart way to avoid running simultaneously. You could also write the PID of the currently running process into your MARKER file, rather than just using an empty file. Then if your file exists, you can compare against os.getpid() and decide what to do from there, like killing your existing script, check to see if that PID is still active on the system, etc. I've also seen this done by checking the age of the lock file and if it's too old, consider it 'stale' and delete it. -Jay From steve at REMOVE.THIS.cybersource.com.au Fri Jun 22 23:42:51 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sat, 23 Jun 2007 13:42:51 +1000 Subject: Python's "only one way to do it" philosophy isn't good? References: <1181368143.874341.273140@r19g2000prf.googlegroups.com> <7x3b0nmkk6.fsf@ruckus.brouhaha.com> Message-ID: On Fri, 22 Jun 2007 13:54:35 -0400, Douglas Alan wrote: >> Python already allows me to shoot myself in the foot, if I wish. I'm >> comfortable with that level of freedom. I'm not necessarily comfortable >> with extensions to the language that would allow me the freedom to shoot >> myself in the head. > > Lisp macros don't let you shoot yourself in the head -- only in the > foot. Being able to do > > True = False > > is being able to shoot yourself in the head. And Python certainly > lets you do that. True, that is a current piece of badness. There are arguments for and against making True and False reserved words, like None. Nevertheless, in Python 1+2 always equals 3. You can't say the same thing about Lisp. >> I would need to be convinced of the advantages, as would many other >> people, including the BDFL. > > The proof is in the pudding for anyone who has seen the advantages it > brings to Lisp. As Paul Graham points out, it's hard to look up and > see the advantages of what is up there in a more powerful language. > It's only easy to look down and see the disadvantages of what is missing > from a less powerful language. To understand the advantages, one has to > be willing to climb the hill and take in the view. I don't accept Graham's reasoning. I think that it is true that people's *values* change, as they get more familiar with a more powerful language. For instance, I used to write Pascal code on a Mac, and I avoided object-oriented techniques because they were too inefficient and slow. (E.g. when Apple released System 7, which used OO code extensively, even the most one-eyed Mac fan boys had to admit that the Finder ran like a dog compared to System 6.) But the advantages were obvious, even before I had experience with OO design. Now, I use Python, which is all object-oriented -- but the hardware I run it on is so much faster that I care more about the programmer productivity (my time) than about the efficiency of the executed code (the computer's time). But if I were still running on a 1988-vintage Mac, you better believe I wouldn't be making the same trade-offs I am now. So, quite frankly, the things which you and Graham value in Lisp *simply don't interest me*. It isn't that I can't see the advantages. They just don't matter to me, in fact in some ways they are disadvantages. Could my opinion ever change? Of course it could. I might, for example, suddenly have a burning passion about language design, or find some problem that is really painful under Python, and then I might go searching for "a more powerful language". One doesn't need to be familiar with more powerful languages to be aware that they offer benefits that less powerful languages don't. Or some really smart people might come up with a macro system that reduces the disadvantages while keeping the advantages, and then dealing with some random module developer's syntax extensions no more frightening than dealing with some random module developer's functions. (Considering the poor design and shoddy code of some modules I've had to deal with, I really worry about giving developers the ability to redefine syntax too.) [snip] >> let alone whether the benefits would outweigh the costs, > > They pay off in boatloads in the Lisp community. But do they? Where is the standard library containing all these magnificent macros? Forcing people to implement basic things from scratch doesn't sound like a pay-off to me. It seems that one of the major costs of having an extremely minimalist, but easily extensible, syntax is that it encourages massive re-invention of the wheel. Things get moved into the language slowly, because it is so easy to work around the lack -- but the cost is a proliferation of different macros all doing the same thing. I think Python has the better philosophy. Python has one really good syntax, minimalistic but not _overly_ minimalistic, not an easily extensible syntax. The cost is that there are some things which could be easier, if the syntax were different, but the benefit is that I don't have to write syntax-extending macros, or debug them, or learn somebody else's. Once every few years, Python introduces a new syntax, e.g. list comprehensions, after much thought. That's better than every time I use a different library or module. -- Steven. From durumdara at gmail.com Thu Jun 7 06:09:43 2007 From: durumdara at gmail.com (durumdara) Date: Thu, 07 Jun 2007 12:09:43 +0200 Subject: Where can I suggest an enchantment for Python Zip lib? Message-ID: <4667D967.4070200@gmail.com> Hi! Where can I ask it? I want to ask that developers change the Python's Zip lib in the next versions. The Zip lib not have a callback procedure. When I zip something, I don't know, what is the actual position of the processing, and how many bytes remaining. It is simply rewriteable, but when I get new Python, it is forget this thing again... So some callback needed for it, if possible. With this I can abort processing and I can show the actual state when I processing a large file. See this thread: http://groups.google.com.kh/group/comp.lang.python/browse_thread/thread/c6069d12273025bf/18b9b1c286d9af7b?lnk=st&q=python+zip+callback&rnum=1#18b9b1c286d9af7b Thanks for your help: dd From claird at lairds.us Tue Jun 5 18:53:38 2007 From: claird at lairds.us (Cameron Laird) Date: Tue, 5 Jun 2007 22:53:38 +0000 Subject: which "GUI module" you suggest me to use? References: Message-ID: In article , ZioMiP wrote: >Hi to all... > >I'm actually using Tkinter for my GUI... but I need to "put a piece of a >web-page in a widget" how can I do? > >which GUI module do you suggest me to use for do that? > >or which GUI module do you suggest me to use at all? > >I'm acutally using Windows Xp but I also use Linux... > >I know that WxPython work only under Windows and PyGTK work only under >Linux... there's some other modules? ? wxPython is available for Linux and Mac OS X. PyGTK is available for Windows. Apparently you want to embed Web content in a Tkinter widget. There are several ways to do this. Do you need a live browser, or is it enough to render HTML? From zacherates at gmail.com Thu Jun 21 22:14:03 2007 From: zacherates at gmail.com (zacherates) Date: Fri, 22 Jun 2007 02:14:03 -0000 Subject: possible to preserve subprocess.Popen objects for later? In-Reply-To: <1182465149.925859.124630@n2g2000hse.googlegroups.com> References: <1182465149.925859.124630@n2g2000hse.googlegroups.com> Message-ID: <1182478443.738912.47940@q19g2000prn.googlegroups.com> On Jun 21, 6:32 pm, Ratko wrote: > Hi all, > > I have a python gui app that launches multiple applications using > subprocess.Popen class and prints their output in the gui (using > PIPEs, threads and wxPython). Everything works great but the problem > is that some applications should run in the background (ie they don't > close when the gui closes) so next time when you start the gui it will > not have a handle on those processes that are still running and > therefore won't be able to print their output. > > So, I was wondering if there is any way to "preserve" the Popen object > of those background processes and reload them when the gui is > restarted? Ideally I would like to have the whole Popen object > preserved but I could also get by with just the Popen.stdout file > object. I can save the Popen.stdout.fileno() integer because that's > what I use in os.read() to read the output anyway but that doesn't > work. > > I have doubts that this could even conceptually work but I thought I'd > try asking anyway. I don't have a full understanding of how processes > and pipes work on the system level... > > Thanks, > Ratko Sounds like you might want to consider running the backround task as either a service or daemon and communicate via a TCP/IP connection or a named pipe rather than using STDIN/OUT. Actually you could use either idea without actually setting up a daemon. Also, you're generally supposed to wait() for your children to die (even if you stop the gui) rather than let them become zombies. Cheers, Aaron From buzzard at urubu.freeserve.co.uk Mon Jun 11 11:44:09 2007 From: buzzard at urubu.freeserve.co.uk (Duncan Smith) Date: Mon, 11 Jun 2007 16:44:09 +0100 Subject: skip next item in list In-Reply-To: <1181573389.186279.108590@g37g2000prf.googlegroups.com> References: <1181573389.186279.108590@g37g2000prf.googlegroups.com> Message-ID: ahlongxp wrote: > list=('a','d','c','d') > for a in list: > if a=='a' : > #skip the letter affer 'a' > > what am I supposed to do? > Maybe, >>> it = iter(['a','d','c','d']) >>> for item in it: print item if item == 'a': x = it.next() a c d >>> The binding of a name to it.next() is unnecessary. It just prevents 'd' being printed. Duncan From showell30 at yahoo.com Mon Jun 4 07:56:22 2007 From: showell30 at yahoo.com (Steve Howell) Date: Mon, 4 Jun 2007 04:56:22 -0700 (PDT) Subject: subexpressions (OT: math) In-Reply-To: <4663FC67.5020009@freakmail.de> Message-ID: <282933.38731.qm@web33506.mail.mud.yahoo.com> --- Wildemar Wildenburger wrote: > > > Oh my, remember when we used to discuss murderous > snakes and silly > British comedians on this group? > I hardly do ... > /W Although all of us are mere amateurs in this business of making parameters when it's circles in question I have a suggestion: Try not to forget the diameters. More here: http://www.xs4all.nl/~jcdverha/scijokes/1_4.html ____________________________________________________________________________________ Building a website is a piece of cake. Yahoo! Small Business gives you all the tools to get online. http://smallbusiness.yahoo.com/webhosting From python at hope.cz Fri Jun 15 05:56:12 2007 From: python at hope.cz (Johny) Date: Fri, 15 Jun 2007 02:56:12 -0700 Subject: WebThumb Message-ID: <1181901372.058925.322830@w5g2000hsg.googlegroups.com> How can I get a website thumbnail? I would like to allow visitors to add their URLs to our pages with the thumbnail of their website. Can anyone suggest a solution for web thumbnails? Thanks L. From stefan.behnel-n05pAM at web.de Fri Jun 15 14:01:06 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Fri, 15 Jun 2007 20:01:06 +0200 Subject: Output of HTML parsing In-Reply-To: <1181915875.875312.137080@z28g2000prd.googlegroups.com> References: <1181915875.875312.137080@z28g2000prd.googlegroups.com> Message-ID: <4672D3E2.6050908@web.de> Jackie wrote: > I want to get the information of the professors (name,title) from the > following link: > > "http://www.economics.utoronto.ca/index.php/index/person/faculty/" That's even XHTML, no need to go through BeautifulSoup. Use lxml instead. http://codespeak.net/lxml > Ideally, I'd like to have a output file where each line is one Prof, > including his name and title. In practice, I use the CSV module. > ---------------------------------------------------- > > import urllib,re,csv > > url = "http://www.economics.utoronto.ca/index.php/index/person/ > faculty/" > > sock = urllib.urlopen(url) > htmlSource = sock.read() > sock.close() import lxml.etree as et url = "http://www.economics.utoronto.ca/index.php/index/person/faculty/" tree = et.parse(url) > namePattern = re.compile(r'class="name">(.*)') > titlePattern = re.compile(r', (.*)\s*') > > name = namePattern.findall(htmlSource) > title_temp = titlePattern.findall(htmlSource) > title =[] > for item in title_temp: > item_new=" ".join(item.split()) #Suppress the > spaces between 'title' and > title.extend([item_new]) > > > output =[] > for i in range(len(name)): > output.insert(i,[name[i],title[i]]) #Generate a list of > [name, title] # untested get_name_text = et.XPath('normalize-space(td[a/@class="name"]') name_list = [] for name_row in tree.xpath('//tr[td/a/@class = "name"]'): name_list.append( tuple(get_name_text(name_row).split(",", 3) + ["","",""])[:3] ) > writer = csv.writer(open("professor.csv", "wb")) > writer.writerows(output) #output CSV file writer = csv.writer(open("professor.csv", "wb")) writer.writerows(name_list) #output CSV file > -------------- End of Program > ---------------------------------------------- > > 3.Should I close the opened csv file("professor.csv")? How to close > it? I guess it has a "close()" function? Stefan From jwkenne at attglobal.net Mon Jun 18 22:48:37 2007 From: jwkenne at attglobal.net (John W. Kennedy) Date: Mon, 18 Jun 2007 22:48:37 -0400 Subject: MI5 Persecution: Goldfish and Piranha 29/9/95 (5104) In-Reply-To: References: Message-ID: <8uHdi.1143$YF6.256@newsfe12.lga> Mike wrote: > And this is here because ....??? He's a broadband-spamming mental case. Plonk him and move on. -- John W. Kennedy If Bill Gates believes in "intelligent design", why can't he apply it to Windows? From siona at chiark.greenend.org.uk Thu Jun 7 07:18:26 2007 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 07 Jun 2007 12:18:26 +0100 (BST) Subject: Integer division References: <1181207216.890336.99990@r19g2000prf.googlegroups.com> Message-ID: jm.suresh at no.spam.gmail.com wrote: > 3/2 => 1 # Usual behavior > some_func(3, 2) => 2 # Wanted def some_func(a, b): return -(-a/b) And people complain about Python's behaviour regarding division of negative integers. -- \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 evan at yelp.com Thu Jun 21 12:15:13 2007 From: evan at yelp.com (Evan Klitzke) Date: Thu, 21 Jun 2007 09:15:13 -0700 Subject: Downloading from a clean url In-Reply-To: <1182430052.176397.289060@q75g2000hsh.googlegroups.com> References: <1182392457.751054.173500@n60g2000hse.googlegroups.com> <1182430052.176397.289060@q75g2000hsh.googlegroups.com> Message-ID: On 6/21/07, D.Hering wrote: > > Evan Klitzke wrote: > > On 6/20/07, D.Hering wrote: > > > General: > > > How do I download a page's data from a clean url. > > > > > > Specific: > > > I'm using PyQt's QHttp and QUrl classes for requests and acquiring the > > > response, but I can't figure out how to access a page's data without > > > knowing the file of the url's path. For instance http://kde.org > > > > If the page is omitted, as in your example of http://kde.org, the page is / > > Right, but so far I'm not able to get a response unless I actually > provide the actual page and it's extension in the path of the url. For > instance /page.html or /this/path/to/page.html ...etc. If that's the case, it sounds like the web server on the other end is misconfigured (or maybe you're getting a 302 or something like that). Install LiveHTTP Headers and see how your browser navigates to the page. -- Evan Klitzke From steve at holdenweb.com Mon Jun 25 11:37:31 2007 From: steve at holdenweb.com (Steve Holden) Date: Mon, 25 Jun 2007 11:37:31 -0400 Subject: How to save initial configuration? (program installation) In-Reply-To: <1182784412.829377.265320@q75g2000hsh.googlegroups.com> References: <1182783746.718276.209460@w5g2000hsg.googlegroups.com> <1182784231.530101.258640@q75g2000hsh.googlegroups.com> <1182784412.829377.265320@q75g2000hsh.googlegroups.com> Message-ID: Jason Zapman II wrote: > On Jun 25, 11:10 am, kyoso... at gmail.com wrote: >> I would think you could pop-up some dialog when the program is first >> run to ask where they want the file to be. On the first run though, >> you can just have the config file located in the current working >> directory with the script file itself. Then just move it or save a new >> copy to the new location and delete the original. > > The 'pop-up' is easy. The problem is how does the program know where > it's state file is the SECOND time it is run? I can't stash it in the > state file, since the program won't know where it is if it's not in > the CWD... (unless I'm missing something obvious). > > The traditional choices are the registry for Windows, and the /etc subtree for the various, almost uncountable, flavors of Unix and nixalikes. You're right, it's much more difficult per-system than per-user, since there are so many conventions. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From me at privacy.net Sun Jun 17 14:26:59 2007 From: me at privacy.net (mark carter) Date: Sun, 17 Jun 2007 19:26:59 +0100 Subject: sqlite3 bug?? In-Reply-To: References: <46752230$0$31685$db0fefd9@news.zen.co.uk> <46753426$0$30325$fa0fcedb@news.zen.co.uk> <1182091411.108272.286280@o61g2000hsh.googlegroups.com> Message-ID: <46757cf6$0$27845$db0fefd9@news.zen.co.uk> Carsten Haese wrote: > On Sun, 2007-06-17 at 07:43 -0700, 7stud wrote: >> Please report the whole docs as a bug. > > I imagine the author appreciates constructive criticism. This is not > constructive criticism. > > In other words: Pointing out specific shortcomings and ways to correct > them, such as what the OP is doing, is helpful. Calling the entire docs > a bug is not helpful. You'll be pleased to know that I was specific, and I suggested a change that I thought would be good. Actually, I think the docs are quite good! I went hunting around some Scheme implementations lately. What was immediately apparent to me was that the docs weren't nearly as good as those for python. Typical problems centre about what modules I was supposed to load, and how I was supposed to use them. What might be obvious to an old hand might not be obvious to someone coming in from fresh. This is where big projects like Python tend to score - the docs have been through many iterations. From frank at chagford.com Sat Jun 9 04:04:20 2007 From: frank at chagford.com (Frank Millman) Date: Sat, 09 Jun 2007 01:04:20 -0700 Subject: Working with fixed format text db's In-Reply-To: References: Message-ID: <1181376260.193715.51330@q66g2000hsg.googlegroups.com> On Jun 8, 5:50 pm, Neil Cerutti wrote: > Many of the file formats I have to work with are so-called > fixed-format records, where every line in the file is a record, > and every field in a record takes up a specific amount of space. > > For example, one of my older Python programs contains the > following to create a fixed-format text record for a batch of new > students: > > new = file("new.dat", "w") > if not new: > print "Error. Could not open file new.dat for writing." > raw_input("Press Return To Exit.") > sys.exit(1) > > for s in freshmen: > new.write(s.ssn.ljust(9)) > new.write(s.id.ljust(10)) > new.write(s.last[:16].ljust(16)) > new.write(s.first[:11].ljust(11)) > new.write(' '.ljust(10)) # Phone Number > new.write(' '.ljust(1254)) # Empty 'filler' space. > new.write('2813 ') > new.write(s.major.ljust(5)) > I have to do this occasionally, and also find it cumbersome. I toyed with the idea of posting a feature request for a new 'fixed length' string formatting operator, with optional parameters for left/ right-justified and space/zero-filled. We already have '%-12s' to space fill for a length of 12, but it is not truly fixed-length, as if the value has a length greater than 12 you need it to be truncated, and this construction will not do that. Assume we have a new flag '!n', which defaults to left-justified and space-filled, but allows an optional 'r' and '0' to override the defaults. Then the above example could be written as format = '%!9s%!10s%!16s%!11s%!10s%!1254s%!6s%!5s' for s in freshmen: new.write (format % (s.ssn,s.id,s.last,s.first, ' ',' ','2813',s.major)) I never felt strongly enough about it to propose it, but I thought I would mention it. Frank Millman From jacob at cd.chalmers.se Fri Jun 8 04:32:20 2007 From: jacob at cd.chalmers.se (Jacob Hallen) Date: Fri, 8 Jun 2007 08:32:20 +0000 (UTC) Subject: ten small Python programs References: Message-ID: In article , Steve Howell wrote: >I've always thought that the best way to introduce new >programmers to Python is to show them small code >examples. Something like this: http://www.lava.se/sam/ Jacob Hall??n -- From rodolfo.ueg at gmail.com Fri Jun 22 02:14:39 2007 From: rodolfo.ueg at gmail.com (Rodolfo S. Carvalho) Date: Fri, 22 Jun 2007 03:14:39 -0300 Subject: Problems with HTTP Request Message-ID: Hi folks! I'm writing my own web server in python, and I'm getting problems to handle POST requests. This is a snippet of my code (of an HttpRequest class): try: length = int(self.myRequestHandler.headers.get('content-length', 0)) except ValueError: length = 0 pdata = self.myRequestHandler.rfile.read(length) # extract POST data from pdata The application is executed normally, the response is sent back to the client, but something is keeping the connection open. I discovered that the problem is in the lines above, but no exception is raised. I tested replacing this line: pdata = self.myRequestHandler.rfile.read(length) by this: pdata = self.myRequestHandler.rfile.read(length-1) On this way, the web server works fine, and close the connection after response ends. But my request is uncomplete, because the last char is not readed. I don't know what to do anymore. I need help =/ Thanks in advance. -- Rodolfo Carvalho Web Developer rodolfo.ueg at gmail.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From nospam at nospam.com Thu Jun 7 10:53:46 2007 From: nospam at nospam.com (Mark T) Date: Thu, 7 Jun 2007 07:53:46 -0700 Subject: Why can not catch the inner exception References: <1181215054.826742.75930@n15g2000prd.googlegroups.com> Message-ID: "???????????????" wrote in message news:1181215054.826742.75930 at n15g2000prd.googlegroups.com... > Please see the follow code, I can not catch the exception " IOError" > raised from shutil.copyfile() , why? > try: > if (DEST_TYPE & TYPE_FTP): > fn = oname > ftpc.UploadFile(f, fn) > else: > fn = os.path.join(dst, oname) > shutil.copyfile(f, fn) > > .... other code.... > > except [IOError, FtpcException],why: > num = 0 > print >>sys.stderr, "can not copy '%s' to '%s': > %s"%(f, fn, why) > ERR_NUM += 1 > > I must do like this: > try: > if (DEST_TYPE & TYPE_FTP): > fn = oname > ftpc.UploadFile(f, fn) > else: > fn = os.path.join(dst, oname) > try: > shutil.copyfile(f, fn) > except IOError: > .... > > .... other code.... > > except [IOError, FtpcException],why: > num = 0 > print >>sys.stderr, "can not copy '%s' to '%s': > %s"%(f, fn, why) > ERR_NUM += 1 > > Thanks! > ??, Use a tuple (IOError,FtpcException) instead of a list in the except statement and it works. --?? From kennerly at finegamedesign.com Fri Jun 22 02:45:25 2007 From: kennerly at finegamedesign.com (Ethan Kennerly) Date: Thu, 21 Jun 2007 23:45:25 -0700 Subject: Python IDE Message-ID: <20070622064543.C70351E4009@bag.python.org> xhm wrote: > PyScripter http://mmm-experts.com/Downloads.aspx?ProductId=4 If PyScripter is your style, Stani's Python Editor also is feature-rich and GUIy. Stani's Python Editor http://pythonide.blogspot.com/ It's got winpdb and a shell integrated. Although, from reading this thread, I've gone back to gVim, after years of absence. Since I already had to memorize the keyboard mapping for older projects, and I prefer unix-style regular expressions, gVim is awesome. But if you don't want to memorize keyboard commands, vim is not for you. I like unit testing by running the unit test and appending the output to my development journal (With the "r !python" syntax). That way I have an ongoing record of problems and progress. I also agree with the philosophy that Ben echoed: Ben wrote: > GNU screen, Emacs or Vim, and Bash. The right tool for each job, and tools > that work well together, rather than a single tool trying to do everything > in its own isolated world. What I'm finding difficult, though, as some people brought up, is integrating gVim with an interactive shell or debugger. Currently I save to the script file and debug it in an interpreter. But I want to get at the results of the debugging to modify the script. And sometimes I want to take snippets from the script under construction, change them, and retest them in an interactive shell. I like what Roland devised: > With a python-enabled VIM it's possible to execute and thus test the > python code. I have the following lines in my vimrc. > F2 prints the result of a line evaluation on the bottom or in a window > named pyout if there. I open pyout with ":vert rightb new pyout" mapped to > F1. But for my trial-and-error style of exploring both Python and the algorithm under construction, I would rather run a dedicated shell or debugger outside of vim and send its output to vim. Would it be relatively easy to fork the debugger/shell input/output to a file which of course vim could access? Because IPython (http://ipython.scipy.org/) saves session input, has many conveniences, and _feels_ like vim, I wanted to use IPython for this purpose. But I've been stumped because I use doctest on Windows and I don't know how to make IPython use the doctest. Even after I tried the workaround provided in the IPython FAQ (http://ipython.scipy.org/moin/FAQ) the doctest was corrupted in IPython. -- Ethan From warren at muse.com Sun Jun 10 17:40:08 2007 From: warren at muse.com (Warren Stringer) Date: Sun, 10 Jun 2007 14:40:08 -0700 Subject: Hooking exceptions outside of call stack In-Reply-To: References: <001f01c7aab4$71153940$240110ac@Muse> Message-ID: <000601c7aba7$eab66aa0$240110ac@Muse> Hey Josiah, I just spent a couple hours with your example, and it explains a lot. Some of your interactive session got garbled, so am reposting your merged_namespace example, with tweaks: #--------------------------------------------------------- def merged_namespace(*ns): try: __builtins__ namespaces = ns + (globals(),__builtins__.__dict__) except NameError: namespaces = ns + (globals(),__builtin__) ns = {} for i in reversed(namespaces): ns.update(i) return ns def foo(): print type(globals()) print a.b[c] #works! return #------------------------------------------ # was having trouble with embedded classes # so, I tried this to track down the problem class a(object): def __init__(self): print 'init a' class b(object): def __init__(self): print 'init b' class c(object): def __init__(self): print 'init c' pass aa = a() # only prints 'init a', oops # so, starting with this: class A(dict): def __getattr__(self, name): # here's where a namespace resolver might go return self[name] def __getitem__(self,key): return key # useless, but simple a = A() # build from scratch a.__dict__['b'] = A() a.b.__dict__['c'] = A() print a.b[a.b.c] # works as expected #print a.b[c] # NameError: name 'c' is not defined #------------------------- # back to Josiah's example ns = merged_namespace(a.b.__dict__) foo2 = type(foo)(foo.func_code, ns, foo.func_name, foo.func_defaults, foo.func_closure) foo2() #--------------------------------------------------------- As I was tracing through merged_namespace, I noticed how large resulting dict is. Too, bad there isn't an equivalent namespace resolution order, as the there is for methods (or, is there? Am not sure where/how locals are managed). Then a tupple could be passed to `foo2 = type(foo)(foo.func_code, namespace, ...)` With a mro-style namespace, __getattr__ might be able to change namespaces, on the fly. Too much of a performance hit? Could be. Fortunately, your example precludes the performance question. Thanks "Restartable exceptions", as Jean-Paul Calderone called it, might have yielded results. But searching on his specific phrase yielded a long discussion (http://www.python.org/search/hypermail/python-1994q2/0425.html) that illuminates the implausibility of this approach in Python. So, am replacing `a.b[c]` with `f(a.b,'c')`. The user still can type "a.b[c]" but, no longer at the python prompt. Oh well. Thanks again, \~/ From duncan.booth at invalid.invalid Thu Jun 21 11:10:08 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 21 Jun 2007 15:10:08 GMT Subject: Adding Python to the path in Windows References: <1182437575.810986.205610@n2g2000hse.googlegroups.com> Message-ID: kyle at thenortheastgroup.com wrote: > I have many users using two different versions of python, 2.4 and > 2.5. I am running Python scripts on their computers programmatically, > but I can't run it with the full path because they have different > versions installed. I need to run it like 'python {script name}'. So > I need to add Python to the path. How do I do this permanently > without going to each computer and setting it through the GUI? I > tried creating a Windows batch script using setx, but the user had to > be an administrator. > > Or is there any other way I can run whatever version of Python happens > to be installed with a single command? Anyone have any ideas? Such a > simple issue, there must be a simple solution. (of course, this is > Windows). > Assuming they have Python installed normally there will be file associations set up for .py and .pyw, so all you need to do to type in the script name: Python itself does not need to be in the path. N.B. You do need to include the .py extension unless you can arrange to edit the PATHEXT environment variable. e.g. C:\Temp>type t.py import sys print sys.version C:\Temp>t.py 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit (Intel)] C:\Temp>assoc .py .py=Python.File C:\Temp>ftype Python.File Python.File="C:\Python25\python.exe" "%1" %* From wildemar at freakmail.de Mon Jun 4 17:14:30 2007 From: wildemar at freakmail.de (Wildemar Wildenburger) Date: Mon, 04 Jun 2007 23:14:30 +0200 Subject: Logic [WAS: Re: Who uses Python?] In-Reply-To: <46647bbc$0$5861$da0feed9@news.zen.co.uk> References: <1180985830.288414.208850@q69g2000hsb.googlegroups.com> <46647149$0$2891$6e1ede2f@read.cnntp.org> <46647bbc$0$5861$da0feed9@news.zen.co.uk> Message-ID: <466480B6.8010401@freakmail.de> Mark Carter wrote: > A woman from a job agency 'phoned me up the other day, and asked me if I > was any good with "algortihms". I told her that all programs are > algorithms, so the question didn't make that much sense. > > What does your "answer" have to do with the qustion, I wonder? She asked if you were good with algorithms to which you replied that all programs are algorithms. Maybe so, but that's not what she asked. The question makes perfect sense, however your answer doesn't, unless you also added something along the lines of "And since I'm good with programs I am good with algorithms". /W (these days appearantly standing for "What a nitpicker" ;)) From metinex at gmail.com Mon Jun 25 11:29:25 2007 From: metinex at gmail.com (Jay Sonmez) Date: Mon, 25 Jun 2007 15:29:25 -0000 Subject: server wide variables Message-ID: <1182785365.877473.298170@q75g2000hsh.googlegroups.com> I want to be able to save some server variables as long as Apache runs on the server (mod_python). How is that possible in Python? From SMERSH009X at gmail.com Fri Jun 22 15:44:53 2007 From: SMERSH009X at gmail.com (SMERSH009X at gmail.com) Date: Fri, 22 Jun 2007 19:44:53 -0000 Subject: How to Encode Parameters into an HTML Parsing Script In-Reply-To: References: <1182479827.076831.210260@z28g2000prd.googlegroups.com> Message-ID: <1182541493.429630.169490@i13g2000prf.googlegroups.com> On Jun 21, 9:45 pm, "Gabriel Genellina" wrote: > En Thu, 21 Jun 2007 23:37:07 -0300, escribi?: > > > So for example if I wanted to navigate to an encoded url > >http://online.investools.com/landing.iedu?signedin=truerather than > > justhttp://online.investools.com/landing.iedu How would I do this? > > How can I modify thescriptto urlencode these parameters: > > {signedin:true} and to associate them with a specific url from the > > urlList > > If you want to use GET, append '?' plus the encoded parameters to the > desired url: > > py> data = {'signedin':'true', 'another':42} > py> print urlencode(data) > signedin=true&another=42 > > Do not use the data argument to urlopen. > > -- > Gabriel Genellina Sweet! I love this python group From borud-news at borud.no Thu Jun 21 10:55:49 2007 From: borud-news at borud.no (Bjorn Borud) Date: 21 Jun 2007 16:55:49 +0200 Subject: The Modernization of Emacs: terminology buffer and keybinding References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182272495.990807.99110@a26g2000pre.googlegroups.com> <87tzt3ihev.fsf@kobe.laptop> <1182370216.961241.6960@n60g2000hse.googlegroups.com> <85zm2ufjpb.fsf@lola.goethe.zz> <1182372592.803332.288260@u2g2000hsc.googlegroups.com> <5dtk4tF34jrimU1@mid.dfncis.de> <1182375388.814275.227380@n2g2000hse.googlegroups.com> Message-ID: [Twisted ] | | Emacs does have documentation. The problem is you have to already know | a load of emacs navigation oddities^Wkeyboard commands to get to and | use it. that, or just start Emacs and follow the instructions that appear on the screen. indeed, I *am* aware that something demanding an attention span in excess of 3 seconds is a bit of a tall order for most users today. -Bj?rn From http Wed Jun 27 13:37:29 2007 From: http (Paul Rubin) Date: 27 Jun 2007 10:37:29 -0700 Subject: Collections of non-arbitrary objects ? References: <1182449993.223262.229500@z28g2000prd.googlegroups.com> <87k5twx4hf.fsf@benfinney.id.au> <1182559502.069773.321620@i38g2000prf.googlegroups.com> <87wsxvrzsj.fsf@benfinney.id.au> <1182620734.940718.196520@e16g2000pri.googlegroups.com> <467ed491$0$27132$426a34cc@news.free.fr> <1182780863.067601.89320@d30g2000prg.googlegroups.com> <46801791$0$32172$426a34cc@news.free.fr> <1182863704.364272.5950@i13g2000prf.googlegroups.com> <46812159$0$24920$426a74cc@news.free.fr> <1182961835.134162.311670@x35g2000prf.googlegroups.com> Message-ID: <7xodj18fja.fsf@ruckus.brouhaha.com> Steve Holden writes: > Think of a tuple as an ordered collection. A given element's ordinal > position indicates its semantics (meaning, significance), and > generally it won't make sense to iterate over the elements of a tuple > (though naturally that doesn't stop people, and neither does the > interpreter). def f(*a): ... is a fundamental language feature and really only makes sense in the context of iterating over tuples. From mitko at qlogic.com Tue Jun 5 15:07:36 2007 From: mitko at qlogic.com (Mitko Haralanov) Date: Tue, 5 Jun 2007 12:07:36 -0700 Subject: Getting mount stats for filesystems In-Reply-To: <4665a7e9$0$24866$9b622d9e@news.freenet.de> References: <46650e6c$0$25817$9b622d9e@news.freenet.de> <4665a7e9$0$24866$9b622d9e@news.freenet.de> Message-ID: <20070605120736.7b7ab6d6@opal.pathscale.com> On Tue, 05 Jun 2007 20:14:01 +0200 "Martin v. L?wis" wrote: > Ah, ok. I recommend to parse /proc/mounts. I was looking for something that reminded me less of Perl and more of C but haven't been able to find such a method. -- Mitko Haralanov mitko at qlogic.com Senior Software Engineer 650.934.8064 System Interconnect Group http://www.qlogic.com ========================================== ... A booming voice says, "Wrong, cretin!", and you notice that you have turned into a pile of dust. From gcmartijn at gmail.com Fri Jun 8 07:28:30 2007 From: gcmartijn at gmail.com (gcmartijn at gmail.com) Date: Fri, 08 Jun 2007 04:28:30 -0700 Subject: soap - sessions ? Message-ID: <1181302110.333627.112900@h2g2000hsg.googlegroups.com> H! When I use php code nusoap everything works but with python I get everytime "Your session key does not exist or has expired" I use this code below: test = SOAPpy.SOAPProxy("http://secure.easynic.com/com/iomart/ easynicWSv2.cfc?wsdl") data = test.login(_id='test',_pass='pass') for item in data: for item2 in item: if item2['key']=='KEY': EASYKEY = item2['value'] # now I have the EASYKEY # create a customer with the key, # print output = "Your session key does not exist or has expired" print test.createOrUpdateContact(key=EASYKEY, title=row[0], firstname=row[2], initials=row[3], lastname=row[4], company=row[5], phone=row[9], fax='', email=row[13], address1=straat, address2='', address3='', area=row[12], city=row[8], country=row[12], postcode=row[7], acc_username='', acc_password='', domaincontactid='') # logout , and this works ! (using the same key) test.logout(key=EASYKEY) With php this works: // get the key $_SESSION[CODElogin] $result = $soapClient->call('login',$params,$_SESSION[serverip], $_SESSION[serverip]) // make a customer $params = array( 'key' => $_SESSION[CODElogin], 'title' => $_POST[title], 'firstname' => $_POST[firstname], 'initials' => $_POST[initials], 'lastname' => $_POST[lastname], 'company' => $_POST[company], 'phone' => $_POST[phone], 'fax' => $_POST[fax], 'email' => $_POST[email], 'address1' => $_POST[address1], 'address2' => $_POST[address2], 'address3' => $_POST[address3], 'area' => $_POST[area], 'city' => $_POST[city], 'country' => $_POST[area], 'postcode' => $_POST[postcode], 'acc_username' => $_POST[acc_username], 'acc_password' => $_POST[acc_password], 'domaincontactid'=> $_POST[domaincontactid] ); // send $result = $soapClient->call('createOrUpdateContact',$params,'http:// secure.easynic.com/com/iomart/easynicWSv2.cfc?wsdl','http:// secure.easynic.com/com/iomart/easynicWSv2.cfc?wsdl'); and everything works, what can I do to make this with python ? or must I use exec("phpprogram.php") ? (I hope not) Thanks From showell30 at yahoo.com Wed Jun 20 08:08:26 2007 From: showell30 at yahoo.com (Steve Howell) Date: Wed, 20 Jun 2007 05:08:26 -0700 (PDT) Subject: Q: listsort and dictsort - official equivalents? In-Reply-To: <740c3aec0706200448k38d19272m2e3f457138ad41de@mail.gmail.com> Message-ID: <335636.24162.qm@web33512.mail.mud.yahoo.com> --- BJ?rn Lindqvist wrote: > On 6/20/07, Gabriel Genellina > wrote: > > > It's not true that the sort must complete (or > that the whole file must > > > be read for that matter), Python has cool > generators which makes the > > > above possible. > > > > That's not possible, the input must be read > completely before sorted() can > > output anything. Suppose the minimum element is at > the end - until you > > read it, you can't output the very first sorted > element. > > Doh! Yes of course. I always thought that sorted() > returned a > generator. Since Python's sort is based on merge > sort, using a > generator approach it should at least be > theoretically possible to > begin emitting the items before the sort operation > completes. > I think Gabriel was making the point that the *input* to sorted() cannot be a generator, even thought sorted() itself could in theory be a generator with the right underlying implementation (e.g. heapsort). It's not unrealistic at all to have an indeterminate sequence of events that you occasionally want to pop results off of in sorted order, with the obvious limitation that you haven't yet seen "future" inputs from the input iteration. The way to express that is by using some kind of heap, though. I don't really see how you'd use the heap as a generator in that case, though. ____________________________________________________________________________________ Building a website is a piece of cake. Yahoo! Small Business gives you all the tools to get online. http://smallbusiness.yahoo.com/webhosting From benedict.verheyen at gmail.com Tue Jun 12 04:30:54 2007 From: benedict.verheyen at gmail.com (Benedict Verheyen) Date: Tue, 12 Jun 2007 10:30:54 +0200 Subject: python-ldap for Python 2.5 on Windows? In-Reply-To: <1181612746.393335.324940@o11g2000prd.googlegroups.com> References: <1181323389.805143.236480@i38g2000prf.googlegroups.com> <1181612746.393335.324940@o11g2000prd.googlegroups.com> Message-ID: Waldemar Osuch schreef: > > I have also build it on XP SP2. > > I have wrapped the files from "setup.py build" and all required .dll > using Inno Setup. > Maybe Vista does not like the executable produced by Inno. > > If you still want to try then unzip the following: > http://www.osuch.org/python-ldap.zip > into your "site-packages" and see how far you can get. > > The detailed instructions on how to build would be quite long and I'm > sure I have forgotten some of the steps already but if you know about > "./configure make make install" dance and know how to use Google you > should be OK. > > 1. First install MinGW, Msys and msysDTK. > 2. Then you need to compile openldap. See: > http://mail.gnome.org/archives/gnomemeeting-devel-list/2005-September/msg00019.html > for reference. You will need regex but you can skip Berkley DB > before you start. > 3. I have compiled openssl too but I have seen ready made libraries > for download. > I do not have link handy at the moment. > 4. The last step would be to run "setup.py build" for python-ldap. > Remove sasl2 from setup.cfg > since cyrus-sasl does not seem to be available for MinGW. > > See how far you can get with the above instructions. If you get stuck > send me a private email and I will try to help you. > If you could keep track of the steps and came up with better > instructions than my pitiful attempt above that would be great. > > Waldemar Hi Waldemar, thanks for the instructions. I will try to build it one of these days and see how far i get. As for the zip, i installed it and it works, i can use the ldap lib now. So as you said, it indeed seems to be a problem with the Inno setup. Anyway, if the zip works, i'm happy :) If i get around to building it and if i succeed, i will post a more detailed report on how to do it. Thanks, Benedict From dejanews at email.com Mon Jun 4 08:02:03 2007 From: dejanews at email.com (samwyse) Date: Mon, 04 Jun 2007 12:02:03 GMT Subject: Python 3000: Standard API for archives? Message-ID: <%aT8i.12569$rO7.12072@newssvr25.news.prodigy.net> I'm a relative newbie to Python, so please bear with me. There are currently two standard modules used to access archived data: zipfile and tarfile. The interfaces are completely different. In particular, script wanting to analyze different types of archives must duplicate substantial pieces of logic. The problem is not limited to method names; it includes how stat-like information is accessed. I think it would be a good thing if a standardized interface existed, similar to PEP 247. This would make it easier for one script to access multiple types of archives, such as RAR, 7-Zip, ISO, etc. In particular, a single factory class could produce PEP 302 import hooks for future as well as current archive formats. I think that an archive module adhering to the standard should adopt a least-common-denominator approach, initially supporting read-only access without seek, i.e. tar files on actual tape. For applications that require a seek method (such as importers) a standard wrapper class could transparently cache archive members in temp files; this would fit in well with Python 3000's rewrite of the I/O interface to support stackable interfaces. To this end, we'd need is_seekable and is_writable attributes for both the module and instances (moduel level would declare if something is possible, not if it is always true). Most importantly, all archive modules should provide a standard API for accessing their individual files via a single archive_content class that provides a standard 'read' method. Less importantly but nice to have would be a way for archives to be auto-magically scanned during walks of directories. Feedback? From gagsl-py2 at yahoo.com.ar Thu Jun 21 21:35:40 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 21 Jun 2007 22:35:40 -0300 Subject: variable sub in a list- how to References: Message-ID: En Thu, 21 Jun 2007 22:16:59 -0300, hari sirigibathina escribi?: > How can I substitute a variable into a list ? > ex: > list() > var = 'Prog' > list.append($Prog) //error occur here Considering the usage of // and $Prog (btw, did you meant $var?) I think you should start by reading some introductory texts, like the Python Tutorial or Dive Into Python , to learn how things are done in Python. -- Gabriel Genellina From harry.g.george at boeing.com Fri Jun 22 04:04:01 2007 From: harry.g.george at boeing.com (Harry George) Date: Fri, 22 Jun 2007 08:04:01 GMT Subject: Setuptools, build and install dependencies (was: eggs considered harmful) References: <87645gx0qb.fsf@benfinney.id.au> Message-ID: Ben Finney writes: > Harry George writes: > > > Historically, python packages played well in this context. Install > > was a simple download, untar, setup.py build/install. > > > > Eggs and with other setuptools-inspired install processes break this > > paradigm. The tarballs are incomplete in the first place. The builds > > sometimes wander off to the internet looking for more downloads. The > > installs sometimes wander off to the internet looking for > > compatibility conditions. (Or rather they try to do so and fail > > because I don't let themn through the firewall.) > > If you provide the build and install script with all the dependencies > already present (in the current directory), my experience is that > setuptools does not do any network actions. > > -- > \ "Self-respect: The secure feeling that no one, as yet, is | > `\ suspicious." -- Henry L. Mencken | > _o__) | > Ben Finney Thanks for the idea. It doesn't work so well in our context, since many dependencies are installed long before a particular egg is attempted. We need to know the dependencies, install them in dependency order, and expect the next package to find them. "configure" does this for hundreds of packages. cmake, scons, and others also tackle this problem. Python's old setup.py seems to be able to do it. However, as I understand it, setuptools can't detect previously installed python packages if they were not installed via eggs. Thus, my ZSI install was failing on "PyXML>=8.3", even though PyXML 8.4 is installed. I can't afford to drag copies of all the dependent source tarballs into an egg's currdir just so it can find them. (We have 6 GB of tarballs -- who knows how much untarred source that would be.) I just found hints that you should not attempt to install ZSI form tarball, but should rather install from an egg. So I was able to install ZSI for py2.4. Unfortunately, that means I would have to carry python-version-dependent renditions of every egg. We have people running on py23, py24, and py25, thus tripling the number of tarballs/eggs to manage. This is the very reason we went to a *source* based repository. -- Harry George PLM Engineering Architecture From walterbyrd at iname.com Sat Jun 16 22:11:25 2007 From: walterbyrd at iname.com (walterbyrd) Date: Sat, 16 Jun 2007 19:11:25 -0700 Subject: What's with "orange" ?? Message-ID: <1182046285.648928.161450@n15g2000prd.googlegroups.com> The maker of the skeletonz python based CMS, amonge other things: http://orangoo.com/skeletonz/ One of the few hosts that really provides good support for django: http://asmallorange.com/ The python component-based data mining software: http://www.ailab.si/orange From steve at REMOVE.THIS.cybersource.com.au Mon Jun 11 06:21:51 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Mon, 11 Jun 2007 20:21:51 +1000 Subject: Postpone creation of attributes until needed References: <1181553891.447344.109390@g4g2000hsf.googlegroups.com> Message-ID: On Mon, 11 Jun 2007 02:24:51 -0700, Frank Millman wrote: > Hi all > > I have a small problem. I have come up with a solution, but I don't > know if it is a) safe, and b) optimal. > > I have a class with a number of attributes, but for various reasons I > cannot assign values to all the attributes at __init__ time, as the > values depend on attributes of other linked classes which may not have > been created yet. I can be sure that by the time any values are > requested, all the other classes have been created, so it is then > possible to compute the missing values. Unless you're doing something like creating classes in one thread while another thread initiates your instance, I don't understand how this is possible. Unless... you're doing something like this? def MyClass(object): def __init__(self): self.x = Parrot.plumage # copy attributes of classes self.y = Shrubbery.leaves Maybe you should force the creation of the classes? def MyClass(object): def __init__(self): try: Parrot except Some_Error_Or_Other: # NameError? # do something to create the Parrot class pass self.x = Parrot.plumage # etc. > At first I initialised the values to None, and then when I needed a > value I would check if it was None, and if so, call a method which > would compute all the missing values. However, there are a number of > attributes, so it got tedious. I was looking for one trigger point > that would work in any situation. This is what I came up with. > >>>> class A(object): > ... __slots__ = ('x','y','z') By using slots, you're telling Python not to reserve space for a __dict__, which means that your class cannot create attributes on the fly. > ... def __init__(self,x,y): > ... self.x = x > ... self.y = y > ... def __getattr__(self,name): > ... print 'getattr',name > ... if name not in self.__class__.__slots__: > ... raise AttributeError,name > ... self.z = self.x * self.y > ... return getattr(self,name) [snip] > In other words, I do not declare the unknown attributes at all. This > causes __getattr__ to be called when any of their values are > requested, and __getattr__ calls the method that sets up the > attributes and computes the values. > > I use __slots__ to catch any invalid attributes, otherwise I would get > a 'maximum recursion depth exceeded' error. That's the wrong solution to that problem. To avoid that problem, __getattr__ should write directly to self.__dict__. > Is this ok, or is there a better way? At the interactive Python prompt: help(property) -- Steven From chris.lasher at gmail.com Fri Jun 15 16:25:58 2007 From: chris.lasher at gmail.com (Chris Lasher) Date: Fri, 15 Jun 2007 20:25:58 -0000 Subject: Priority Queue with Mutable Elements Message-ID: <1181939158.688317.207790@o61g2000hsh.googlegroups.com> Hello, I am working with large graphs (~150,000 to 500,000 nodes) which I need decompose node-by-node, in order of a node's value. A node's value is determined by the sum of its edge weights. When a node is removed from the graph, its neighbors' values must be updated to take into account the removed edges. I was told to look for a priority queue in Python. I had a look at the heapq module. It looks like it supports ordering on insertion, but I'm unsure how to update the queue once a node's value changes. Additionally, I need the queue to be sorted on a particular attribute of the node objects, and don't see a way to do that other than override the __cmp__ method. Should I just use a list and use .sort() or sorted()? That seems like it could be horribly inefficient. I found Andrew Snare's PQueue extension module [1] , which supports updating values in the priority queue by reassignment. It appeared to be broken in Python2.5 [2] but I found the offending line (a call to PyMem_DEL) and changed it (to PyObject_FREE) and it appears to be working fine. I would prefer to limit external depedencies for my modules, however. Many thanks for your insight and advice, Chris [1] http://py.vaults.ca/apyllo.py/514463245.769244789.44776582 [2] http://tinyurl.com/363dg9 or From els24 at cornell.edu Mon Jun 18 17:04:29 2007 From: els24 at cornell.edu (Eric Spaulding) Date: Mon, 18 Jun 2007 17:04:29 -0400 Subject: passing arguments to tcpserver classes In-Reply-To: References: Message-ID: <4676F35D.1030001@cornell.edu> Great -- thanks! (and also to J. Ezequiel). Mark T wrote: > "Eric Spaulding" wrote in message > news:mailman.9058.1181745026.32031.python-list at python.org... > >> Is there an easy way to pass arguments to a handler class that is used by >> the standard TCPServer? >> >> normally --> srvr =SocketServer.TCPServer(('',port_num), TCPHandlerClass) >> >> I'd like to be able to: srvr =SocketServer.TCPServer(('',port_num), >> TCPHandlerClass, (arg1,arg2)) >> >> And have arg1, arg2 available via TCPHandlerClass.__init__ or some other >> way. >> >> Where TCPHandlerClass: >> >> class TCPHandlerClass(SocketServer.StreamRequestHandler): >> def handle(self): >> #handle stream events here# >> >> >> Thanks for any advice. >> >> > > In the handler class, self.server refers to the server object, so subclass > the server and override __init__ to take any additional server parameters > and store them as instance variables. > > import SocketServer > > class MyServer(SocketServer.ThreadingTCPServer): > def __init__(self, server_address, RequestHandlerClass,arg1,arg2): > SocketServer.ThreadingTCPServer.__init__(self,server_address,RequestHandlerClass) > self.arg1 = arg1 > self.arg2 = arg2 > > class MyHandler(SocketServer.StreamRequestHandler): > def handle(self): > print self.server.arg1 > print self.server.arg2 > > if __name__ == '__main__': > srv = MyServer(('',5000),MyHandler,123,456) > srv.serve_forever() > > --Mark > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From toolmaster at 163.com Sat Jun 9 01:49:03 2007 From: toolmaster at 163.com (WaterWalk) Date: Fri, 08 Jun 2007 22:49:03 -0700 Subject: Python's "only one way to do it" philosophy isn't good? Message-ID: <1181368143.874341.273140@r19g2000prf.googlegroups.com> I've just read an article "Building Robust System" by Gerald Jay Sussman. The article is here: http://swiss.csail.mit.edu/classes/symbolic/spring07/readings/robust-systems.pdf In it there is a footprint which says: "Indeed, one often hears arguments against building exibility into an engineered sys- tem. For example, in the philosophy of the computer language Python it is claimed: \There should be one|and preferably only one|obvious way to do it."[25] Science does not usually proceed this way: In classical mechanics, for example, one can construct equa- tions of motion using Newtonian vectoral mechanics, or using a Lagrangian or Hamiltonian variational formulation.[30] In the cases where all three approaches are applicable they are equivalent, but each has its advantages in particular contexts." I'm not sure how reasonable this statement is and personally I like Python's simplicity, power and elegance. So I put it here and hope to see some inspiring comments. From aahz at pythoncraft.com Sat Jun 16 19:48:21 2007 From: aahz at pythoncraft.com (Aahz) Date: 16 Jun 2007 16:48:21 -0700 Subject: Writing books (was Re: Want to learn Python) References: <1181907696.878873.214760@i13g2000prf.googlegroups.com> <1hzrppt.1i3pamvoxog4rN%aleax@mac.com> <1182011078.358795.151590@c77g2000hse.googlegroups.com> Message-ID: In article <1182011078.358795.151590 at c77g2000hse.googlegroups.com>, 7stud wrote: > >It's nice to hear about an author who cares enough about the end >product that bears their name to insist on quality. I'm so tired of >hearing authors whine that the publisher screwed up the book. In all fairness, my co-author and primary partner (Stef Maruch) is a technical writer and editor as a profession, and she used to work at Yale Press. So we had more expertise on hand for knowing how to deal with publishers. Like law and sausages, the publishing industry does not bear close examination, and yes, if an author does not know what to expect, it's easy to get a book screwed up. For that matter, even when you *do* know what to expect, books still get screwed up, though that happens more in fiction publishing (go look in rec.arts.sf.composition for some horror stories written by experienced multi-book authors). On the gripping hand, I've tech edited three or four other Python books, and several of them were clearly written by people who didn't know Python and didn't want to learn enough to write a book about it. And they ignored my edits. (This seems like another opportunity to thank our tech editor, David Goodger.) So your larger point about careless authors is essentially correct. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "as long as we like the same operating system, things are cool." --piranha From luismgz at gmail.com Thu Jun 21 17:58:40 2007 From: luismgz at gmail.com (=?iso-8859-1?q?Luis_M=2E_Gonz=E1lez?=) Date: Thu, 21 Jun 2007 21:58:40 -0000 Subject: visual gui ides for python/jythpn In-Reply-To: <1182363400.993370.109800@k79g2000hse.googlegroups.com> References: <1182363400.993370.109800@k79g2000hse.googlegroups.com> Message-ID: <1182463120.865204.66380@k79g2000hse.googlegroups.com> On Jun 20, 3:16 pm, kromakey wrote: > Hi, > > Are there any free visual GUI IDE's available for python/jython, which > have a drag and drop form designer similar to Visual Studio or > Delphi ? > > Cheers > kromakey PythonCard is an extremely easy to use alternative. It's like a simplified Visual Basic or Delphi IDE. Check IT out: www.pythoncard.org From bj_666 at gmx.net Mon Jun 4 03:29:17 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Mon, 04 Jun 2007 09:29:17 +0200 Subject: int vs long References: <1180839659.196587.194200@p77g2000hsh.googlegroups.com> <7xr6otiv4l.fsf@ruckus.brouhaha.com> <1180895701.813483.326780@k79g2000hse.googlegroups.com> <7xabvgj33p.fsf@ruckus.brouhaha.com> <1hz4uas.7jeyyu192pb8tN%aleax@mac.com> Message-ID: In <1hz4uas.7jeyyu192pb8tN%aleax at mac.com>, Alex Martelli wrote: > Paul Rubin wrote: > >> Dan Bishop writes: >> > If you ever do, it's trivial to write your own enumerate(): >> > def enumerate(seq): >> > index = 0 >> > for item in seq: >> > yield (index, item) >> > index += 1 >> >> That's a heck of a lot slower than the builtin, and if you're running it >> often enough for sys.maxint to be an issue, you may care about the speed. > > Perhaps itertools.izip(itertools.count(), seq) might be faster (haven't > timed it, but itertools tends to be quite fast). I think correct is more important than fast. `itertools.count()` has the same issues that `enumerate()`: >>> from itertools import count >>> from sys import maxint >>> c = count(maxint) >>> c.next() 2147483647 >>> c.next() -2147483648 What I find most disturbing here, is that it happens silently. I would have expected an exception instead of the surprise. Ciao, Marc 'BlackJack' Rintsch From duncan.booth at invalid.invalid Mon Jun 18 04:00:57 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 18 Jun 2007 08:00:57 GMT Subject: global destructor not called? References: <4672b53f$0$31597$426a74cc@news.free.fr> <1182114313.259817.185670@m36g2000hse.googlegroups.com> Message-ID: "bruno.desthuilliers at gmail.com" wrote: >> >> def __del__ (self): >> >> try: >> >> os.remove (self.name + '.old') >> >> except: >> >> pass >> >> >> And setting: >> >> sys.stderr = logger(...) >> >> >> It seems my cleanup (__del__) is never called, >> ... > > Mmm... If I read the language's references, I see this: > > """ > It is not guaranteed that __del__() methods are called for objects > that still exist when the interpreter exits. > """ > http://docs.python.org/ref/customization.html > > Hopefully you fuond the right way to ensure correct clean-up !-) > > (damn, I knew I rembered something special about destructors... but I > couldn't remember exactly what.) > I don't think you can tell from this description whether the __del__ method was called or not. Even if sys.stderr is destroyed before Python exits and the __del__ method is called the OP will still get the effect described: the global variables in the module defining logger will have been cleared before stderr is destroyed, so __del__ will simply throw an NameError when trying to access os. From joe at incomps.com Thu Jun 7 11:09:08 2007 From: joe at incomps.com (Joe) Date: Thu, 7 Jun 2007 09:09:08 -0600 Subject: MySQL InterfaceError In-Reply-To: <163f0ce20706062024o556038f5te71ddacfc64c473e@mail.gmail.com> References: <001e01c7a6f3$e687ed40$0f01a8c0@desktop9> <002901c7a6f4$f55e56a0$0f01a8c0@desktop9> <008e01c7a7a5$ddaf8ae0$0f01a8c0@desktop9> <163f0ce20706061650k5708926ck449c53bf0bb39a81@mail.gmail.com> <016a01c7a897$2fbd4650$0f01a8c0@desktop9> <163f0ce20706062024o556038f5te71ddacfc64c473e@mail.gmail.com> Message-ID: <01d301c7a915$ccc10e40$0f01a8c0@desktop9> > Huh the only thing I can find on InterfaceError is "Errors related to > the database interface and not the database itself." You might be able > to get some info from connection.info() . . . Yeah, I wish there was more documentation about this type of error. The only thing info() tells me is that the connection is open through id ######. > Are you using utf8? MySQLdb seems to have some problems with that. > Also, I assume you've tried catching the error and printing the error > message, right? Yes, we are using utf8. What kind of problems can be seen with it? This is all I have run across so far. What type of encoding would you suggest? I am still new at some of this stuff, so if you could possibly explain (off-topic, so a link is fine) the differences between database encodings I would be grateful. And, yes, printing the error message returns absolutely nothing. The tuple following InterfaceError is both the error code and message. Unfortunately, it will only give me (0, '') which isn't much help. Thanks again! Jough From J.V.Ashby at rl.ac.uk Mon Jun 18 11:28:07 2007 From: J.V.Ashby at rl.ac.uk (John Ashby) Date: Mon, 18 Jun 2007 16:28:07 +0100 Subject: Do U have anything to share with this students References: <1181926856.041008.258770@o11g2000prd.googlegroups.com> <1181999183.047568.44000@m36g2000hse.googlegroups.com> Message-ID: Josh Hill wrote: > On Sat, 16 Jun 2007 13:06:23 -0000, Milt > wrote: > >>On Jun 15, 1:00?pm, slvsl... at gmail.com wrote: >>> This is a network of students. Find the people of your kind there >>> >>> http://tinyurl.com/33uvla >>> >>> Click and register to access millions of students. >> >>Your link doesn't work. > > Hope you're protected against malware. > The URL in question has been terminated by tinyurl for violation of TOS. Milt, you need to run an uptodate virus/spyware checker on your computer (although looking at your headers, you seem to be on a Mac, so it might not be as urgent). john From markacy at gmail.com Wed Jun 13 04:21:53 2007 From: markacy at gmail.com (markacy) Date: Wed, 13 Jun 2007 08:21:53 -0000 Subject: How to save python codes in files? In-Reply-To: <1181721972.486523.37680@g37g2000prf.googlegroups.com> References: <1181711063.512249.289520@x35g2000prf.googlegroups.com> <1181721972.486523.37680@g37g2000prf.googlegroups.com> Message-ID: <1181722913.777141.279570@n15g2000prd.googlegroups.com> On 13 Cze, 10:06, why? wrote: > Evan Klitzke wrote: > > On 6/12/07, why? wrote: > > > Im working with Python 2.2 on my red hat linux system. Is there any > > > way to write python codes in separate files and save them so that i > > > can view/edit them in the future? Actually I've just started with > > > python and would be grateful for a response. Thanx! > > > Of course -- just put the code into a text file (using your favorite > > text editor) and then run the script using the python command, e.g. by > > executing on a command line: > > python my_program.py > > > Since you're on a Linux system you can also use this as the first line > > of your file and then chmod +x the file to make it into an executable > > script: > > > #!/usr/bin/env python > > > -- > > Im still unable to follow... :( > See, if i have to save the following code in a file, how should i > proceed? > > >>> def sum(x,y): return x+y > ... :D You should try some basic manual on linux :D Copy and paste the code (do not include >>> and ...) to the editor, save. Then run as advised above. Good luck. Cheers, Marek From debajit at debajit.com Tue Jun 26 10:43:32 2007 From: debajit at debajit.com (Debajit Adhikary) Date: Tue, 26 Jun 2007 10:43:32 -0400 Subject: Converting Diff Output to XML? Message-ID: <110a172d0706260743m10a9aaebt81e072717dbd6582@mail.gmail.com> What would be the best way to convert the regular (unix) diff output into XML? Are there any libraries at all which might help? -------------- next part -------------- An HTML attachment was scrubbed... URL: From george.sakkis at gmail.com Thu Jun 14 16:18:51 2007 From: george.sakkis at gmail.com (George Sakkis) Date: Thu, 14 Jun 2007 20:18:51 -0000 Subject: Moving items from list to list In-Reply-To: <1181838605.080038.162390@x35g2000prf.googlegroups.com> References: <1181838605.080038.162390@x35g2000prf.googlegroups.com> Message-ID: <1181852331.675145.87260@n15g2000prd.googlegroups.com> On Jun 14, 12:30 pm, HMS Surprise wrote: > Just wondered if there was some python idiom for moving a few items > from one list to another. I often need to delete 2 or 3 items from one > list and put them in another. Delete doesn't seem to have a return > value. I don't care which items I get so now I just use a couple of > pops or a for loop for more than two. > > Thanks > > jh >>> x = range(10) >>> y = [] >>> y.append(x.pop(4)) >>> print x, y [0, 1, 2, 3, 5, 6, 7, 8, 9] [4] >>> y.append(x.pop(7)) >>> print x, y [0, 1, 2, 3, 5, 6, 7, 9] [4, 8] HTH, George From nejtak... Wed Jun 6 14:02:42 2007 From: nejtak... (Troels Thomsen) Date: Wed, 6 Jun 2007 20:02:42 +0200 Subject: [pyserial - winXP] Serial port stop receiving data after a few hours, raise no error References: <1181125442.737934.280150@q75g2000hsh.googlegroups.com> Message-ID: <4666f6c9$0$52097$edfadb0f@dread11.news.tele.dk> I read that when the serial port encounters an error (frame error or so, I imagine?) it stop receiving data until the library function "getCommError()" is called. Troels: I think you are right Am I on the good track? Can I call this function from my pyserial code? Why pyserial does'nt raise a serial.SerialException in this case? Troels: Well , you have the source, don't you ? The serial lib has a handle somwhere. Call getCommError with that ? Or ? tpt From dkishore1 at gmail.com Thu Jun 7 08:53:35 2007 From: dkishore1 at gmail.com (Kishore D) Date: Thu, 7 Jun 2007 20:53:35 +0800 Subject: Unable to start IDLE Message-ID: Hi, I am facing a problem in starting IDLE. The hourglass appears for a while and then goes off. When i tried opening it after switching of the firewall, it still din help. If some other program is accessing the port can anyone tell me how to assign the port to python. Thanks . -------------- next part -------------- An HTML attachment was scrubbed... URL: From bignose+hates-spam at benfinney.id.au Fri Jun 1 08:03:39 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 01 Jun 2007 22:03:39 +1000 Subject: Is PEP-8 a Code or More of a Guideline? References: <1180236987.850208.271410@u30g2000hsc.googlegroups.com> <1180575848.698433.289180@h2g2000hsg.googlegroups.com> Message-ID: <87k5unzxt0.fsf@benfinney.id.au> Carl Banks writes: > Identifiers should just allow spaces. > > first element.get item(selected value) > > This is not a joke. It would be a hideous pain to read though. My decades of schooling have carved channels in my brain that recognise the space as a *separator* for lexical elements, and any non-space separator as being lower down the hierarchy. The parentheses just look awkward, but the period is *definitely* joining tokens together whereas the spaces separate them. Thus, the example you give parses as the tokens "first", "element.get", "item", "selected", "value". I don't see any language with the characteristics you describe being at all useful until the major natural language of programmers ceases to use spaces this way. -- \ "First they came for the verbs, and I said nothing, for verbing | `\ weirds language. Then, they arrival for the nouns and I speech | _o__) nothing, for I no verbs." -- Peter Ellis | Ben Finney From john at datavoiceint.com Thu Jun 14 15:31:17 2007 From: john at datavoiceint.com (HMS Surprise) Date: Thu, 14 Jun 2007 12:31:17 -0700 Subject: Moving items from list to list In-Reply-To: References: <1181838605.080038.162390@x35g2000prf.googlegroups.com> Message-ID: <1181849477.311734.314490@d30g2000prg.googlegroups.com> Thanks. That will work. The 2nd, smaller lst starts out empty but this is easily adapted. jh From exarkun at divmod.com Thu Jun 28 17:38:25 2007 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Thu, 28 Jun 2007 17:38:25 -0400 Subject: IMAP library In-Reply-To: Message-ID: <20070628213825.4947.1941341450.divmod.quotient.4951@ohm> On Thu, 28 Jun 2007 18:44:02 -0300, Bruno Barberi Gnecco wrote: > It seems that this question has been asked a few times in this >group before, but sometime has passed since the last post and maybe there's >something new. I'm looking for a high level IMAP library--I know of imaplib, >but it's awfully documented and I was hoping to avoid reading RFCs for >a simple email reader routine. > > So, is there any example, routine, library or code in some software >package that reads mails from IMAP, with attachments? I don't need anything >fancy, just reading the emails and decoding them. > > If there isn't, I'm willing to write one and release it under LGPL. >Anybody would like to help? > For the IMAP4 part of this, I'd suggest Twisted's IMAP4 library. To deal with attachments and other MIME features, you can use the stdlib email package to parse the message into a structured form and then process it appropriately. Jean-Paul From dwahler at gmail.com Sun Jun 17 08:05:14 2007 From: dwahler at gmail.com (David Wahler) Date: Sun, 17 Jun 2007 13:05:14 +0100 Subject: sqlite3 bug?? In-Reply-To: <46752230$0$31685$db0fefd9@news.zen.co.uk> References: <46752230$0$31685$db0fefd9@news.zen.co.uk> Message-ID: On 6/17/07, mark carter wrote: > I hesitate to ask, but ... > > I'm using Ubuntu Feisty: > * Python 2.5.1 (r251:54863, May 2 2007, 16:56:35) > [GCC 4.1.2 (Ubuntu 4.1.2-0ubuntu4)] on linux2 > * SQLite version 3.3.13 > > Suppose I run the following program: > import sqlite3 > > conn = sqlite3.connect('example') > > > c = conn.cursor() > > # Create table > c.execute('''create table stocks > (date text, trans text, symbol text, > qty real, price real)''') > > # Insert a row of data > c.execute("""insert into stocks > values ('2006-01-05','BUY','RHAT',100,35.14)""") > > and then I go into sqlite: > % sqlite3 example > sqlite3> select * from stocks ; > > It returns 0 rows. I'm in the right directory. I have experienced this > problem with some other sqlite3 database work I have done with python, > so I'm figuring there is something fishy going on. I've tried doing > similar exercises with Ruby, and they have worked OK. > > Anyone else getting these problems? See http://www.python.org/dev/peps/pep-0249/ (emphasis mine): .commit() Commit any pending transaction to the database. *Note that if the database supports an auto-commit feature, this must be initially off.* An interface method may be provided to turn it back on. (This really should be a FAQ...) -- David From josiah.carlson at sbcglobal.net Thu Jun 14 15:48:35 2007 From: josiah.carlson at sbcglobal.net (Josiah Carlson) Date: Thu, 14 Jun 2007 19:48:35 GMT Subject: Method much slower than function? In-Reply-To: References: <1181781612.939800.238890@q19g2000prn.googlegroups.com> <1181795969.141307.94140@i13g2000prf.googlegroups.com> Message-ID: Francesco Guerrieri wrote: > On 6/14/07, Peter Otten <__peter__ at web.de> wrote: >> Gabriel Genellina wrote: >> > ... >> > py> print timeit.Timer("f2()", "from __main__ import >> f2").repeat(number=1) >> > [0.42673663831576358, 0.42807591467630662, 0.44401481193838876] >> > py> print timeit.Timer("f1()", "from __main__ import >> f1").repeat(number=1) >> > >> > ...after a few minutes I aborted the process... >> >> I can't confirm this. > > [...] > >> $ python2.5 -m timeit -s 'from join import f1' 'f1()' >> 10 loops, best of 3: 212 msec per loop >> $ python2.5 -m timeit -s 'from join import f2' 'f2()' >> 10 loops, best of 3: 259 msec per loop >> $ python2.5 -m timeit -s 'from join import f3' 'f3()' >> 10 loops, best of 3: 236 msec per loop > > On my machine (using python 2.5 under win xp) the results are: >>>> print timeit.Timer("f2()", "from __main__ import f2").repeat(number >>>> = 1) > [0.19726834822823575, 0.19324697456408974, 0.19474492594212861] >>>> print timeit.Timer("f1()", "from __main__ import f1").repeat(number >>>> = 1) > [21.982707133304167, 21.905312587963252, 22.843430035622767] > > so it seems that there is a rather sensible difference. > what's the reason of the apparent inconsistency with Peter's test? It sounds like a platform memory resize difference. - Josiah From stuart.tett at gmail.com Sun Jun 24 11:13:23 2007 From: stuart.tett at gmail.com (Stuart) Date: Sun, 24 Jun 2007 15:13:23 -0000 Subject: pydoc with METH_VARGS In-Reply-To: <1182657646.734577.248820@w5g2000hsg.googlegroups.com> References: <1182629624.579928.186260@n60g2000hse.googlegroups.com> <1182657646.734577.248820@w5g2000hsg.googlegroups.com> Message-ID: <1182698003.620552.245700@m36g2000hse.googlegroups.com> I'm asking if there's some sort of commenting or input file or something to customize the output pydoc generates. Thanks. On Jun 23, 11:00 pm, 7stud wrote: > On Jun 23, 2:13 pm, Stuart wrote: > > > With my Python extension module all the function definitions are with > > METH_VARGS. The result being that pydoc, just puts "(...)" for the > > argument list. Can I hand edit this to put the specific variable names > > I want? With optional arguments in brackets or something? > > > Thanks. > > Are you asking whether you can change a text file that pydoc produces? From __peter__ at web.de Thu Jun 28 16:08:01 2007 From: __peter__ at web.de (Peter Otten) Date: Thu, 28 Jun 2007 22:08:01 +0200 Subject: try/except/else/finally problem References: <1387teta99gajc4@corp.supernews.com> <138822drq8rnu37@corp.supernews.com> Message-ID: Ed Jensen wrote: > Peter Otten <__peter__ at web.de> wrote: > >>> try: >>> f = file('test.txt', 'r') >>> except IOError: >>> print 'except' >>> else: >>> print 'else' >>> finally: >>> print 'finally' > >> You need Python 2.5 for that to work. In older Python versions you have >> to nest try...except...else and try...finally. > > Thanks Peter. > > Given the code above, can you show me what that would look like? The > nested version, that is. try: try: f = file("test.txt", "r") except IOError: print "except" else: print "else" finally: print "finally" Peter From siddhartag at excite.com Tue Jun 12 01:45:40 2007 From: siddhartag at excite.com (siddhartag at excite.com) Date: Tue, 12 Jun 2007 05:45:40 -0000 Subject: Setting the encoding in the basic auth header Message-ID: <1181627140.208015.256160@q19g2000prn.googlegroups.com> This is not strictly a python question, but I'm hoping someone here has come across a similar situation. I have a django app and I've protected some views with basic authentication. The user can use any unicode character in the username and password fields. When this happens, the data is not properly encoded by the browser before transmission. How can I get the browser to encode the data as utf-8 before sending it over? Is there some header I need to send? This is what I'm doing at the moment. def getAuthenticateResponse(): response = HttpResponse() response.status_code = 401 response.headers["WWW-Authenticate"] = 'Basic realm="Realm"' return response When I enter character \xf1 as the username which is outside ascii but within iso-8859-1 Firefox 2.0 sends this as \xf1 IE 7 also sends this as \xf1 But the utf-8 encoding is \xc3\xb1 If I enter character 0BA4 (TAMIL LETTER TA) which is outside iso-8859-1 Firefox 2 sends this as \xa4 (seems to drop the high byte) IE 7 sends this as ? It seems that both browsers are using the iso-8859-1 charset. Is there any way I can get them to encode the data with utf-8 instead? Thanks for any help. -- Siddharta From Graham.Dumpleton at gmail.com Tue Jun 12 19:59:50 2007 From: Graham.Dumpleton at gmail.com (Graham Dumpleton) Date: Tue, 12 Jun 2007 23:59:50 -0000 Subject: cgi.FieldStorage() not working on Windows In-Reply-To: <1181661435.258140.17800@x35g2000prf.googlegroups.com> References: <1181661435.258140.17800@x35g2000prf.googlegroups.com> Message-ID: <1181692790.432649.273820@i13g2000prf.googlegroups.com> On Jun 13, 1:17 am, arorap wrote: > I've mod_php installed with Apache 2.2. In one of my folders, I'm > using the cgihandler as the PythonHandler as my target host runs > python only as CGI. Here cgi.FieldStorage() doesn't seem to work. I > can see the form data in sys.stdin but cgi.FieldStorage() returns an > empty dictionary. Here's the code for the test script I am posting to > - > > -- > #!/usr/bin/python > > import os > import cgi > import sys > > print "Content Type: text/plain\n\n" > print "Hello CGI World !\n" > > for key in os.environ: > print key + "= " + os.environ[key] > > print cgi.FieldStorage() > > print sys.stdin.read() > -- > > And here's the output I see .. > > -- > Hello CGI World ! > > HTTP_REFERER=http://learnpython/form.htm > SERVER_SOFTWARE= Apache/2.2.4 (Win32)mod_python/3.3.1 Python/2.5.1 > SCRIPT_NAME= /mptest.py > SERVER_SIGNATURE= > REQUEST_METHOD= POST > SERVER_PROTOCOL= HTTP/1.1 > QUERY_STRING= abc=ayz > PATH= C:\Program Files\Internet Explorer;;C:\WINDOWS\system32;C: > \WINDOWS;C:\WINDOWS\System32\Wbem;q:\bin;m:\cm\clearcase\bin;M:\PERL\NT > \EXEC\BIN;m:\cm\clearcase\bin\nt;M:\Perl\NT\EXEC\BIN;m:\perl\nt\exec > \bin;m:\cm\clearcase\utils;q:\bin;m:\opus;m:\tvcs;C:\highc331\bin;C: > \Program Files\Rational\ClearCase\bin;C:\Program Files\Rational\common > CONTENT_LENGTH= 86 > HTTP_USER_AGENT= Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; > SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727) > HTTP_CONNECTION= Keep-Alive > SERVER_NAME= learnpython > REMOTE_ADDR= 127.0.0.1 > PATHEXT= .COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH > SERVER_PORT= 80 > SERVER_ADDR= 127.0.0.1 > DOCUMENT_ROOT= D:/Projects/LearnPython/www > COMSPEC= C:\WINDOWS\system32\cmd.exe > SCRIPT_FILENAME= D:/Projects/LearnPython/www/mptest.py > SERVER_ADMIN= puneet.ar... at tekelec.com > HTTP_HOST= learnpython > SystemRoot= C:\WINDOWS > HTTP_CACHE_CONTROL= no-cache > REQUEST_URI= /mptest.py?abc=ayz > HTTP_ACCEPT= */* > WINDIR= C:\WINDOWS > GATEWAY_INTERFACE= Python-CGI/1.1 > REMOTE_PORT= 1081 > HTTP_ACCEPT_LANGUAGE= en-us > CONTENT_TYPE= application/x-www-form-urlencoded > HTTP_ACCEPT_ENCODING= gzip, deflate > > FieldStorage(None, None, []) > > firstName=puneet&address=hawaii > -- > > I am posting to this script using a form with two text fields named > firstName and address. > > any clue where am I going wrong ? You don't need mod_python/cgihandler to run CGI scripts. Rather than bring mod_python into the picture and confuse things, set up Apache to run your script as a traditional CGI script instead. BTW, the fact that mod_python is loaded means that CGI scripts aren't the only way of using Python available to you as you seem to think. So, suggest you do some research as to what the differences are between CGI and mod_python. Graham From jeremy+complangpython at jeremysanders.net Tue Jun 19 04:15:40 2007 From: jeremy+complangpython at jeremysanders.net (Jeremy Sanders) Date: Tue, 19 Jun 2007 09:15:40 +0100 Subject: Matrix Multiplication References: <1182113543.957069.135240@k79g2000hse.googlegroups.com> <1182118748.755871.267780@u2g2000hsc.googlegroups.com> <1182184094.620093.15930@n60g2000hse.googlegroups.com> Message-ID: sturlamolden wrote: > That's what I wrote: "NumPy has a matrix type." It is called called > numpy.matrix. > > I did not suggest using the array type numpy.array. > > Reading carefully is indeed important... I know what you wrote and you are strictly correct. I was just clarifying it for a reader who may not have instantly realised that there were multiple array types in numpy (I didn't for a while), and could have wasted many hours and been discouraged. Explaining clearly is indeed important. -- Jeremy Sanders http://www.jeremysanders.net/ From ps at nospam.com Tue Jun 5 03:14:06 2007 From: ps at nospam.com (Pierre Sangouard) Date: Tue, 5 Jun 2007 09:14:06 +0200 Subject: Python Memory Leak using SWIG References: <1180984686.314914.296660@g37g2000prf.googlegroups.com> Message-ID: <46650d42$0$10290$426a74cc@news.free.fr> cody314 at gmail.com wrote: > Versions: > Python 2.5.1 (r251:54863, May 14 2007, 10:50:04) > SWIG Version 1.3.20 > > Hello I have some code that wraps a C++ library so I may use it in > python. The code basically just gets some data and puts it in the > PyArrayObject* which is returned as a PyObject*. > I then call it from python like so: > self.c = __f2.fdct2_wrapper(x,self.nbs,self.nba,self.ac) > > I then loop (which pretty much only calls this function) over and > over. I put the variable as a self.c hoping the garbage collector > would know how to delete it after the class goes out of scope. I also > tried explicitly deleting the variable (del var) in the loop with no > success. In all cases quiet a large memory leak occurs (and grows > rather quickly). > > I believe this is comming from the fact that the thing that is > returned is a pointer to the data. So the returning object is a > pointer. The python garbage collector then doesn't know how to delete > this structure and probably (maybe) just deletes the pointer after the > class goes out of scope. Leave the data there and causing the memory > leak issue. I however doesn't know how to tell python that this > variable is a pointer and to delete whats going to it. Or perhaps > tell SWIG to delete the data, and return the structure some other way? > > Here is the c++ wrapping code, perhaps there is an easy way to fix > this memory leak (I believe a lot of SWIG people probably do this) > perhaps some function call from the python? or some special call from > the SWIG? Thanks a bunch! > > // set up the list output > PyListObject* out; > PyArrayObject* output; > out = (PyListObject*) PyList_New(0); > npy_intp dims[2]; > int i,j; > > for(i=0;i { > // append a list for this scale > PyList_Append((PyObject*) out,PyList_New(0)); > > for(j=0;j { > // set the dimensions for this scale & angle > dims[0] = g[i][j].n(); > dims[1] = g[i][j].m(); > > // make an array for this scale & angle's data > output = (PyArrayObject*) PyArray_SimpleNewFromData(2, dims, > PyArray_CDOUBLE,g[i][j]._data); > Py_INCREF((PyObject*) output); > > // append this angle's data to the list for this scale > PyList_Append(PyList_GetItem((PyObject*) out,i),(PyObject*) > output); > > // zero the CpxNumMat for this scale & angle, hand ownership to > numpy > g[i][j]._data = NULL; > g[i][j]._m = 0; > g[i][j]._n = 0; > output->flags = output->flags | NPY_OWNDATA; > } > } > > return (PyObject*) out; I think %newobject swig directive is a solution to your problem. Pierre From aleax at mac.com Thu Jun 28 02:09:49 2007 From: aleax at mac.com (Alex Martelli) Date: Wed, 27 Jun 2007 23:09:49 -0700 Subject: nested list comprehension and if clauses References: <1183007216.684569.222450@k79g2000hse.googlegroups.com> <1i0e21c.m73ptlth8j5mN%aleax@mac.com> <7x3b0cy5sy.fsf@ruckus.brouhaha.com> Message-ID: <1i0e2zi.xj9f5ap5w662N%aleax@mac.com> Paul Rubin wrote: > aleax at mac.com (Alex Martelli) writes: > > > print [(m,n) for m in range(5) for n in multab(m) if m>2] > > Sure, just place the if clause where it needs to apply (between the two > > for clauses) [apart from the fact that this example is best expressed by > > using range(3,5), as somebody already said;-)]. > > You mean > > print [(m,n) for m in range(5) if m > 2 for n in multab(m)] > > Heh. I didn't realize you could do that. Thanks. You're welcome (though a range(3,5) would still be better here:-). Alex From kyle at thenortheastgroup.com Thu Jun 21 11:30:00 2007 From: kyle at thenortheastgroup.com (kyle at thenortheastgroup.com) Date: Thu, 21 Jun 2007 08:30:00 -0700 Subject: Adding Python to the path in Windows In-Reply-To: <1182439377.009844.320760@q75g2000hsh.googlegroups.com> References: <1182437575.810986.205610@n2g2000hse.googlegroups.com> <1182439377.009844.320760@q75g2000hsh.googlegroups.com> Message-ID: <1182439800.148330.221600@p77g2000hsh.googlegroups.com> On Jun 21, 11:22 am, kyoso... at gmail.com wrote: > > If your users aren't programmers, then why not just run Python over > the network? That's what we do at my place of employment. The only > machines that have Python actually installed are development machines. > > Mike Mike, I place the scripts on the server, but hadn't thought of placing an entire Python installation on the server. I just tried it and it seems to work. It shouldn't cause any problems? That might actually work out really well too. Thanks for the suggestion. From damienlmoore at gmail.com Thu Jun 7 12:01:11 2007 From: damienlmoore at gmail.com (dmoore) Date: Thu, 07 Jun 2007 09:01:11 -0700 Subject: Bug/Weak Implementation? popen* routines can't handle simultaneous read/write? Message-ID: <1181232071.928835.301710@w5g2000hsg.googlegroups.com> Hi folks, I've seen the following issue come up in multiple posts to this mailing list: I have a python program that spawns a child process with popen or popen2 or popen3 or popen2.popen2 etc. the child process is interactive: it asks for input then spits out some output, asks for more input then spits out some output. for example, consider the trivial child program: print "welcome" print ">", s=raw_input() while s!='exit': print "you entered:",s print ">", s=raw_input() Now I may be completely wrong about this (I did play with popen for a very long time before writing this message), but it appears that none of the popen variants allow for a sequence of reads and writes to/from this child. that is, if I read from the open pipe's output I will never be able to write the input for the child because the parent program will block on read until eof (I will have similar blocking problems if I start with write - using readline does not seem to help). the standard proposed remedy I have seen on this list is to use Unix- only select/fctl, or otherwise dig into the bowls of the win32 api, or download some half-complete sourceforge process control project. All well and good, but unsatisfying for writing platform independent code. it turns out that there is at least one open source multi-platform (read: win32/linux) api that does handle synchronous I/O with the child: wxWidgets and wxPython using the class wxProcess. Now the wxWidgets implementation is far from perfect, but it at least allows a program to test for new input on the child's stdout and read stdout/ write stdout in a non-blocking way. However, I find it frustrating that I have to import wx just to have useable interactive pipes in my python scripts when I would expect this to be part of the native python implementation. Anybody have any thoughts on this? Do I have my story straight? (the popen variants can't handle this case and there are no other alternatives in the standard python distro) Is there some place I can submit this as a feature request? (Python dev?) From jimxu at google.com Wed Jun 27 19:57:02 2007 From: jimxu at google.com (Yongjian Xu) Date: Wed, 27 Jun 2007 16:57:02 -0700 Subject: Converting Diff Output to XML? In-Reply-To: <110a172d0706260743m10a9aaebt81e072717dbd6582@mail.gmail.com> References: <110a172d0706260743m10a9aaebt81e072717dbd6582@mail.gmail.com> Message-ID: <9c09a1210706271657w13c21100k551c66b4b307cb5a@mail.gmail.com> gnosis has a converter for ASCII file to xml file, its called txt2dw.py. give it a try. -- Jim On 6/26/07, Debajit Adhikary wrote: > > What would be the best way to convert the regular (unix) diff output into > XML? > Are there any libraries at all which might help? > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Yongjian (Jim) Xu =========== Sysops -------------- next part -------------- An HTML attachment was scrubbed... URL: From mossab00019 at gmail.com Thu Jun 28 11:49:26 2007 From: mossab00019 at gmail.com (mossab00019 at gmail.com) Date: Thu, 28 Jun 2007 08:49:26 -0700 Subject: Excuse me!! Message-ID: <1183045766.315349.251860@n60g2000hse.googlegroups.com> Excuse me!! Would you stop for a moment?! Haven't you thought-one day- about yourself ? Who has made it? Have you seen a design which hasn't a designer ?! Have you seen a wonderful,delicate work without a worker ?! It's you and the whole universe!.. Who has made them all ?!! You know who ?.. It's "ALLAH",prise be to him. Just think for a moment. How are you going to be after death ?! Can you believe that this exact system of the universe and all of these great creation will end in nothing...just after death! Have you thought, for a second, How to save your soul from Allah's punishment?! Haven't you thought about what is the right religion?! Here you will get the answer http://www.anashed.net/flash/lastb_reath.swf http://www.todayislam.com/ http://www.islam-guide.com http://www.sultan.org From kerny404 at gmail.com Tue Jun 19 08:20:15 2007 From: kerny404 at gmail.com (andrea) Date: Tue, 19 Jun 2007 05:20:15 -0700 Subject: textmate and execute line Message-ID: <1182255615.005437.146660@k79g2000hse.googlegroups.com> Hi, I have the latest bundle for python (upgraded from svn) but I don't understand how execute line works.. It only works if I play with arithmetic operations, something like this works: 2*2 4 but for example trying to execute this line gives me this error, any help? x = 1; x + 1 Traceback (most recent call last): File "/tmp/temp_textmate.31Kc2h", line 19, in ? stdout.write(exc) TypeError: argument 1 must be string or read-only character buffer, not list Thanks a lot From robert.kern at gmail.com Wed Jun 20 16:40:05 2007 From: robert.kern at gmail.com (Robert Kern) Date: Wed, 20 Jun 2007 15:40:05 -0500 Subject: Python's "only one way to do it" philosophy isn't good? In-Reply-To: References: <1181368143.874341.273140@r19g2000prf.googlegroups.com> Message-ID: Douglas Alan wrote: > "Terry Reedy" writes: >> Which I obviously read and responded to by noting "And 3.0 may add a new >> generic function module to dispatch on multiple arguments and possibly >> predicates." > > So, that's great. Python will once again adopt a wonderful feature > that has been usable in Lisp implementations for 20 years now. (This > is a good thing, not a bad thing. I just don't like so much the > having to wait 20 years.) The problem with Python's model is that you > have to wait for a rather centralized process to agree on and > implement such a feature. No, you don't. Philip Eby has been working on various incarnations of generic functions for some time now. The only thing new with 3.0 is that they may be included in the standard library and parts of the rest of the standard library may use them to implement their features. Implementing generic functions themselves don't require anyone to convince python-dev of anything. http://python.org/pypi/simplegeneric/0.6 http://peak.telecommunity.com/DevCenter/RulesReadme -- 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 newsgroups at nospam.demon.co.uk Fri Jun 1 07:34:23 2007 From: newsgroups at nospam.demon.co.uk (Douglas Woodrow) Date: Fri, 1 Jun 2007 12:34:23 +0100 Subject: c[:]() References: Message-ID: <77KEEZK$QAYGFwmk@woodrowhorsfall.plus.com> On Fri, 1 Jun 2007 07:23:16, Steve Holden wrote >> Actually you can copy and paste from a Windows cmd/command shell: >>right-click the title-bar of the window, select "Edit" from the pop-up >>menu, then "Mark" from the sub-menu to copy whatever you want to >>select into the Windows clipboard. > >Better still, modify your shortcut by bring up the command window's >Properties page and setting "Quick Edit Mode". Then you can select with >the mouse and hit Enter to copy. Cool, thanks Steve! Newsgroups really are a good way of learning new things quickly. -- Doug Woodrow From gagsl-py2 at yahoo.com.ar Wed Jun 20 14:30:50 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 20 Jun 2007 15:30:50 -0300 Subject: How to hide a program? References: <1182347596.414718.117190@w5g2000hsg.googlegroups.com> <5dsq6hF36eulqU1@mid.uni-berlin.de> <1182349569.122969.284950@q19g2000prn.googlegroups.com> Message-ID: En Wed, 20 Jun 2007 11:26:09 -0300, jvdb escribi?: > On 20 jun, 15:59, "Diez B. Roggisch" wrote: >> jvdb wrote: >> > Is it possible to start a program 'hidden' or minimized to at least >> > the system tray? And, if yes., could some one help me on this? >> >> I'm not exactly sure what you mean here, but I guess you want the >> command-window suppressed. You can do so by naming your scripts *.pyw, >> which will invoke pythonw.exe instead. That has no command-window. > > I forgot to mention that i have created a Windows executable of the > script. How did you create it? Using py2exe? Use windows=your_program.py instead of console=... in your setup script. -- Gabriel Genellina From jldunn2000 at googlemail.com Thu Jun 21 06:19:48 2007 From: jldunn2000 at googlemail.com (loial) Date: Thu, 21 Jun 2007 03:19:48 -0700 Subject: install paramiko on AIX (ActiveState) Message-ID: <1182421188.003383.178400@c77g2000hse.googlegroups.com> I need help installing paramiko on ActiveState python on AIX 5 I am new to python so need info on how to download and install paramiko AIX box does not have internet connection so presume cannot use ez_setup.py? Can anyone help? From kyosohma at gmail.com Thu Jun 14 17:27:15 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Thu, 14 Jun 2007 21:27:15 -0000 Subject: Questions about mathematical and statistical functionality in Python In-Reply-To: References: Message-ID: <1181856435.026267.225930@q19g2000prn.googlegroups.com> On Jun 14, 4:02 pm, "Talbot Katz" wrote: > Greetings Pythoners! > > I hope you'll indulge an ignorant outsider. I work at a financial software > firm, and the tool I currently use for my research is R, a software > environment for statistical computing and graphics. R is designed with > matrix manipulation in mind, and it's very easy to do regression and time > series modeling, and to plot the results and test hypotheses. The kinds of > functionality we rely on the most are standard and robust versions of > regression and principal component / factor analysis, bayesian methods such > as Gibbs sampling and shrinkage, and optimization by linear, quadratic, > newtonian / nonlinear, and genetic programming; frequently used graphics > include QQ plots and histograms. In R, these procedures are all available > as functions (some of them are in auxiliary libraries that don't come with > the standard distribution, but are easily downloaded from a central > repository). > > For a variety of reasons, the research group is considering adopting Python. > Naturally, I am curious about the mathematical, statistical, and graphical > functionality available in Python. Do any of you out there use Python in > financial research, or other intense mathematical/statistical computation? > Can you compare working in Python with working in a package like R or S-Plus > or Matlab, etc.? Which of the procedures I mentioned above are available in > Python? I appreciate any insight you can provide. Thanks! > > -- TMK -- > 212-460-5430 home > 917-656-5351 cell I'd look at following modules: matplotlib - http://matplotlib.sourceforge.net/ numpy - http://numpy.scipy.org/ Finally, this website lists other resources: http://www.astro.cornell.edu/staff/loredo/statpy/ Mike From reubendb at gmail.com Mon Jun 11 14:18:58 2007 From: reubendb at gmail.com (reubendb) Date: Mon, 11 Jun 2007 18:18:58 -0000 Subject: Accessing global namespace from module In-Reply-To: <1181583469.562064.29440@p77g2000hsh.googlegroups.com> References: <1181577768.728377.262720@m36g2000hse.googlegroups.com> <1181583469.562064.29440@p77g2000hsh.googlegroups.com> Message-ID: <1181585938.144294.119790@w5g2000hsg.googlegroups.com> On Jun 11, 1:37 pm, kyoso... at gmail.com wrote: > On Jun 11, 11:02 am, reubendb wrote: > > > > > Hello, > > I am new to Python. I have the following question / problem. > > I have a visualization software with command-line interface (CLI), > > which essentially is a Python (v. 2.5) interpreter with functions > > added to the global namespace. I would like to keep my own functions > > in a separate module and then import that module to the main script > > (that will be executed using the CLI interpreter). The problem is, I > > cannot access the functions in the global namespace of the main script > > from my module. Is there anyway to do that ? > > > I think you're doing it backwards. If you want access to AddPlot, then > you should import mainscript into that module instead of the other way > around. When I have common methods I want to call from different > scripts, I put those methods/functions into their own module/file. > Then I just import the module and call whatever script I need. > > > > commonMods.py > --------------------- > AddPlot(*args, *kwargs): > # Do something > DrawPlots(*args, *kwargs): > # Do something > --------------------- Hi Mike, The problem is I don't define the functions AddPlot() and DrawPlots(). It's built into the python interpreter of the CLI version of the program I mentioned, and they are defined on the main script. I load the main script using something like "software -cli -s mainscript.py". In the mainscript.py I import myModule, but of course myModule does not have access to the functions defined in the global namespace of mainscript.py. Thanks. RDB From josiah.carlson at sbcglobal.net Sat Jun 2 22:32:04 2007 From: josiah.carlson at sbcglobal.net (Josiah Carlson) Date: Sat, 02 Jun 2007 19:32:04 -0700 Subject: Python rocks In-Reply-To: <4661da4f$0$19227$fa0fcedb@news.zen.co.uk> References: <4661adda$0$19256$da0feed9@news.zen.co.uk> <4661da4f$0$19227$fa0fcedb@news.zen.co.uk> Message-ID: Mark Carter wrote: > Josiah Carlson wrote: >> What kind of scoping did you desire? > > Well, I had in mind so that if you defined a function, but wanted to > access a global var, that you didn't have to use the global keyword. Not > much of a biggie, I guess. You already get read access to globals without using the global keyword. To replace what the global name points to you need to use the global keyword, but if it is mutable (list, dictionary, etc.), you can append to it, delete items from it, etc., all without keywords. > I guess that about wraps it up, then. Python pretty much has it all. > Except for macros - which is not necessarily a dealbreaker, anyway. Yeah, the lack of macros sometimes bothers me, then I remember that if I *really* need them, there's always Logix and bytecodehacks.inline: http://bytecodehacks.sourceforge.net/bch-docs/bch/module-bytecodehacks.inline.html I don't know how much work it would take to get the bytecodehacks working in a modern Python, but it may be an interesting exercise. - Josiah From warren at muse.com Tue Jun 5 15:04:29 2007 From: warren at muse.com (Warren Stringer) Date: Tue, 5 Jun 2007 12:04:29 -0700 Subject: c[:]() In-Reply-To: References: <00b301c7a690$25af37d0$240110ac@Muse> Message-ID: <015701c7a7a4$584fac00$240110ac@Muse> Roland Puntaier [mailto:Roland.Puntaier at br-automation.com] > Warren, can you please restate your point. Hey Roland, where were you a few days ago ;-) I think most suggestions were valid, in their own context. Only yesterday, was I finally able to get it in perspective, so here goes: There are two idioms: a domain specific language, called Tr3 http://muse.com/tr3/Tr3%20Overview.pdf , and Python. The idioms both complement each other and conflict. Most of this thread has explored that conflict. Tr3 has three main components: a namespace tree, a directed graph of inputs and a directed graph of outputs. By analogy: the namespace functions like XML, inputs function like callbacks, and outputs function like standard procedures. The precursor to Tr3 was written C++. The inputs were script while the outputs were in C++. So, any changes in procedure required a recompile. The new version still allows C++ plugins, but the procedures can be written in Python. Inputs to Tr3 are queries to other parts of the namespace. By analogy, inputs behave like an Xpath query. So `a//z` searches for all descendants of `a` named `z`. The results of a query yields a list that can change state for the node on the tree which made the query. Another example, more in line with the title of this thread, is the query `a[:4]b`, which returns a list `[a[0].b, a[1].b, a[2].b, a[3].b]` Outputs are Python. This thread was my way of exploring to what degree that the `a[:4]b` of inputs could be applied to outputs as `a[:4]b()`. It would be idiomatic to Tr3 but not as idiomatic to Python. Here's why: What should this mean? if a[:4]b(): . Should it mean: if a[0].b() and a[1].b() and a[2].b() and a[3].b(): . or if a[0].b() or a[1].b() or a[2].b() or a[3].b(): . or if a[0].b(): . if a[1].b(): . if a[2].b(): . if a[3].b(): . Each interpretation could be justified. Thus, the implicit iteration is ambiguous. I am porting code that only uses this form a[:4]b() Which translates to: for i in range(4): a[i].b() There is only one interpretation and thus unambiguous. I have also explored writing client code that interprets `a[:4]b` as: if a[0].b() and a[1].b() and a[2].b() and a[3].b(): . A few algorithms, like Huffman codes, wind up looking much simpler, with implicit iterators. Be that as it may, making such algorithms easier to read may not be worth the cost of adding ambiguity to a general purpose procedural language. So, you're all right. Relax. Get outdoors. Fall in love. Make someone happy. And thanks again, \~/ From bignose+hates-spam at benfinney.id.au Fri Jun 8 19:18:19 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sat, 09 Jun 2007 09:18:19 +1000 Subject: Working with fixed format text db's References: Message-ID: <87ps46vxvo.fsf@benfinney.id.au> Neil Cerutti writes: > I was hoping for a module that provides a way for me to specify a > fixed file format, along with some sort of interface for writing and > reading files that are in said format. Isn't that done by the 'struct' module ? >>> records = [ ... "Foo 13 Bar ", ... "Spam 23 Eggs ", ... "Guido 666Robot ", ... ] >>> record_format = "8s3s8s" >>> for record in [struct.unpack(record_format, r) for r in records]: ... print record ... ('Foo ', '13 ', 'Bar ') ('Spam ', '23 ', 'Eggs ') ('Guido ', '666', 'Robot ') -- \ "Buy not what you want, but what you need; what you do not need | `\ is expensive at a penny." -- Cato, 234-149 BC, Relique | _o__) | Ben Finney From sjmachin at lexicon.net Sat Jun 9 21:25:24 2007 From: sjmachin at lexicon.net (John Machin) Date: Sat, 09 Jun 2007 18:25:24 -0700 Subject: pyexe "format" In-Reply-To: References: Message-ID: <1181438724.935702.151780@z28g2000prd.googlegroups.com> On Jun 10, 10:38 am, hg wrote: > hg wrote: > > Hi, > > > Is there a clean way to figure out that a .exe was actually generated by > > pyexe ? > > > hg > > I should gave writtent "definite" instead of "clean" > > hg Reminds me of the story about a teacher trying to correct a student who was using rather dialectal English: You have went and putten "putten" when you should of putten "put"! :-) You should of looken at this: http://www.py2exe.org/index.cgi/WhereAmI HTH, John From horpner at yahoo.com Thu Jun 7 14:30:59 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Thu, 07 Jun 2007 18:30:59 GMT Subject: running a random function References: <1654405.LVbK4P6cM3@teancum> <1181239338.068346.323050@h2g2000hsg.googlegroups.com> Message-ID: On 2007-06-07, Stebanoid wrote: > if you have a list of functions you can try this: > > import random > import math > m[int(math.floor(len(m)*random.random()))]() # seems like Lisp Or rather m[random.randint(0, len(m))]() -- Neil Cerutti Caution: Cape does not enable user to fly. --Kenner's Batman costume From max at alcyone.com Sat Jun 9 21:57:06 2007 From: max at alcyone.com (Erik Max Francis) Date: Sat, 09 Jun 2007 18:57:06 -0700 Subject: urllib2 - iteration over non-sequence In-Reply-To: References: <1181427526.996101.75230@m36g2000hse.googlegroups.com> <466B2AA7.3040704@websafe.com> <1181429903.533207.105730@p77g2000hsh.googlegroups.com> Message-ID: Gary Herron wrote: > So... You must explicitly read the contents of the file-like object > yourself, and loop through the lines you self. However, fear not -- > it's easy. The socket._fileobject object provides a method "readlines" > that reads the *entire* contents of the object, and returns a list of > lines. And you can iterate through that list of lines. Like this: > > import urllib2 > url = urllib2.urlopen('http://www.google.com') > for line in url.readlines(): > print line > url.close() This is really wasteful, as there's no point in reading in the whole file before iterating over it. To get the same effect as file iteration in later versions, use the .xreadlines method:: for line in aFile.xreadlines(): ... -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM, Y!M erikmaxfrancis If you flee from terror, then terror continues to chase you. -- Benjamin Netanyahu From gagsl-py2 at yahoo.com.ar Mon Jun 11 16:43:37 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 11 Jun 2007 17:43:37 -0300 Subject: REALLY need help with iterating a list. References: <1181586648.614514.228900@m36g2000hse.googlegroups.com> <1181588376.426556.46530@j4g2000prf.googlegroups.com> <1181592683.009076.24300@p77g2000hsh.googlegroups.com> Message-ID: En Mon, 11 Jun 2007 17:11:23 -0300, Radamand escribi?: > On Jun 11, 1:23 pm, Fredrik Lundh wrote: >> here's a simple variation of that, which is a bit more efficient, and >> perhaps also a bit easier to use in the general case: >> >> while serverlist: >> still_active = [] >> for server in serverlist: >> pinger = ping[server] >> if pinger.returncode is None: >> pinger.poll() >> still_active.append(server) >> else: >> pingresult[server] = pinger.stdout.read() >> pingreturncode[server] = pinger.returncode >> serverlist = still_active >> >> > > Thats an interesting approach but, if the returncode for a given > server is None say, 20 times in a row you will have append'ed that > server to the list 20 times, i suppose you could check the list to see > if its already there but thats a bit kludgey... Read the code again and notice that there are TWO lists involved. There is at most one append per server - unless there are duplicates in the original list, the new list won't have any. > also, the line "pinger = ping[server]" would have to be extracted from > this loop otherwise your going to ping the same server repeatedly > until it answers... Uh...? -- Gabriel Genellina From DustanGroups at gmail.com Thu Jun 14 16:37:59 2007 From: DustanGroups at gmail.com (Dustan) Date: Thu, 14 Jun 2007 20:37:59 -0000 Subject: a_list.count(a_callable) ? In-Reply-To: <1181850818.567840.251090@x35g2000prf.googlegroups.com> References: <1181850818.567840.251090@x35g2000prf.googlegroups.com> Message-ID: <1181853479.914070.217270@i13g2000prf.googlegroups.com> On Jun 14, 2:53 pm, Ping wrote: > Hi, > > I'm wondering if it is useful to extend the count() method of a list > to accept a callable object? What it does should be quite intuitive: > count the number of items that the callable returns True or anything > logically equivalent (non-empty sequence, non-zero number, etc). > > This would return the same result as len(filter(a_callable, a_list)), map and filter are basically obsolete after the introduction of list comprehensions; your expression is equivalent to: len([i for i in a_list if a_callable(i)]) Which can then be converted into a generator expression (round brackets instead of square brackets) to avoid the intermediate list: len((i for i in a_list if a_callable(i))) Or syntactically equivalent (avoiding lispy brackets): len(i for i in a_list if a_callable(i)) > but without constructing an intermediate list which is thrown away > after len() is done. > > This would also be equivalent to > n = 0 > for i in a_list: > if a_callable(i): n += 1 > but with much shorter and easier-to-read code. It would also run > faster. > > This is my first post and please bear with me if I'm not posting it in > the right way. > > Regards, > Ping From bscrivener42 at gmail.com Sat Jun 9 08:44:27 2007 From: bscrivener42 at gmail.com (BartlebyScrivener) Date: Sat, 09 Jun 2007 12:44:27 -0000 Subject: VIM editor question In-Reply-To: References: Message-ID: <1181393067.068779.265610@g4g2000hsf.googlegroups.com> On Jun 9, 1:14 am, "Jerry VanBrimmer" wrote: > In your vim configuration file enter: > > colorscheme > > Example: > > colorscheme elflord > > Restart vim. No! That's completely wrong. It should be: colorscheme moria set bg=dark http://www.vim.org/scripts/script.php?script_id=1464 From evan at yelp.com Wed Jun 13 01:08:52 2007 From: evan at yelp.com (Evan Klitzke) Date: Tue, 12 Jun 2007 22:08:52 -0700 Subject: How to save python codes in files? In-Reply-To: <1181711063.512249.289520@x35g2000prf.googlegroups.com> References: <1181711063.512249.289520@x35g2000prf.googlegroups.com> Message-ID: On 6/12/07, why? wrote: > Im working with Python 2.2 on my red hat linux system. Is there any > way to write python codes in separate files and save them so that i > can view/edit them in the future? Actually I've just started with > python and would be grateful for a response. Thanx! Of course -- just put the code into a text file (using your favorite text editor) and then run the script using the python command, e.g. by executing on a command line: python my_program.py Since you're on a Linux system you can also use this as the first line of your file and then chmod +x the file to make it into an executable script: #!/usr/bin/env python -- Evan Klitzke From bbxx789_05ss at yahoo.com Mon Jun 25 22:23:52 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: Mon, 25 Jun 2007 19:23:52 -0700 Subject: can't start Apache on Mac OS X--no listening sockets available? Message-ID: <1182824632.015853.317970@g4g2000hsf.googlegroups.com> I'm trying to get Apache set up on my system so I can use mod_python. I installed Apache 2.2.4 according to the following instructions: http://switch.richard5.net/isp-in-a-box-v2/installing-apache-on-mac-os-x/#comment-30704 and everything seemed to install correctly, but I can't start Apache. I typed in the following command: $ sudo /Library/Apache2/bin/apachectl start Password: and I got this error message: httpd: Could not reliably determine the server's fully qualified domain name, using tms-computer.local for ServerName (48)Address already in use: make_sock: could not bind to address 0.0.0.0:80 no listening sockets available, shutting down Unable to open logs Any ideas? From hn_sd_ywx_xiaq at 163.com Wed Jun 27 20:40:47 2007 From: hn_sd_ywx_xiaq at 163.com (XiaQ) Date: Thu, 28 Jun 2007 08:40:47 +0800 Subject: How can I 'compound' streams? Message-ID: I need to build a stream that writes to stdout and a file at the same time. Is there already a function in the Python library to do this? From steve at holdenweb.com Sat Jun 2 13:11:05 2007 From: steve at holdenweb.com (Steve Holden) Date: Sat, 02 Jun 2007 13:11:05 -0400 Subject: Python 2.3 ODBC Datetime limitations In-Reply-To: <33cd6d8d0706011112w554ee6darea56f0977e9e3216@mail.gmail.com> References: <33cd6d8d0706011112w554ee6darea56f0977e9e3216@mail.gmail.com> Message-ID: <4661A4A9.60805@holdenweb.com> YuePing Lu wrote: > Hello, > > Has any of you ever used Python odbc to retrieve data from a relational DB? > > I encountered a problem where it can't handle datetime _earlier than > _*1969*, and _later than _*2040*. It just returned some garbage strings > when I call str(my_date_object). > > When I call strptime to convert the value I got ValueError exception: > > # Table records > for record in self._records: > columns = [] > for i in range(len(self._description)): > if self._description[i][1]=='DATE': > strDate=str(record[i]) > try: > #convert the date format to be mm/dd/yyyy: > oDate=time.strptime(strDate) #convert to struct_time object > strfDate=time.strftime("%m/%d/%Y", oDate) > > columns.append(strfDate) > except ValueError, msg: > raise "Date converstion error", msg > > ... > Any other solutions that you've heard? > > Thanks very much in advance, > Reading the documentation for the time module, you will see: The epoch is the point where the time starts. On January 1st of that year, at 0 hours, the ``time since the epoch'' is zero. For Unix, the epoch is 1970. To find out what the epoch is, look at gmtime(0). The functions in this module do not handle dates and times before the epoch or far in the future. The cut-off point in the future is determined by the C library; for Unix, it is typically in 2038. So this may not be a problem with the odbc module, which isn't the most up-to-date piece of software on the block but is mostly reliable for simple purposes. I'd try something from the datetime module. When I retrieve a date column from a postgreSQL database using ODBC is see: >>> curs.execute("SELECT orginvdt FROM organization WHERE orginvdt IS NOT NULL") 0 >>> row = curs.fetchone() >>> row (,) >>> dbidate = row[0] >>> dir(dbidate) [] So it isn't easy to know just by looking what you can do with a dbitdate. But if you can hack around with the time module you can probably hack around with datetime too, and that's a more capable module. However it's possible that the epoch-to-2038 restriction is actually imposed byt he odbc drivers, in which case you will need to look for another Python driver module for your database. It would have been helpful if you hadn't trapped the exception so that we could have seen the exact traceback - this would have given man more clues as to what was going on. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden ------------------ Asciimercial --------------------- Get on the web: Blog, lens and tag your way to fame!! holdenweb.blogspot.com squidoo.com/pythonology tagged items: del.icio.us/steve.holden/python All these services currently offer free registration! -------------- Thank You for Reading ---------------- From joe at incomps.com Mon Jun 4 18:09:01 2007 From: joe at incomps.com (Joe) Date: Mon, 4 Jun 2007 16:09:01 -0600 Subject: MySQL InterfaceError In-Reply-To: <001e01c7a6f3$e687ed40$0f01a8c0@desktop9> References: <001e01c7a6f3$e687ed40$0f01a8c0@desktop9> Message-ID: <002901c7a6f4$f55e56a0$0f01a8c0@desktop9> Sorry, forgot some valuable information. If you couldn't tell from the traceback, the error will be thrown during the first executed query that the program runs into (no matter what that query is). Jough _____ From: python-list-bounces+joe=incomps.com at python.org [mailto:python-list-bounces+joe=incomps.com at python.org] On Behalf Of Joe Sent: Monday, June 04, 2007 4:01 PM To: python-list at python.org Subject: MySQL InterfaceError I still consider myself a newbie, and being new to the list I request that you take it easy on me. ;) We're running a RHEL LAMP server with the mod_python publisher interpreter. The MySQLdb module seems to be giving me more problems than I had hoped for. With a fresh restart of apache, all programs run flawlessly for an average of 7-8 executions, but then will return an InterfaceError. The last few lines of the traceback are as follows: File "build/bdist.linux-i686/egg/MySQLdb/cursors.py", line 147, in execute charset = db.character_set_name() InterfaceError: (0, '') This InterfaceError will continue sporadically about half of the time the programs are run. We are running mysql version 4.1.2 so I was assuming it may be caused by the mysql_character_set_name() bug (as shown in the comments here: http://dev.mysql.com/doc/refman/5.0/en/mysql-character-set-name.html), but this was ruled out when the error continued after hard coding the charset as utf8. As you can see, without any error description this is very hard to debug. I have spent several days researching this and have come up empty handed. I would appreciate any help anyone can give. If this is the wrong list to ask, please let me know and I will repost elsewhere. Versions: Python: 2.5.1 MySQL: 4.1.2 MySQLdb: 1.2.2 Thanks! Jough -------------- next part -------------- An HTML attachment was scrubbed... URL: From kaldrenon at gmail.com Thu Jun 21 16:10:18 2007 From: kaldrenon at gmail.com (Kaldrenon) Date: Thu, 21 Jun 2007 20:10:18 -0000 Subject: The Modernization of Emacs: terminology buffer and keybinding In-Reply-To: <1182453375.531950.141460@m36g2000hse.googlegroups.com> References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182272495.990807.99110@a26g2000pre.googlegroups.com> <87tzt3ihev.fsf@kobe.laptop> <1182370216.961241.6960@n60g2000hse.googlegroups.com> <85zm2ufjpb.fsf@lola.goethe.zz> <1182372592.803332.288260@u2g2000hsc.googlegroups.com> <1182373919.262388.100740@c77g2000hse.googlegroups.com> <85r6o6fhkb.fsf@lola.goethe.zz> <1182375045.626510.188170@m36g2000hse.googlegroups.com> <1182453375.531950.141460@m36g2000hse.googlegroups.com> Message-ID: <1182456618.763414.219080@g4g2000hsf.googlegroups.com> Feel free to disagree with what I'm about to say. I know that this thread would be far, FAR shorter if OP hadn't been instigating disagreement, but so far most of the discourse has been polite, so I'm going to say what I'm thinking. I think there are far too many people in all camps (the Emacs camp, the vi* camp, and the GUI/IDE/point-and-click-and-make- everything-"user-friendly" camp) who look at this disagreement as a debate in which they Are Right, and the members of the other two camps Are Wrong. There are billions of people in this world, and even if you ignore the ones who don't need to use a text editor or word processor on a regular basis, you end up with a VERY large number of people. And people are different. We think differently, we all have different things that come to us naturally, different things that are tricky but learn-able, and different things that we'll never be able to do without a manual open in front of us. There are a lot of people for whom emacs is easy to learn, logical to use, and the way it is set up (or at least the way -they- set it up) is so natural to them that they'll never be as productive anywhere else. But there are also a lot of people for whom emacs doesn't click, who can give it a genuine try but still not catch on, and even once they learn enough to muddle through, they'll always work better in Word, or in an IDE. But I think there's something else to it, and it's part of why I think the emacs faithful swear by it so fiercely, even if it does seem a daunting tool to master. I don't think anyone can make the argument that any (past or current) graphics-based editor is as efficient when being used to its fullest as a text-based editor. It's basic math - it takes measurably more time to move a hand to the mouse, move/click the mouse, and more the hand back to the touch-typing position than it does to execute even a moderately complex series of keystrokes. Maybe not large amounts of time -per action-, but it doesn't take too long for it to add up if you spend a lot of time editing. Contrast the time saved by not having to reposition one's hands, the extensibility, and customization against the learning curve of an interface that doesn't exactly throw its controls at the user, and here's the conclusion I think results: graphical interfaces are - easier- to develop some proficiency with, but proficiency with emacs pays of far more in the long run. And if you disagree with me, or if you think I expressed my point poorly (I'm good that that), all you need to do is ask Steve Yegge his thoughts on emacs. -Andrew From doug at alum.mit.edu Fri Jun 29 12:53:49 2007 From: doug at alum.mit.edu (Douglas Alan) Date: Fri, 29 Jun 2007 12:53:49 -0400 Subject: Python's "only one way to do it" philosophy isn't good? References: <7xejjzmk7u.fsf@ruckus.brouhaha.com> <7xy7i7xjl5.fsf@ruckus.brouhaha.com> <1183098228.517915.12140@q75g2000hsh.googlegroups.com> Message-ID: Steve Holden writes: > "Python" doesn't *have* any refcounting semantics. I'm not convinced that Python has *any* semantics at all outside of specific implementations. It has never been standardized to the rigor of your typical barely-readable language standards document. > If you rely on the behavior of CPython's memory allocation and > garbage collection you run the risk of producing programs that won't > port tp Jython, or IronPython, or PyPy, or ... > This is a trade-off that many users *are* willing to make. Yes, I have no interest at the moment in trying to make my code portable between every possible implementation of Python, since I have no idea what features such implementations may or may not support. When I code in Python, I'm coding for CPython. In the future, I may do some stuff in Jython, but I wouldn't call it "Python" -- it'd call it "Jython". When I do code for Jython, I'd be using it to get to Java libraries that would make my code non-portable to CPython, so portability here seems to be a red herring. |>oug From martin at v.loewis.de Tue Jun 5 03:19:08 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 05 Jun 2007 09:19:08 +0200 Subject: Getting mount stats for filesystems In-Reply-To: References: Message-ID: <46650e6c$0$25817$9b622d9e@news.freenet.de> Mitko Haralanov schrieb: > Hi, I am trying to find a way to figure out whether a certain remote > filesystem is mounted using tcp vs. udp in Python. I've looked at the > statvfs call and module but they don't give me anything useful (the > F_FLAGS field for both a tcp and a udp filesystem is the same. > > I could, of course, get the output of mount and parse that but I would > prefer something more elegant. I'm not quite sure what you want to achieve. You are on machine B, and you want to find out whether a remote file system (on machine A) is mounted remotely (say, from machine C)? How do you answer that question with mount(8)? Also, what is a tcp filesystem? Regards, Martin From simonroses at granisla.com Thu Jun 28 16:50:03 2007 From: simonroses at granisla.com (Simon Roses Femerling) Date: Thu, 28 Jun 2007 22:50:03 +0200 Subject: Vista 64 + Python2.5 + wxpython 28 issue In-Reply-To: <4684150e$0$24850$9b622d9e@news.freenet.de> References: <4684150e$0$24850$9b622d9e@news.freenet.de> Message-ID: <000001c7b9c5$e70a0d40$b51e27c0$@com> Hello Martin, I installed wxpython 2.8 using the installer (wxPython2.8-win32-unicode-2.8.4.0-py25.ex), yeah I assume is the 32 bits version. Is there any 64 version installer or do I need to build myself ? Thanks, SRF -----Original Message----- From: python-list-bounces+simonroses=granisla.com at python.org [mailto:python-list-bounces+simonroses=granisla.com at python.org] On Behalf Of "Martin v. L?wis" Sent: jueves, 28 de junio de 2007 22:08 To: python-list at python.org Subject: Re: Vista 64 + Python2.5 + wxpython 28 issue > I have installed python 2.5 (AMD64) on Vista (64), also installed wx 2.8 > but I'm getting this error: > > """" > Traceback (most recent call last): > File "mymodule.py", line 39, in > import wx > File "C:\Python25\Lib\site-packages\wx-2.8-msw-unicode\wx\__init__.py", > line 4 > 5, in > from wx._core import * > File "C:\Python25\Lib\site-packages\wx-2.8-msw-unicode\wx\_core.py", > line 4, i > n > import _core_ > ImportError: DLL load failed with error code 193 > """ > > I have set python.exe to run under admin but that do not fix the problem. > > Any ideas ? 193 means ERROR_BAD_EXE_FORMAT. Could it be that you are using a 32-bit extension DLL? How precisely did you "install" wx 2.8? Did you rebuild it from source? Regards, Martin -- http://mail.python.org/mailman/listinfo/python-list From python at jayloden.com Mon Jun 18 12:36:49 2007 From: python at jayloden.com (Jay Loden) Date: Mon, 18 Jun 2007 12:36:49 -0400 Subject: Parsing HTML, extracting text and changing attributes. In-Reply-To: References: <1182175239.122827.4150@g4g2000hsf.googlegroups.com> Message-ID: <4676B4A1.4040402@jayloden.com> Neil Cerutti wrote: > You could get good results, and save yourself some effort, using > links or lynx with the command line options to dump page text to > a file. Python would still be needed to automate calling links or > lynx on all your documents. OP was looking for a way to parse out part of the file and apply classes to certain types of tags. Using lynx/links wouldn't help, since the output of links or lynx is going to end up as plain text and the desire isn't to strip all the formatting. Someone else mentioned lxml but as I understand it lxml will only work if it's valid XHTML that they're working with. Assuming it's not (since real-world HTML almost never is), perhaps BeautifulSoup will fare better. http://www.crummy.com/software/BeautifulSoup/documentation.html -Jay From felciano at gmail.com Fri Jun 22 13:18:11 2007 From: felciano at gmail.com (felciano) Date: Fri, 22 Jun 2007 10:18:11 -0700 Subject: Python plain-text database or library that supports joins? Message-ID: <1182532691.182581.110940@m37g2000prh.googlegroups.com> Hello -- Is there a convention, library or Pythonic idiom for performing lightweight relational operations on flatfiles? I frequently find myself writing code to do simple SQL-like operations between flat files, such as appending columns from one file to another, linked through a common id. For example, take a list of addresses and append a 'district' field by looking up a congressional district from a second file that maps zip codes to districts. Conceptually this is a simple database operation with a join on a common field (zip code in the above example). Other case use other relational operators (projection, cross-product, etc) so I'm really looking for something SQL-like in functionality. However, the data is in flat-files, the file structure changes frequently, the files are dynamically generated from a range of sources, are short-lived in nature, and otherwise not warrant the hassle of a database setup. So I've been looking around for a nice, Pythonic, zero-config (no parsers, no setup/teardown, etc) solution for simple queries that handles a database of csv-files-with-headers automatically. There are number of solutions that are close, but in the end come up short: - KirbyBase 1.9 (latest Python version) is the closest that I could find, as it lets you keep your data in flatfiles and perform operations using the field names from those text-based tables, but it doesn't support joins (the more recent Ruby version seems to). - Buzhug and Sqlite have their data structures w no automatic .tab or .csv parsing (unless sqlite includes a way to map flatfiles to sqlite virtual tables that I don't know about). - http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/159974 is heading in the right direction, as it shows how to perform relational operations on lists and are index based rather than field-name based. - http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/498130 and http://furius.ca/pubcode/pub/conf/common/bin/csv-db-import.html provide ways of automatically populating DBs but not the reverse (persist changes back out to the data files) The closest alternatives I've found are the GNU textutils that support join, cut, merge, etc but I need to add additional logic they don't support, nor do they allow field-level write operations from Python (UPDATE ... WHERE ...). Normally I'd jump right in and start coding but this seems like something so common that I would have expected someone else to have solved, so in the interest of not re-inventing the wheel I thought I'd see if anyone had any other suggestions. Any thoughts? Thanks! Ramon From stefan.sonnenberg at pythonmeister.com Tue Jun 19 16:47:10 2007 From: stefan.sonnenberg at pythonmeister.com (Stefan Sonnenberg-Carstens) Date: Tue, 19 Jun 2007 22:47:10 +0200 Subject: labeled break/continue In-Reply-To: <20070619200021.GG26884@theory.org> References: <20070619200021.GG26884@theory.org> Message-ID: <467840CE.2070208@pythonmeister.com> Matt Chisholm schrieb: > On Mon, 18 Jun 2007 05:28, faulkner wrote: > >> On Jun 18, 12:35 am, Matt Chisholm wrote: >> >>> Hi. I was wondering if there had ever been an official decision on >>> the idea of adding labeled break and continue functionality to Python. >>> > > >> python-dev just mentioned that the BDFL vetoed it a while ago. >> they're writing a PEP just to document why it was vetoed. >> >> > > Really? I can't find anything in the python-dev archives, or in the > list of PEPs. Does anyone know the PEP number (if one has been > assigned)? Or maybe someone could send me a link to the discussion or > forward the discussion to me off list? That would be much > appreciated. > > -matt > What should a labled break/continue be good for ? Sounds like goto to me, which is also almost useless in almost every case. And to me, a solution are local functions, or properly defined if elif else stmts. A local function with no params and/or returns is as good as labeled thingys. What python really need is a switch stmt ;-) (Even perl6 will have one - if one will ever have perl6...) From deets at nospam.web.de Sun Jun 10 08:12:57 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 10 Jun 2007 14:12:57 +0200 Subject: matching objects by a tuple field criterion In-Reply-To: <1181476538.812941.37490@r19g2000prf.googlegroups.com> References: <1181473124.790391.293120@r19g2000prf.googlegroups.com> <1181476538.812941.37490@r19g2000prf.googlegroups.com> Message-ID: <5d286hF32u0ciU1@mid.uni-berlin.de> bullockbefriending bard schrieb: >> Instead of passing a wild-card tuple like (*,*,*,4,*,*) simply pass the >> integer you want to match and the position you want to match it in. > > for sure. that was more for expository purpose rather than how i was > planning to go about it. > > >> As a generator expression: >> >> (obj for obj in list_of_objects if obj.data[what] == where) > > above or equivalent list comprehension was what i had in mind as far > as linear search goes. and scanning the list like this will most > likely be 'good enough' performance-wise. however, partly just out of > curiosity, i was wondering if there is some kind of data structure > which might let me find all the matches a bit faster. You can of course create a tree from the tuples, where the first level of nodes corresponds to the first attribute of the tuple and so forth. There are certainly cases where the speedup is tremendous - think of a single integer in the first criteria - but then the overall performance depends on the real-live queries. If lot's of wildcards are used, you might end up slower if the tree-walk takes more time than the C-implemented list-iteration will cost you. Diez From matt-python at theory.org Mon Jun 18 00:35:52 2007 From: matt-python at theory.org (Matt Chisholm) Date: Sun, 17 Jun 2007 21:35:52 -0700 Subject: labeled break/continue Message-ID: <20070618043552.GA28584@theory.org> Hi. I was wondering if there had ever been an official decision on the idea of adding labeled break and continue functionality to Python. I've found a few places where the idea has come up, in the context of named code blocks: http://groups.google.com/group/comp.lang.python/browse_thread/thread/a696624c92b91181/065b1dbc13ec2807?lnk=gst&q=labeled+break&rnum=1#065b1dbc13ec2807 and in the context of discussing do/while loops and assignments in conditionals: http://groups.google.com/group/comp.lang.python/browse_thread/thread/6da848f762c9cf58/979ca3cd42633b52?lnk=gst&q=labeled+break&rnum=3#979ca3cd42633b52 Both of those discussions just kind of petered out or changed direction without any conclusion. There's also this Python 2.6 which has a similar syntax (although different semantics) to one of the syntaxes proposed in the first discussion above: http://sourceforge.net/tracker/index.php?func=detail&aid=1714448&group_id=5470&atid=355470 I would be willing to help make a case and then write a PEP for labeled break and continue, as long as the community or the BDFL hasn't already decided against it. -matt P.S. My apologies about cross posting; python-ideas seems like a better place to post this, but PEP 1 says to post to python-list. From kyosohma at gmail.com Tue Jun 12 13:21:05 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Tue, 12 Jun 2007 17:21:05 -0000 Subject: Forgetting an import In-Reply-To: <1181666164.640868.225130@i38g2000prf.googlegroups.com> References: <1181666164.640868.225130@i38g2000prf.googlegroups.com> Message-ID: <1181668865.591796.232790@x35g2000prf.googlegroups.com> On Jun 12, 11:36 am, HMS Surprise wrote: > I imported a set of functions from a file I wrote to interpreter > shell: > > from myFile import * > > Now if I change functions in this file how can I make python forget it > so I can force a fresh import? > > thanx, > > jh If you did an import FunctionName, then you could use the "reload" built-in. Otherwise, I think you'll just have to restart the shell. import FunctionName # do something # reload FunctionName after editing it reload(FunctionName) Mike From cam.ac.uk at mh391.invalid Sun Jun 24 14:18:00 2007 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Sun, 24 Jun 2007 19:18:00 +0100 Subject: Accessing variable from a function within a function In-Reply-To: References: Message-ID: Nathan Harmston wrote: > Hi, > > I m playing around with extended euclids algorithm from Knuth. I m > trying to build a function with a function inside it. > > def exteuclid(m,n): > a,a1,b,b1,c,d = 0,1,1,0,m,n > def euclid(c,d): > q = c /d > r = c % d > if r == 0: > print a,b > return d > else: > print a1,a,b1,b,c,d,q,r > t = b1 > b = t - q * b > a = t - q * a > c,d,a1,b1 = d,r,a,b > return euclid(c,d) > return euclid(c,d) > > Unfortunately this doesnt work since a,a1,b,b1 arent declared in the > function. Is there a way to make these variables accessible to the > euclid function. Or is there a better way to design this function? Well, it would be simpler to pass through all the variables rather than relying on variables in a wider scope. -- Michael Hoffman From stephenhorne100 at aol.com Sun Jun 3 18:20:18 2007 From: stephenhorne100 at aol.com (Ninereeds) Date: Sun, 03 Jun 2007 15:20:18 -0700 Subject: *Naming Conventions* In-Reply-To: References: Message-ID: <1180909218.939713.112010@q69g2000hsb.googlegroups.com> On Jun 4, 5:03 am, Thorsten Kampe wrote: > for validanswer in validanswers: > if myAnswers.myanswer in myAnswers.validAnswers[validanswer]: > MyOptions['style'] = validanswer First, for small loops with loop variables whose meaning is obvious from context, the most readable name is usually something like 'i' or 'j'. It avoids unnecessary duplication and clutter. Of course, just as physically turning your head to look in the rear view mirror is necessary in a driving test but stupid for real driving, you are likely to be penalised for this if you do it in an educational setting or somewhere else where daft coding conventions are strictly enforced (I once worked in a company that had library constants 'Zero' and 'One' defined because the coding conventions insisted on absolutely no unnamed 'magic numbers' - spelling the numbers using letters apparently didn't count). Second, when naming a member, you should take into account that references will already be specifying what the whole class describes. That is, provide new information where possible, and avoid unnecessary repetition. Since Python is dynamically typed, it can be useful for names to describe the datatype of the content at times (though not to the Hungarian notation extreme that is common is C code, esp. for Windows). And while most variable names are nouns, sometimes adjectives are most appropriate - esp where the noun is already clear from context. Based on this, your code might become something like... for i in validanswers: if myAnswers.current in myAnswers.validList [i]: MyOptions['style'] = i 'i' Its obviously a validanswer since it is one of the validanswers. 'myAnswers.current' I know its related to myAnswers, but the adjective 'current' tells me more about this specific member. 'myAnswers.validList' 'valid' on its own is useful extra information, but suggests a flag field. validList is better since it avoids that confusion. Depending on what myAnswers.myanswer actually holds, it might alternately be renamed something like myAnswers.uid or myAnswers.id (a [unique] identifier code identifying the answer) or myAnswers.text (the text of the answer). It is also often useful to use a convention where a prefix identifies whether a name is a (p)arameter, (l)ocal variable, or (m)ember variable - no prefix for functions, usually. For example, a simple setter method may logically use the same name for the parameter specifying the value to write, the member variable to write to, and (barring a prefix along the lines of 'Set') the method name. From dek at oliver.lbl.gov Mon Jun 25 11:11:01 2007 From: dek at oliver.lbl.gov (David E. Konerding DSD staff) Date: Mon, 25 Jun 2007 15:11:01 +0000 (UTC) Subject: Chroot Jail Not Secure for Sandboxing Python? References: <1182748892.916068.146780@p77g2000hsh.googlegroups.com> <467f55f7$0$20850$9b622d9e@news.freenet.de> <1182782910.811850.284350@u2g2000hsc.googlegroups.com> Message-ID: On 2007-06-25, gregpinero at gmail.com wrote: > On Jun 25, 1:43 am, "Martin v. L?wis" wrote: >> gregpin... at gmail.com schrieb: >> >> > This wiki page suggests using a chroot jail to sandbox Python, but >> > wouldn't running something like this in your sandboxed Python instance >> > still break you out of the chroot jail: >> >> > os.execle ('/usr/bin/python','-c','import os; os.execlp("/bin/sh")', >> > {}) >> >> Depending on how the chroot jail is set up, this command might not >> work - in the jail, /bin/sh might not exist. > > I followed up with my ISP. Here's the answer I got: > > The os.exec call prepends the chroot directory to the absolute path, > but does NOT provide chroot for the child process. However, as long > as the environment is maintained, which contains an LD_PRELOAD, the > "chroot" will also be maintained. If LD_PRELOAD is removed or > ignored, then the chroot is ineffective. > > Another way of saying it is that every process is responsible for > providing and maintaining the chroot through the LD_PRELOAD variable. > Those processes only maintain the chroot if that variable remains set. None of this makes any sense to me. Once an application is running inside a chroot, there is no easy manipulation the application can do "to break out". The example you gave above executes a shell that is in the chroot dir. That's not really breaking out of the sandbox, it's just accessing something inside the sandbox. if your ISP is trying to enforce chroot through an LD_PRELOAD library, they might be using 'fakechroot' which doesn't look very good to me. Dave From hg at nospam.org Tue Jun 12 15:25:52 2007 From: hg at nospam.org (hg) Date: Tue, 12 Jun 2007 14:25:52 -0500 Subject: stdout/err and C extentions Message-ID: <5rCbi.98038$vE1.59482@newsfe24.lga> Hi, I have the following ********************* C extention - redir.c #include "Python.h" PyObject * test_redir_test(PyObject *self) { fprintf(stdout, "Hello from an extention!\n"); Py_INCREF(Py_None); return Py_None; } static PyMethodDef test_redir_methods[] = { {"test", (PyCFunction)test_redir_test, METH_NOARGS, "Prints test string \n"}, {NULL, NULL, 0, NULL} }; DL_EXPORT(void) inittest_redir(void) { Py_InitModule3("test_redir", test_redir_methods, "Provides a test function.\n"); } ********************* setup.py : from distutils.core import setup, Extension import sys import os include = [] setup(name="test_redir", version="0.1", ext_modules=[ Extension( "test_redir", ["redir.c"], undef_macros=['RELEASE'], library_dirs=[], ) ] ) *********************** python test script: test.py: import sys class My_Stdout: def write(self, p_string): l_file = open('res.txt','a') l_file.write(p_string) l_file.close sys.stdout = My_Stdout() print 'toto' import test_redir test_redir.test() **************** Question: print 'toto' does go to "res.txt" while "Hello from an extention!\n" goes to the console. Any clue ? Thanks, hg From nikbaer at gmail.com Wed Jun 13 21:20:16 2007 From: nikbaer at gmail.com (nik) Date: Thu, 14 Jun 2007 01:20:16 -0000 Subject: save class Message-ID: <1181784016.454693.42340@o11g2000prd.googlegroups.com> Hi, I would like to create a class and then save it for re-use later. I have tried to use pickle, but am not sure if that is right. I am sorry, but I am new to python. Basically, I have a class, Map. I want to be able to create new maps: MapA, MapB... that have Map as the base class. start with- class Map: pass and then get a different class class MapA(Map): pass that can be saved in a .py file for re-use so far I thought that - cls = new.classobj('MapA', (Map, ), {}) file = open('somefile', mode='w') pickle.dump(cls, file) -might work, but it didn't.... can anybody point me in the right direction? I know that classes must get saved from the interactive console, so I would think that it would be a standard thing to do. Thank you, Nik From doug at alum.mit.edu Fri Jun 29 09:56:14 2007 From: doug at alum.mit.edu (Douglas Alan) Date: Fri, 29 Jun 2007 09:56:14 -0400 Subject: Python's "only one way to do it" philosophy isn't good? References: <7xejjzmk7u.fsf@ruckus.brouhaha.com> <7xy7i7xjl5.fsf@ruckus.brouhaha.com> Message-ID: "Chris Mellon" writes: > You're arguing against explicit resource management with the argument > that you don't need to manage resources. Can you not see how > ridiculously circular this is? No. It is insane to leave files unclosed in Java (unless you know for sure that your program is not going to be opening many files) because you don't even know that the garbage collector will ever even run, and you could easily run out of file descriptors, and hog system resources. On the other hand, in Python, you can be 100% sure that your files will be closed in a timely manner without explicitly closing them, as long as you are safe in making certain assumptions about how your code will be used. Such assumptions are called "preconditions", which are an understood notion in software engineering and by me when I write software. |>oug From deets at nospam.web.de Tue Jun 26 05:37:09 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 26 Jun 2007 11:37:09 +0200 Subject: Face Recognition References: <1182814191.138864.80450@w5g2000hsg.googlegroups.com> Message-ID: <5ec525F388c7bU1@mid.uni-berlin.de> Henrik Lied wrote: > Hi there! > > Has anyone made effort to try to create a python binding to a facial > recognition software [1]? > > For those of you with some experience - would this be very hard? OpenCV has a python-binding. And a ctypes-binding. Diez From gagsl-py2 at yahoo.com.ar Tue Jun 19 22:17:07 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 19 Jun 2007 23:17:07 -0300 Subject: caseless dictionary howto ? References: <4dc64$46782a84$d443bb3a$4629@news.speedlinq.nl> <5c1e3$4678448d$d443bb3a$1513@news.speedlinq.nl> Message-ID: En Tue, 19 Jun 2007 19:40:10 -0300, Steven Bethard escribi?: > Stef Mientki wrote: >> Evan Klitzke wrote: >>> On 6/19/07, Stef Mientki wrote: >>>> >>>> I need to search a piece of text and make all words that are equal >>>> (except their case) also equal in their case, based on the first >>>> occurrence. > ... def __setitem__(self, key, value): > ... self._dict[key.lower()] = value > ... if key not in self._original_keys: > ... self._original_keys[key.lower()] = key > ... > > Note that because I store the first form encountered for every key, I > can always use the lower-case version to retrieve the "original string". As written, it stores the last used spelling; a small change is required to get the intended behavior: > ... def __setitem__(self, key, value): > ... self._dict[key.lower()] = value > ... if key.lower() not in self._original_keys: > ... self._original_keys[key.lower()] = key -- Gabriel Genellina From borud-news at borud.no Wed Jun 20 08:52:30 2007 From: borud-news at borud.no (Bjorn Borud) Date: 20 Jun 2007 14:52:30 +0200 Subject: The Modernization of Emacs: terminology buffer and keybinding References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182272495.990807.99110@a26g2000pre.googlegroups.com> <87tzt3ihev.fsf@kobe.laptop> Message-ID: [Giorgos Keramidas ] | | Educating the user to avoid confusion in this and other cases of made | up, 'user-friendly' descriptions is not a good enough answer. there are two types of "user friendly". there's "user friendly" and then there is "beginner friendly" which is often mislabeled. the latter is more important for applications which are to be used casually. like utilities you only use once or twice per year -- those need to be "beginner friendly". for applications you are likely to use for prolonged periods of time (like programming, video editing, music production etc), it does not make sense to optimize for "beginner friendly". at least not at the cost of making the application less "user friendly". applications you spend a lot of time using are worth an investment in learning how to use them. what creates friction in an application you know reasonably well is when common tasks are fiddly. for instance, while menus are often good for casual use and lower the initial threshold for absolute beginners, depending heavily on menu navigation becomes too fiddly if you are performing a certain task 2-3 times per minute. it is not _user_ friendly. Emacs is rather "user friendly", but not very "beginner friendly". when I was first confronted with it, the sort of text editors I was used to were Wordstar and derivatives of it. I was rather annoyed that it didn't do what I expected, so I just used a different editor. a few years later I bemoaned the fact that Emacs was so hard to use during a conversation with a friend. he asked me if I had actually made an effort to learn Emacs, which of course I hadn't. so I figured I might as well give it a shot. following the tutorial that comes with Emacs (and which is referred to in the startup message) I spent a couple of hours one afternoon learning the basics. already the next day I started using Emacs for programming. the week after I had progressed to using it as my newsreader (which I still do to this day) and eventually I started reading my email in Emacs. perhaps two months after I had sat down to learn Emacs I wrote my first Emacs extensions in Emacs Lisp. mostly simple stuff to make common programming tasks easier. I found Emacs to be user friendly, but in a different sense than the, IMHO faulty definition, "beginner friendly". Emacs let me, as a user, do more with less effort and provides a lot less friction than many other developer tools I've used. at work I use it extensively, and we have lots of neat extensions that really save a lot of time. -Bj?rn From bj_666 at gmx.net Fri Jun 8 11:39:32 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Fri, 08 Jun 2007 17:39:32 +0200 Subject: Case-Insensitive Sorting of Multi-Dimensional Lists References: <020e01c7a94c$a7970750$0f01a8c0@desktop9> <1181316575.800182.167640@m36g2000hse.googlegroups.com> Message-ID: In <1181316575.800182.167640 at m36g2000hse.googlegroups.com>, mosscliffe wrote: > I have tried the following, for a one dimensional list and it works, > but I can not get my head around this lambda. How would this be > written, without the lamda ? Well ``lambda``\s are just anonymous functions so you can write it with a named function of course. > mylist = ['Fred','bill','PAUL','albert'] > > mylist.sort(key=lambda el: el.lower()) So this becomes: def keyfunc(el): return el.lower() mylist.sort(key=keyfunc) Ciao, Marc 'BlackJack' Rintsch From pete.forman at westerngeco.com Wed Jun 20 12:31:29 2007 From: pete.forman at westerngeco.com (Pete Forman) Date: Wed, 20 Jun 2007 17:31:29 +0100 Subject: SimplePrograms challenge References: Message-ID: Steve Howell writes: > 3) The median example raises the question of what > would happen with an empty list. I don't think it's > important to cover that case in the simple example > (it's really the responsibility of the caller IMO not > to call median with nonsense arguments), but perhaps > there is a simple way to fix this? An empty list raises an IndexError, a non-iterable raises TypeError. This is correct behavior IMHO, there is nothing to fix. Median should return an element (or average of two) from its input and if that is not meaningful returning None or other special value is neither appropriate nor Pythonic. Only the caller knows how to handle such exceptional circumstances. Actually there are some other issues. Should the median of an even number of integers allow halves? Should median insist that its input has an odd number of elements? But it's tough squeezing all that discourse into 13 or 14 lines ;-) BankAccount allows arbitrarily large withdrawals, is that to be fixed too? -- Pete Forman -./\.- Disclaimer: This post is originated WesternGeco -./\.- by myself and does not represent pete.forman at westerngeco.com -./\.- the opinion of Schlumberger or http://petef.port5.com -./\.- WesternGeco. From jstroud at mbi.ucla.edu Mon Jun 11 19:54:10 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Mon, 11 Jun 2007 16:54:10 -0700 Subject: A gotcha: Python pain point? In-Reply-To: <1181604836.292323.154510@z28g2000prd.googlegroups.com> References: <1181604836.292323.154510@z28g2000prd.googlegroups.com> Message-ID: Beorn wrote: > Consider this example: > > >>> def funcs(x): > ... for i in range(5): > ... def g(): return x + i > ... yield g > > I would expect the value of x used in g to be that at the function > declaration time, as if you've pass g a (x=x) argument, especially > after reading this post: http://lua-users.org/wiki/LuaScopingDiscussion > > But: > > >>> [ fun() for fun in list(funcs(1)) ] > [5, 5, 5, 5, 5] > > Whereas: > > >>> [ fun() for fun in funcs(1) ] > [1, 2, 3, 4, 5] > > This came up while discussing Python pain points at > http://intertwingly.net/blog/2007/06/04/Python-Pain-Points#c1181602242 > > I can see how it works now, but I haven't found an easy-to-read > documentation on this. > > I guess it's debatable if perhaps every i used in the loop shouldn't > be a different i. It had me fooled, anyways. > > Rgds, > Bjorn > If this isn't classified as a bug, then someone has some serious explaining to do. Why would it be desirable for a generator to behave differently in two different contexts. Should I import this to see how many principles this behavior violates? James From jackie.BPUG at gmail.com Tue Jun 19 11:19:06 2007 From: jackie.BPUG at gmail.com (Jackie) Date: Tue, 19 Jun 2007 08:19:06 -0700 Subject: Output of HTML parsing In-Reply-To: <4672D3E2.6050908@web.de> References: <1181915875.875312.137080@z28g2000prd.googlegroups.com> <4672D3E2.6050908@web.de> Message-ID: <1182266346.376278.99140@g37g2000prf.googlegroups.com> On 6 15 , 2 01 , Stefan Behnel wrote: > Jackie wrote: > import lxml.etree as et > url = "http://www.economics.utoronto.ca/index.php/index/person/faculty/" > tree = et.parse(url) > > Stefan- - > > - - Thank you. But when I tried to run the above part, the following message showed up: Traceback (most recent call last): File "D:\TS\Python\workspace\eco_department\lxml_ver.py", line 3, in tree = et.parse(url) File "etree.pyx", line 1845, in etree.parse File "parser.pxi", line 928, in etree._parseDocument File "parser.pxi", line 932, in etree._parseDocumentFromURL File "parser.pxi", line 849, in etree._parseDocFromFile File "parser.pxi", line 557, in etree._BaseParser._parseDocFromFile File "parser.pxi", line 631, in etree._handleParseResult File "parser.pxi", line 602, in etree._raiseParseError etree.XMLSyntaxError: line 2845: Premature end of data in tag html line 8 Could you please tell me where went wrong? Thank you Jackie From steve at REMOVE.THIS.cybersource.com.au Tue Jun 12 19:32:38 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Wed, 13 Jun 2007 09:32:38 +1000 Subject: Python's "only one way to do it" philosophy isn't good? References: Message-ID: On Tue, 12 Jun 2007 15:51:07 -0700, Steve Howell wrote: > > --- "Anders J. Munch" <2007 at jmunch.dk> wrote: >> >> Converting tail-recursion to iteration is trivial, >> and perfectly reasonable for >> a human to do by hand. You add an outer "while >> True"-loop, the recursive call >> becomes a tuple assignment, and other code paths end >> with a break out of the >> loop. Completely mechanical and the resulting code >> doesn't even look that bad. >> > > I have to ask the stupid question. If a human can do > this completely mechanically, why can't a machine? They can and do -- some compilers optimize tail-recursion into iteration. Python doesn't, as a deliberate design decision, because to do so would lose traceback information. -- Steven. From google at mrabarnett.plus.com Mon Jun 4 18:46:12 2007 From: google at mrabarnett.plus.com (MRAB) Date: Mon, 04 Jun 2007 15:46:12 -0700 Subject: Python, Dutch, English, Chinese, Japanese, etc. In-Reply-To: References: Message-ID: <1180997172.657169.134660@o5g2000hsb.googlegroups.com> On Jun 4, 6:12 pm, Ross Ridge wrote: > Ross Ridge wrote: > > Translating keywords and standard identifiers into Chinese could make > > learning Python even more difficult. It would probably make things > > easier for new programmers, but I don't know if serious programmers would > > actually prefer programming using Chinese keywords. It would make their > > Python implementations incompatible with the standard implementation, they > > wouldn't be able to use third-party modules and their own code wouldn't > > be portable. If novice Chinese programmers would have to unlearn much > > of they've learned in order to become serious Python programmers are > > you really doing them a favour by teaching them Chinese Python? > > > It would really only work if Chinese Python became it own successful > > dialect of Python, independent of the standard Python implementation. > > Chinese Python programmers would be isolated from other Python > > programmers, each with their own set of third-party modules and little > > code sharing between the two groups. I don't think this would be good > > for Python as whole. > > Wildemar Wildenburger wrote: > > >I don't see the problem here. The bytecode wouldn't change (right?). > > Python code generally isn't shared as bytecode and it's not just keywords > we're talking about here, all standard Python identifiers (eg. "os" and > "sys") would be translated too. > > >So what? One would have to make sure that the interprter understands both > >(or to generalize: all) language versions of python and wham! > > That might work, you'd need both the standard and Chinese versions the > Python standard libraries. I doubt anyone outside of China would want > a distribution that included both, so there would still be barriers to > code sharing between the two communities. > > Interestingly, someone has already created a Chinese version of Python > much like Steve Howell suggested: > > http://www.chinesepython.org/cgi_bin/cgb.cgi/home.html > http://www.chinesepython.org/cgi_bin/cgb.cgi/english/english.html > > Apparently it hasn't been updated in almost four years, so I don't know > much use it gets. > Instead of having many different Pythons for many different languages, how about one for a language like Esperanto? http://en.wikipedia.org/wiki/Esperanto That could be the language for the standard libraries instead of English. From bruno.desthuilliers at gmail.com Mon Jun 4 16:51:20 2007 From: bruno.desthuilliers at gmail.com (bruno.desthuilliers at gmail.com) Date: Mon, 04 Jun 2007 13:51:20 -0700 Subject: *Naming Conventions* In-Reply-To: <1180909218.939713.112010@q69g2000hsb.googlegroups.com> References: <1180909218.939713.112010@q69g2000hsb.googlegroups.com> Message-ID: <1180990280.960271.235550@h2g2000hsg.googlegroups.com> On Jun 4, 12:20 am, Ninereeds wrote: > On Jun 4, 5:03 am, Thorsten Kampe wrote: > > > for validanswer in validanswers: > > if myAnswers.myanswer in myAnswers.validAnswers[validanswer]: > > MyOptions['style'] = validanswer > > First, for small loops with loop variables whose meaning is obvious > from context, the most readable name is usually something like 'i' or > 'j'. 'i' and 'j' are the canonical names for for loops indices in languages that don't support proper iteration over a sequence. Using them for the iteration variable of a Python for loop (which is really a 'foreach' loop) would be at best confusing. (snip) > Based on this, your code might become something like... > > for i in validanswers: > if myAnswers.current in myAnswers.validList [i]: > MyOptions['style'] = i And this is *exactly* what one should not do in Python. If you want a generic name here, use 'item' instead. > It is also often useful to use a convention where a prefix identifies > whether a name is a (p)arameter, (l)ocal variable, or (m)ember You don't have to use any kind of prefix for attributes ('member' is not a Python idiom - remember that in Python, a method is also an attribute...) since the use of 'self' is mandatoy. And you usually don't need to distinguish 'local' from 'parameters', since 1/ parameters names *are* local 2/ pythonic methods and functions tends to be short, so you usually know which names are params. FWIW, prefixing names this way is something I've almost never seen in Python code. > variable - no prefix for functions, usually. For example, a simple > setter method Python has a pretty good support for computed attributes (look for 'property'), so you don't need explicit getters/setters. From rappavu at gmail.com Thu Jun 28 01:45:08 2007 From: rappavu at gmail.com (Rajendran Appavu) Date: Thu, 28 Jun 2007 11:15:08 +0530 Subject: Tkinter pack_forget() and destroy() Message-ID: <3634b0c20706272245r3330b320o9b98517f0c8a3983@mail.gmail.com> When I am done with a widget that is packed in a Frame, is it safe to call destroy() method on the widget after calling its pack_forget() or grid_forget() method? -- Thanks, Rajendran. From bignose+hates-spam at benfinney.id.au Thu Jun 21 19:59:32 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 22 Jun 2007 09:59:32 +1000 Subject: Changing the names of python keywords and functions References: <1182452862.872909.206780@u2g2000hsc.googlegroups.com> <467ad90c$0$22151$9b622d9e@news.freenet.de> Message-ID: <87abusx3iz.fsf@benfinney.id.au> "Martin v. L?wis" writes: > (unattributed author) wrote: > > "<> OS"- (THIS IS MY IMAGINARY EXAMPLE OF KEYWORD), > > my program must write this code in some user file, but my > > program must read this command like: "import os".How > > can I do something like that?? > > The keywords are listed in Grammar/Grammar. You need to edit > this file, then recompile. To clarify, are you suggesting changing the source code of the Python implementation and recompiling it? If the keywords are changed in the Python executable, won't that break the import of any Python module written for the standard keywords -- such as many of those in the standard library? My understanding of the original poster's requirement was that the keywords should be additional to, not replacement for, the existing Python keywords. -- \ "The way to build large Python applications is to componentize | `\ and loosely-couple the hell out of everything." -- Aahz | _o__) | Ben Finney From bignose+hates-spam at benfinney.id.au Tue Jun 19 20:43:17 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 20 Jun 2007 10:43:17 +1000 Subject: Reference current module? References: <4678201b$0$16340$88260bb3@free.teranews.com> Message-ID: <871wg7zc9m.fsf@benfinney.id.au> Tobiah writes: > Can I do: > > getattr(current_module, 'foo') > > where 'current_module' is a handle the the one > that the code is in? Just like The python-list archives are your friend. Google is able to search within a site hierarchy by using search terms like the following: site:mail.python.org/pipermail/python-list/ current module reference Searching there, I immediately find this brief thread: -- \ "I hope if dogs ever take over the world, and they chose a | `\ king, they don't just go by size, because I bet there are some | _o__) Chihuahuas with some good ideas." -- Jack Handey | Ben Finney From pauland80 at gmail.com Wed Jun 6 06:24:02 2007 From: pauland80 at gmail.com (pauland80 at gmail.com) Date: Wed, 06 Jun 2007 03:24:02 -0700 Subject: [pyserial - winXP] Serial port stop receiving data after a few hours, raise no error Message-ID: <1181125442.737934.280150@q75g2000hsh.googlegroups.com> Hello, My soft passively listen to a device sending +- 300 bytes of data each second. After several hours of work, the soft abruptly stops receiving data without any error, (while the device sends properly, of course) and I need to restart it (the python soft) to "reactivate" the ports. I read that when the serial port encounters an error (frame error or so, I imagine?) it stop receiving data until the library function "getCommError()" is called. Am I on the good track? Can I call this function from my pyserial code? Why pyserial does'nt raise a serial.SerialException in this case? Notes: --------- I'm not working with plain serial ports, I use serial over USB (FTDI or so) and serial over Ethernet (moxa.com). I'm in 115k 8N1 and I use 4 ports simultaneously I use python 2.4 with pyserial 2.2 on Windows XP. TIA, Paul Andr? From bpowah at gmail.com Thu Jun 14 23:20:33 2007 From: bpowah at gmail.com (bpowah at gmail.com) Date: Fri, 15 Jun 2007 03:20:33 -0000 Subject: inverting a dictionary of lists Message-ID: <1181877633.471386.196380@i38g2000prf.googlegroups.com> I searched for an hour and don't see a solution to this (i assume somewhat common) problem. I have a very large dictionary of lists: d = {a:[1,2], b:[2,3], c:[3]} and i want to reverse the associativity of the integers thusly: inverse(d) makes {1:[a], 2:[a,b], 3:[b,c]} my solution expands the original dict into two lists of keys and list elements: list1: [a,a,b,b,c] list2: [1,2,2,3,3] then recombines them with the reverse operation. but this takes too much time and a lot of memory. I wonder if anyone can point me to a more efficient solution? From kyosohma at gmail.com Tue Jun 19 16:52:51 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Tue, 19 Jun 2007 13:52:51 -0700 Subject: Controlling Firefox with Python Message-ID: <1182286371.974090.80760@q75g2000hsh.googlegroups.com> Hi, I would like to be able to control Firefox through Python. I see there's pyWinAuto, which might work if they had good documentation. I've also messed with win32 modules, but I don't think Firefox will work with those too nicely since it isn't a COM-based program. I've also found some Python Firefox XUL scripting information that is at least 2 years old and also not documented well. I really need to be able to cycle through the tabs that are open in a current Firefox session and search for a specifically labeled tab. Any ideas on how to do this would be appreciated. I am using Windows XP with Python 2.4. Thanks! Mike From mauriceling at acm.org Tue Jun 5 07:26:31 2007 From: mauriceling at acm.org (Maurice LING) Date: Tue, 05 Jun 2007 11:26:31 GMT Subject: Who uses Python? In-Reply-To: <1181036147.620798.268520@p47g2000hsd.googlegroups.com> References: <1180985830.288414.208850@q69g2000hsb.googlegroups.com> <1181036147.620798.268520@p47g2000hsd.googlegroups.com> Message-ID: <46654863.3040800@acm.org> montyphyton at gmail.com wrote: > i use it for text mining, processing large text corpora for scientific > purposes. i'm also working on some neat data mining tools written in > python (called orange, in case someone's interested) > Hi, I am very interested with your use of Python. I am into text mining as well. Perhaps we can communicate more on this... I am also interested in your data mining tools, orange... Care to give more details. Thanks in advance Maurice From openopt at ukr.net Fri Jun 22 12:56:24 2007 From: openopt at ukr.net (dmitrey) Date: Fri, 22 Jun 2007 09:56:24 -0700 Subject: howto run a function w/o text output? Message-ID: <1182531384.017220.218070@w5g2000hsg.googlegroups.com> hi all, I have a y = some_func(args) statement, and the some_func() produces lots of text output. Can I somehow to suppress the one? Thx in advance, D. From mccredie at gmail.com Mon Jun 4 13:17:27 2007 From: mccredie at gmail.com (Matimus) Date: Mon, 04 Jun 2007 17:17:27 -0000 Subject: How do you htmlentities in Python In-Reply-To: References: Message-ID: <1180977447.745432.109040@q19g2000prn.googlegroups.com> On Jun 4, 6:31 am, "js " wrote: > Hi list. > > If I'm not mistaken, in python, there's no standard library to convert > html entities, like & or > into their applicable characters. > > htmlentitydefs provides maps that helps this conversion, > but it's not a function so you have to write your own function > make use of htmlentitydefs, probably using regex or something. > > To me this seemed odd because python is known as > 'Batteries Included' language. > > So my questions are > 1. Why doesn't python have/need entity encoding/decoding? > 2. Is there any idiom to do entity encode/decode in python? > > Thank you in advance. I think this is the standard idiom: >>> import xml.sax.saxutils as saxutils >>> saxutils.escape("&") '&' >>> saxutils.unescape(">") '>' >>> saxutils.unescape("A bunch of text with entities: & > <") 'A bunch of text with entities: & > <' Notice there is an optional parameter (a dict) that can be used to define additional entities as well. Matt From adelagon at gmail.com Mon Jun 18 23:20:02 2007 From: adelagon at gmail.com (Alvin Delagon) Date: Tue, 19 Jun 2007 11:20:02 +0800 Subject: sizeof() in python Message-ID: <7a01f6c00706182020m1c6c58eel334bfcc22ec5566f@mail.gmail.com> Quick question: Is there a way to know the size of data in python? Like a sizeof feature in C? I need this because I have to make a python application that will send packets at 1-2 kilobytes/sec via UDP. Thank you in advance guys. -------------- next part -------------- An HTML attachment was scrubbed... URL: From john at datavoiceint.com Thu Jun 14 12:30:05 2007 From: john at datavoiceint.com (HMS Surprise) Date: Thu, 14 Jun 2007 09:30:05 -0700 Subject: Moving items from list to list Message-ID: <1181838605.080038.162390@x35g2000prf.googlegroups.com> Just wondered if there was some python idiom for moving a few items from one list to another. I often need to delete 2 or 3 items from one list and put them in another. Delete doesn't seem to have a return value. I don't care which items I get so now I just use a couple of pops or a for loop for more than two. Thanks jh From thomas at jollans.com Thu Jun 28 08:11:28 2007 From: thomas at jollans.com (Thomas Jollans) Date: Thu, 28 Jun 2007 14:11:28 +0200 Subject: Evolution of a pythonistas! In-Reply-To: <1183031173.173821.104990@e16g2000pri.googlegroups.com> References: <1183031173.173821.104990@e16g2000pri.googlegroups.com> Message-ID: swordofrue wrote: > Hello everyone, > > I just started reading the python documentation and then I got to > thinking. How does a pythonistas evolve? What kind of natural > evolution does a pythonistas endure? The reason why I wonder is > simply because I have no idea of where I should be going. What kind of > goals should I set? Any stories related to your own evolution as a > python programming would most likely help give me some direction in > this vast world of python. two words: get coding what you need is an idea for something to write, and a web browser with access to docs.python.org ;-) also, the singular is "pythonista", a synonym is "pythoneer" (I prefer the latter...) The "get coding" principle applies particularly well to python - have a look at ESR's "Why Python". http://www.python.org/about/success/esr/ -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 260 bytes Desc: OpenPGP digital signature URL: From ross at heth.eclipse.co.uk Sat Jun 30 10:13:58 2007 From: ross at heth.eclipse.co.uk (Ross Hetherington) Date: Sat, 30 Jun 2007 15:13:58 +0100 Subject: linecache and comparison with input Message-ID: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA512 Say I've got a file called 'testfile' that contains the following three lines: foo bar baz And a script that goes like this: #!/usr/bin/env python import random import sys import linecache rnd = random.randint(1,3) line = linecache.getline('testfile', rnd) print line gss = raw_input('Enter line: ',) if gss == line: print 'yes' sys.exit() else: print 'no' Even if the right word is entered, the script always prints `no'. Can anyone explain why this happens? -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.7 (GNU/Linux) Comment: Using GnuPG with Fedora - http://enigmail.mozdev.org iD8DBQFGhmUm0HlvQApfM3gRCl23AJ45cv7A0KVi2h8/cWmcCrg4X8HZOACfT6V8 IpXAzpD0jKnFFDEJEmOFvc4= =UA5b -----END PGP SIGNATURE----- From jdcrane7 at gmail.com Fri Jun 15 21:35:21 2007 From: jdcrane7 at gmail.com (Jack Crane) Date: Fri, 15 Jun 2007 18:35:21 -0700 Subject: Want to learn Python References: <1181907696.878873.214760@i13g2000prf.googlegroups.com> Message-ID: Amol wrote in news:1181907696.878873.214760 @i13g2000prf.googlegroups.com: > Hi, I want to learn Python in less than a month which resources should > I use. I prefer to read books . Please give me a list of *recognized* > resources. Thank You all > http://www.pythonware.com/daily/4368043588838810608/ Jack Crane From doug at alum.mit.edu Fri Jun 29 12:45:34 2007 From: doug at alum.mit.edu (Douglas Alan) Date: Fri, 29 Jun 2007 12:45:34 -0400 Subject: Python's "only one way to do it" philosophy isn't good? References: <7x3b0nmkk6.fsf@ruckus.brouhaha.com> <7xejjzmk7u.fsf@ruckus.brouhaha.com> <7xy7i7xjl5.fsf@ruckus.brouhaha.com> <1182872972.417776.78650@o11g2000prd.googlegroups.com> <7xtzsuy7fe.fsf@ruckus.brouhaha.com> <1182955743.076746.114790@i38g2000prf.googlegroups.com> <877ipn9gff.fsf@mulj.homelinux.net> <87fy4akcp7.fsf@mulj.homelinux.net> Message-ID: Hrvoje Niksic writes: >> Generators aren't slower than hand-coded iterators in *Python*, but >> that's because Python is a slow language. > But then it should be slow for both generators and iterators. Python *is* slow for both generators and iterators. It's slow for *everything*, except for cases when you can have most of the work done within C-coded functions or operations that perform a lot of work within a single call. (Or, of course, cases where you are i/o limited, or whatever.) >> *Perhaps* there would be some opportunities for more optimization if >> they had used a less general mechanism.) > Or if the generators were built into the language and directly > supported by the compiler. In some cases implementing a feature is > *not* a simple case of writing a macro, even in Lisp. Generators may > well be one such case. You can't implement generators in Lisp (with or without macros) without support for generators within the Lisp implementation. This support was provided as "stack groups" on Lisp Machines and as continuations in Scheme. Both stack groups and continuations are slow. I strongly suspect that if they had provided direct support for generators, rather than indirectly via stack groups and continuations, that that support would have been slow as well. |>oug From carsten at uniqsys.com Wed Jun 13 14:34:59 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Wed, 13 Jun 2007 14:34:59 -0400 Subject: Python's "only one way to do it" philosophy isn't good? In-Reply-To: References: <1181368143.874341.273140@r19g2000prf.googlegroups.com> <7xy7irxjom.fsf@ruckus.brouhaha.com> <466f0c2c$0$4157$ba624c82@nntp02.dk.telia.net> <46702229$0$4158$ba624c82@nntp02.dk.telia.net> Message-ID: <1181759699.3374.19.camel@dot.uniqsys.com> On Wed, 2007-06-13 at 18:22 +0000, Neil Cerutti wrote: > On 2007-06-13, Anders J. Munch <2007 at jmunch.dk> wrote: > > General tail-call optimisation is of course completely > > out-of-bounds for Python, because it ruins tracebacks. Unlike > > tail recursion, which could use recursion counters. > > Is it really ruined? To use a similar example: > > def foo(x): > bar(x+1) > > def bar(x): > if x > 10: > raise ValueError > else: > foo(x+2) > > Today, when I call foo(4), I get something like: > > C:\WINNT\system32\cmd.exe /c python temp.py > Traceback (most recent call last): > File "temp.py", line 529, in > foo(4) > File "temp.py", line 521, in foo > bar(x+1) > File "temp.py", line 527, in bar > foo(x+2) > File "temp.py", line 521, in foo > bar(x+1) > File "temp.py", line 527, in bar > foo(x+2) > File "temp.py", line 521, in foo > bar(x+1) > File "temp.py", line 525, in bar > raise ValueError > ValueError > shell returned 1 > > With tail-call optimization you'd get something like: > > C:\WINNT\system32\cmd.exe /c python temp.py > Traceback (most recent call last): > File "temp.py", line 529, in > foo(4) > File "temp.py", line 525, in bar > raise ValueError > ValueError > shell returned 1 > > What makes the latter harder to work with? The fact that you don't see how many call levels down your algorithm got before throwing an exception. This may be an important clue in debugging a recursive algorithm. -- Carsten Haese http://informixdb.sourceforge.net From nagle at animats.com Thu Jun 28 16:09:19 2007 From: nagle at animats.com (John Nagle) Date: Thu, 28 Jun 2007 13:09:19 -0700 Subject: Python's "only one way to do it" philosophy isn't good? In-Reply-To: <1183044721.683930.131920@x35g2000prf.googlegroups.com> References: <7xir9cbm0g.fsf@ruckus.brouhaha.com> <7xejjzmk7u.fsf@ruckus.brouhaha.com> <7xy7i7xjl5.fsf@ruckus.brouhaha.com> <1183044721.683930.131920@x35g2000prf.googlegroups.com> Message-ID: Andy Freeman wrote: > On Jun 27, 11:41 pm, John Nagle wrote: > While I agree that weak pointers are good and can not be an > afterthought, I've written code where "back" changed dynamically, and > I'm pretty sure that Nagle has as well. That sort of thing tends to show up in GUI libraries, especially ones that have event ordering issues. It's a tough area. > Many programs with circular lists have an outside pointer to the > current element, but the current element changes. All of the links > implementing the list have to be strong enough to keep all of the list > alive. > Yes, one can implement a circular list as a vector with a current > index, but that has space and/or time consequences. We used to see things like that back in the early 1980s, but today, worrying about the space overhead associated with keeping separate track of ownership and position in a circular buffer chain isn't a big deal. I last saw that in a FireWire driver, and even there, it wasn't really necessary. John Nagle From fred at adventistcare.org Fri Jun 1 13:16:03 2007 From: fred at adventistcare.org (Sells, Fred) Date: Fri, 1 Jun 2007 13:16:03 -0400 Subject: MySQLdb insert fails on one table Message-ID: thank you! that was it. I created the table using a create table (select from.... which must have defaulted to InnoDb, now I just create it in a script. > -----Original Message----- > From: Carsten Haese [mailto:carsten at uniqsys.com] > Sent: Friday, June 01, 2007 8:56 AM > To: Sells, Fred > Cc: python-list at python.org > Subject: Re: MySQLdb insert fails on one table > > > On Fri, 2007-06-01 at 11:48 -0400, Sells, Fred wrote: > > INSERT INTO valid_individuals (fname,lname,alias,email) > VALUES (%s,%s,%s,%s) > > [['xxxx', 'yyyy', 'zzzzz', 'aaaaaa']] > > > > this function works fine for several other tables, but on > this one I get no > > errors and there is nothing in the table. If I run the > equivalent insert on > > the command line, it's just fine. > > This usually indicates that the table is transaction-aware > (e.g. storage > mechanism InnoDB versus MyISAM) and you're not committing your > transaction, so the transaction gets rolled back when your > connection is > closed. > > HTH, > > -- > Carsten Haese > http://informixdb.sourceforge.net > From ndbecker2 at gmail.com Sat Jun 16 16:16:10 2007 From: ndbecker2 at gmail.com (Neal Becker) Date: Sat, 16 Jun 2007 16:16:10 -0400 Subject: Is there a way to hook into module destruction? Message-ID: Code at global scope in a module is run at module construction (init). Is it possible to hook into module destruction (unloading)? From mensanator at aol.com Thu Jun 14 18:02:35 2007 From: mensanator at aol.com (mensanator at aol.com) Date: Thu, 14 Jun 2007 15:02:35 -0700 Subject: Efficient way of generating original alphabetic strings like unix file "split" In-Reply-To: <1181857180.456039.252940@q19g2000prn.googlegroups.com> References: <1181846461.238047.84140@j4g2000prf.googlegroups.com> <87d4zyqoy5.fsf@merkury.smsnet.pl> <1181857180.456039.252940@q19g2000prn.googlegroups.com> Message-ID: <1181858555.994606.56650@i13g2000prf.googlegroups.com> On Jun 14, 4:39 pm, py_genetic wrote: > > You didn't try hard enough. :) > > >http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/190465 > > > -- > > HTH, > > Rob > > Thanks Rob, "permutation" was the keyword I shcould have used! See my other post to see if that is indeed what you mean. From deets at nospam.web.de Fri Jun 8 08:30:15 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 08 Jun 2007 14:30:15 +0200 Subject: how to do reading of binary files? In-Reply-To: <1181304990.863669.94020@m36g2000hse.googlegroups.com> References: <1181304192.406529.135190@n4g2000hsb.googlegroups.com> <5csv4gF30to8lU1@mid.uni-berlin.de> <1181304990.863669.94020@m36g2000hse.googlegroups.com> Message-ID: <5ct0evF31n730U1@mid.uni-berlin.de> jvdb schrieb: > On 8 jun, 14:07, "Diez B. Roggisch" wrote: >> jvdb schrieb: > ...... >> What has the searching to do with the reading? 10MB easily fit into the >> main memory of a decent PC, so just do >> >> contents = open("file").read() # yes I know I should close the file... >> >> print contents.find('\x0c') >> >> Diez > > True. But there is another issue attached to the one i wrote. > When i know how much this occurs, i know the amount of pages in the > file. After that i would like to be able to extract a given amount of > data: > file x contains 20 <0C>. then for example i would like to extract from > instance 5 to instance 12 from the file. > The reason why i want to do this: The 0C stands for a pagebreak in PCL > language. This way i would be absle to extract a certain amount of > pages from the file. And? Finding the respective indices by using last_needle_position = 0 positions = [] while last_needle_position != -1: last_needle_position = contents.find(needle, last_needle_position+1) if last_needle_position != -1: positions.append(last_needle_position) will find all the pagepbreaks. then just slice contents appropriatly. Did you read the python tutorial? diez From george.sakkis at gmail.com Wed Jun 13 13:34:15 2007 From: george.sakkis at gmail.com (George Sakkis) Date: Wed, 13 Jun 2007 17:34:15 -0000 Subject: Windows build of PostgreSQL library for 2.5 In-Reply-To: <1181753874.015973.193030@g37g2000prf.googlegroups.com> References: <1180534505.421166.83700@q66g2000hsg.googlegroups.com> <1180536164.370773.183140@q69g2000hsb.googlegroups.com> <1180538458.993024.173510@g4g2000hsf.googlegroups.com> <1181753874.015973.193030@g37g2000prf.googlegroups.com> Message-ID: <1181756055.087005.269850@i38g2000prf.googlegroups.com> On Jun 13, 12:57 pm, Ben Sizer wrote: > On 30 May, 16:20, Ben Sizer wrote: > > > On 30 May, 15:42, Frank Millman wrote: > > > > On May 30, 4:15 pm,BenSizer wrote: > > > > > I've been looking for a Windows version of a library to interface to > > > > PostgreSQL, but can only find ones compiled under Python version 2.4. > > > > Is there a 2.5 build out there? > > > > Is this what you are looking for? > > > >http://stickpeople.com/projects/python/win-psycopg/ > > > It may well be, thanks. > > On second thoughts, is there one anywhere without an extra multi- > megabyte dependency? This seems to rely on the eGenix 'mx' library. > > -- > Ben Sizer IIRC version 2 (psycopg2) doesn't depend on mx: http://www.stickpeople.com/projects/python/win-psycopg/psycopg2-2.0.5.1.win32-py2.5-pg8.2.0-release.exe George From emin.shopper at gmail.com Fri Jun 1 11:30:54 2007 From: emin.shopper at gmail.com (Emin.shopper Martinian.shopper) Date: Fri, 1 Jun 2007 11:30:54 -0400 Subject: What is equivalent of *this = that in python? Message-ID: <32e43bb70706010830t38e69cb1t732e5dbdaff6cd1b@mail.gmail.com> Dear Experts, How do I reassign self to another object? For example, I want something like class foo: def Update(self,other): # make this object the same as other or make this object a copy of other self = other # This won't work. What I really want is *this = other in C++ terminology. Thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: From martin at v.loewis.de Sat Jun 23 03:14:39 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sat, 23 Jun 2007 09:14:39 +0200 Subject: urllib interpretation of URL with ".." In-Reply-To: References: Message-ID: <467cc85f$0$3039$9b622d9e@news.freenet.de> John Nagle schrieb: > Here's a URL, found in a link, which gives us trouble > when we try to follow the link: > > http://sportsbra.co.uk/../acatalog/shop.html > > Browsers immediately turn this into > > http://sportsbra.co.uk/acatalog/shop.html > > and go from there, but urllib tries to open it explicitly, which > results in an HTTP error 400. > > Is "urllib" wrong? I can't see how. HTTP 1.1 says that the parameter to the GET request should be an abs_path; RFC 2396 says that /../acatalog/shop.html is indeed an abs_path, as .. is a valid segment. That RFC also has a section on relative identifiers and normalization; it defines what .. means *in a relative path*. Section 4 is explicit about .. in absolute URIs: # The syntax for relative URI is a shortened form of that for absolute # URI, where some prefix of the URI is missing and certain path # components ("." and "..") have a special meaning when, and only when, # interpreting a relative path. Notice the "and only when": the browsers who modify above URL before sending it seem to be in clear violation of RFC 2396. Regards, Martin From warren at muse.com Fri Jun 1 13:47:22 2007 From: warren at muse.com (Warren Stringer) Date: Fri, 1 Jun 2007 10:47:22 -0700 Subject: c[:]() In-Reply-To: <54c0a1810706010850u3522f2f2xde90495cf46af727@mail.gmail.com> References: <1180504190.055427.173610@h2g2000hsg.googlegroups.com><1180504773.374529.161740@q66g2000hsg.googlegroups.com><002801c7a2eb$288a8750$240110ac@Muse> <54c0a1810706010850u3522f2f2xde90495cf46af727@mail.gmail.com> Message-ID: <006301c7a474$e861beb0$240110ac@Muse> Thanks, Dakz for taking the time to reply: > This discussion has gone in more circles than Earth has gone 'round > the Sun, but it seems you should consider the following: Yes, I've been feeling a bit dizzy > 1) Sequences and functions serve fundamentally different purposes in > Python. One is for containing objects, the other is for executing an > action. (And yes, I'm aware that these concepts can differ in other > contexts. But we're talking about Python.) I guess I've been arguing for fewer semantics, not more > 2) It seems--at least to me--a bit dubious to change an entire general > purpose programming language to suit a very limited--and frankly > strange--use case. Agreed. > 3) You'd probably be better off making a very simple and concise > domain specific language. Hence: http://muse.com/tr3/Tr3%20Overview.pdf I'm going to take Steve Holden's advice and hang out at c.l.py Cheers, \~/ From bruno.42.desthuilliers at wtf.websiteburo.oops.com Thu Jun 28 07:45:34 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Thu, 28 Jun 2007 13:45:34 +0200 Subject: problem with hack using multiple inheritance for plugins In-Reply-To: <1183028051.940679.145680@q69g2000hsb.googlegroups.com> References: <1183026288.857294.91620@q69g2000hsb.googlegroups.com> <1183028051.940679.145680@q69g2000hsb.googlegroups.com> Message-ID: <46839f4c$0$22380$426a74cc@news.free.fr> massimo s. a ?crit : >> At this point, it seems too much a deep object-oriented hell to be >> able to dig it myself. Would you help me getting some cue on the >> problem? > > Update. Now I know that: > - every sane Python class should return after > type(self) Certainly not, unless you're using a pretty old Python version. 'instance' type means old-style classes - the legacy Python object model, replaced some years ago with a *much* better one ('new-style' classes). IIRC, this (now dying) legacy object model should disappear with Py3K. > - when disabling the multiple-inheritance-hack, the situation comes > back to normal I may be wrong here - I don't use old-style classes, and I avoid multiple inheritance whenever I can - but I think this may has to do with mixing old-style and new-style classes. > What happens that makes the wxFrame class different from the cmd.Cmd > class? wxFrame is obviously a new-style class. wrt/ this snippet: for plugin_name in self.config['plugins']: try: plugin=__import__(plugin_name) try: print type(self) eval('plugin.'+plugin_name+'Commands._plug_init(self)') except AttributeError: pass except ImportError: pass You may want to try this instead: for plugin_name in self.config['plugins']: try: plugin=__import__(plugin_name) except ImportError: # eventually do something like logging the error ? continue try: cmdplug = getattr(plugin, plugin_name+'Commands') cmdplug._plug_init(self) except AttributeError: # eventually do something like logging the error ? continue From bruno.42.desthuilliers at wtf.websiteburo.oops.com Thu Jun 14 02:51:03 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Thu, 14 Jun 2007 08:51:03 +0200 Subject: Method much slower than function? In-Reply-To: <%Q0ci.35541$G23.26580@newsreading01.news.tds.net> References: <1181781612.939800.238890@q19g2000prn.googlegroups.com> <%Q0ci.35541$G23.26580@newsreading01.news.tds.net> Message-ID: <4670e551$0$20040$426a74cc@news.free.fr> Neil Cerutti a ?crit : (snip) > class bar: > def readgenome(self, filehandle): > self.s = ''.join(line.strip() for line in filehandle) => self.s = ''.join(line.strip() for line in filehandle if not '>' in line) From martin at see.sig.for.address Sun Jun 24 08:30:20 2007 From: martin at see.sig.for.address (Martin Gregorie) Date: Sun, 24 Jun 2007 13:30:20 +0100 Subject: The Modernization of Emacs: terminology buffer and keybinding In-Reply-To: <1182661040.286559.150880@q75g2000hsh.googlegroups.com> References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182272495.990807.99110@a26g2000pre.googlegroups.com> <87tzt3ihev.fsf@kobe.laptop> <1182370216.961241.6960@n60g2000hse.googlegroups.com> <85zm2ufjpb.fsf@lola.goethe.zz> <1182372592.803332.288260@u2g2000hsc.googlegroups.com> <1182373919.262388.100740@c77g2000hse.googlegroups.com> <85r6o6fhkb.fsf@lola.goethe.zz> <1182375045.626510.188170@m36g2000hse.googlegroups.com> <85myyufgwj.fsf@lola.goethe.zz> <1182375528.985142.293900@q69g2000hsb.googlegroups.com> <1182545268.055596.228700@i38g2000prf.googlegroups.com> <1182661040.286559.150880@q75g2000hsh.googlegroups.com> Message-ID: <0o42l4-t81.ln1@zoogz.gregorie.org> Twisted wrote: > At least Windows 3.1 had most apps have the same keys for the vast > majority of commands, and those were the right keys. Emacs has all the > applications have the vast majority of their commands use the same > WRONG keys. Including whatever you'd use to rebind them. And the help > you'd use to find out what the damn keys are in the first place. ;) > You're mis-remembering this. Apple, first with the Lisa and then with the Mackintosh, had extremely consistent menus, menu shortcuts and other key assignments. It was possible to teach almost anybody to use them in 15 minutes flat. A major reason for the consistency was the Programmer's Toolbox, a piece of ROM that contained all the stuff an application needed to handle keyboard, mouse and menus. It was there and easy to use, so of course all applications programmers used it. Windows 3 and 3.1 were the first usable Windows versions. Windows 1 and 2 were a bad jokes. Win/286 worked but had no applications. Win 3.x worked a lot better. However, it lacked any equivalent of the Programmers Toolbox and as a result the applications were anything but consistent. MS applications were self-similar, but other apps used wildly divergent ideas about menu structures, shortcuts and key assignments. Compare 3.x versions of Word with Wordperfect, or the Borland IDEs and this is obvious. MS finally kicked applications providers into more-or-less consistency but that wasn't before Win 95 appeared and they then spoilt the record by arbitrary and capricious menu changes as each version of MS Office appeared. -- martin@ | Martin Gregorie gregorie. | Essex, UK org | From see_website at mindprod.com.invalid Sun Jun 24 05:13:02 2007 From: see_website at mindprod.com.invalid (Roedy Green) Date: Sun, 24 Jun 2007 09:13:02 GMT Subject: Portable general timestamp format, not 2038-limited References: <1182544384.709759.235300@o11g2000prd.googlegroups.com> Message-ID: <35bs73dkp4p00ihq4q7ibgh3o460pk3nsp@4ax.com> On Fri, 22 Jun 2007 13:33:04 -0700, James Harris wrote, quoted or indirectly quoted someone who said : >1) subsecond resolution - milliseconds or, preferably, more detailed >2) not bounded by Unix timestamp 2038 limit >3) readable in Java >4) writable portably in Perl which seems to mean that 64-bit values >are out >5) readable and writable in Python >6) storable in a free database - Postgresql/MySQL Unix gets in trouble in 2038 only with 32-bit timestamps. Java's 64-bit longs are fine. If you need code to create timestamps, you can modify parts of BigDate to run in Perl or Python. see http://mindprod.com/products1.html#BIGDATE To get more detailed, just use a unix long timestamp multiplied by 1000 to track in microseconds. You can use MS nanosecond timestamps. see http://mindprod.com/products1.html#FILETIMES just store them as longs in the database. The only catch is ad-hoc queries won't work with them. JDBC out the box should be fine. one of : DATE java.sql.Date TIME java.sql.Time TIMESTAMP java.sql.Timestamp BIGINT long will be what you need. -- Roedy Green Canadian Mind Products The Java Glossary http://mindprod.com From markacy at gmail.com Mon Jun 4 09:35:50 2007 From: markacy at gmail.com (markacy) Date: Mon, 04 Jun 2007 13:35:50 -0000 Subject: magic names in python In-Reply-To: <1180939436.862957.127810@p77g2000hsh.googlegroups.com> References: <1180939436.862957.127810@p77g2000hsh.googlegroups.com> Message-ID: <1180964150.671803.24300@m36g2000hse.googlegroups.com> On 4 Cze, 08:43, per9000 wrote: > Hi, > > I recently started working a lot more in python than I have done in > the past. And I discovered something that totally removed the pretty > pink clouds of beautifulness that had surrounded my previous python > experiences: magic names (I felt almost as sad as when I discovered > the strange pink worms that eat you in nethack, not to mention the > mind flayers - I really hate them). > > I guess all programming languages have magic names to some extent > (f.x. classes in the "C-family" have constructors that must have the > same name as the class (foo::foo) instead of foo.__init__). > > I just used a search engine a little on this topic and I found no > comprehensive list of magic names in python. > > So my questions: > * is there a comprehensive list of magic names in python (so far i > know of __init__ and __repr__)? > * are these lists complete or can magic names be added over time (to > the python "core")? > * are magic names the same in different python versions? > > I also tried (selected parts of(?)) the unittest package for use in > Zope and it seemed functions that I created for my test with the magic > prefix "test" were magic, other functions were not. > > So another question emerges: > * is the use of magic names encouraged and/or part of good coding > practice. > > Live long and prosper, > Per > > -- > > Per Erik Strandberg > home:www.pererikstrandberg.se > work:www.incf.org > also:www.spongswedencare.se On "magic" methods and their usage You can read here: http://diveintopython.org/object_oriented_framework/special_class_methods.html By the way - this is a very good book on python. Cheers, Marek From http Sat Jun 16 21:33:49 2007 From: http (Paul Rubin) Date: 16 Jun 2007 18:33:49 -0700 Subject: Python's "only one way to do it" philosophy isn't good? References: <1181368143.874341.273140@r19g2000prf.googlegroups.com> <1hzrsp4.7vjuav1aegg0tN%aleax@mac.com> <1hzsdrr.wxcx771jwicv5N%aleax@mac.com> <1182007539_10897@sp12lax.superfeed.net> <1hzt8l3.1npcm8u1jroax1N%aleax@mac.com> Message-ID: <7x7iq35pqa.fsf@ruckus.brouhaha.com> aleax at mac.com (Alex Martelli) writes: > PL/1 is basically gone, but its legacy of "take what you need and leave > the rest" is unfortunately alive in other languages that are blind to > the enormous advantages of simplicity and uniformity. Intercal? From josiah.carlson at sbcglobal.net Mon Jun 18 20:17:41 2007 From: josiah.carlson at sbcglobal.net (Josiah Carlson) Date: Mon, 18 Jun 2007 17:17:41 -0700 Subject: Python and (n)curses In-Reply-To: <1182211133.956524.160020@g4g2000hsf.googlegroups.com> References: <1182211133.956524.160020@g4g2000hsf.googlegroups.com> Message-ID: pinkfloydhomer at gmail.com wrote: > I need to develop a cross-platform text-mode application. I would like > to do it in Python and I would like to use a mature text-mode library > for the UI stuff. > > The obvious choice, I thought, was ncurses. But as far as I can tell, > it is not available for Python on Windows? > > Is there a workaround? Or are there alternative libraries that might > be used instead of (n)curses? I know I can use (n)curses on *nix and > console on Windows etc., but that is of course suboptimal. This link offers a series of links for console IO... http://mail.python.org/pipermail/python-list/2005-January/303984.html Among them is a link to the 'wcurses' module that has been relocated here: http://adamv.com/dev/python/curses/ It doesn't actually work in the console, but it seems as though you can program towards one API. There is always cygwin + Python + ncurses. - Josiah From cai.haibin at gmail.com Wed Jun 20 10:43:39 2007 From: cai.haibin at gmail.com (james_027) Date: Wed, 20 Jun 2007 07:43:39 -0700 Subject: class attributes & data attributes Message-ID: <1182350619.334867.31520@a26g2000pre.googlegroups.com> hi everyone, I am now in chapter 5 of Dive Into Python and I have some question about it. From what I understand in the book is you define class attributes & data attributes like this in python class Book: total # is a class attribute def __init__(self): self.title # is a data attributes self.author # another data attributes To define class attributes is like defining a function in class, to define a data attributes is defining a variable inside the __init__ method. what makes me confuse is this model from Django from django.db import models class Person(models.Model): first_name = models.CharField(maxlength=30) last_name = models.CharField(maxlength=30) I believe the first_name and last_name are data attributes? but why it is they look like a class attributes as being define. Thanks in advance for explaining james From theller at ctypes.org Fri Jun 22 03:20:42 2007 From: theller at ctypes.org (Thomas Heller) Date: Fri, 22 Jun 2007 09:20:42 +0200 Subject: "assert" annoyance In-Reply-To: <7xmyys368j.fsf_-_@ruckus.brouhaha.com> References: <7xmyys368j.fsf_-_@ruckus.brouhaha.com> Message-ID: Paul Rubin schrieb: > So I have some assert statements in my code to verify the absence of > some "impossible" conditions. They were useful in debugging and of > course I left them in place for "real" runs of the program. Umpteen > hours into a run, an assertion failed, and of course since failure > was "impossible", I didn't catch the exception so the whole program > crashed. I don't know what I'd have done with the exception anyway, > since it would have had to be caught at an outer scope where the > data I cared about was no longer around, or else I'd have had to > predict in advance what I needed to examine and pass that as a > an arg to the assert statement. > > What I really want is for any assertion failure, anywhere in the > program, to trap to the debugger WITHOUT blowing out of the scope > where the failure happened, so I can examine the local frame. That > just seems natural, but I don't see an obvious way to do it. Am I > missing something? I guess I could replace all the assertions with > function calls that launch pdb, but why bother having an assert > statement? http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65287 Thomas From steve at REMOVE.THIS.cybersource.com.au Sun Jun 24 07:29:08 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sun, 24 Jun 2007 21:29:08 +1000 Subject: is this a valid import sequence ? References: <4f97$467c254d$d443bb3a$9522@news.speedlinq.nl> <137qo1egg4v1k04@corp.supernews.com> <1i0694u.1n6evsntoei0wN%aleax@mac.com> <1i06hm3.1ii0h87p707f2N%aleax@mac.com> Message-ID: On Sat, 23 Jun 2007 21:11:42 -0700, Alex Martelli wrote a lot, with lots of YELLING. Wow. What can I say? Given the amount of SHOUTING in your post, and the fact that you feel so strongly about the trivial question of the redundant use of the global statement that you would "fail a student" who did it -- even if they did everything else correctly, efficiently and elegantly -- it seems to me that you are beyond rational discussion on this subject. Perhaps you should consider writing a PEP to make the redundant use of the global statement a compile-time error? Then there would be absolutely no doubt in anyone's mind that it is _wrong_ (and not just unnecessary or redundant) to use the global statement in the circumstances discussed. Then we can move on to removing floats of the form 1.e0, unary-plus on numeric types, and string-slices like s[:]. I'm not sure where you got the idea that I'm "encouraging newbies to overuse globals", when I wrote in an earlier post to this same thread: "However, using global variables is almost always a bad idea. Passing parameters around is really cheap in Python, that's almost always a better solution." If you manage to calm down enough to answer without exaggerating and misrepresenting my views, I would like to hear your opinion of whether the following two functions are equally as wrong: def f1(gizmo): global spam # holds the frommet needed for the gizmo gizmo.get_frommet(spam) def f2(gizmo): # global spam holds the frommet needed for the gizmo gizmo.get_frommet(spam) I'm sure they're both wrong, but I'd like to know if there are degrees of wrongness. -- Steven. From me at privacy.net Mon Jun 4 16:47:17 2007 From: me at privacy.net (Mark Carter) Date: Mon, 04 Jun 2007 21:47:17 +0100 Subject: Who uses Python? In-Reply-To: <1180985830.288414.208850@q69g2000hsb.googlegroups.com> References: <1180985830.288414.208850@q69g2000hsb.googlegroups.com> Message-ID: <46647a59$0$5860$da0feed9@news.zen.co.uk> walterbyrd wrote: > Anything else? Finance? Web-analytics? SEO? Digital art? I played with NodeBox a little while ago: http://nodebox.net/code/index.php/Home "NodeBox is a Mac OS X application that lets you create 2D visuals (static, animated or interactive) using Python programming code and export them as a PDF or a QuickTime movie. NodeBox is free and well-documented." Pretty trippy stuff. From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Wed Jun 6 17:55:04 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Wed, 06 Jun 2007 23:55:04 +0200 Subject: Determinant of Large Matrix References: Message-ID: <5coopoF2vt25kU1@mid.individual.net> James Stroud wrote: > For this matrix, I'm getting this with numpy: > > 2774532095.9999971 > > But I have a feeling I'm exceeding the capacity of floats here. > Does anyone have an idea for how to treat this? Not if you don't state your requirements more precisely. E. g. what precision do you need? > Is it absurd to think I could get a determinant of this matrix? Absolutely not. > Is there a python package that could help me? Help doing what? BTW, scilab says this: -->det(A) ans = 2.7745320960000E+09 -->ans-2774532095.9999971 ans = 2.8610229492188E-06 --> The error is 15 magnitudes below your result -- what do you want more? :) Regards, Bj?rn P.S.: >>> print 2774532095.9999971 2774532096.0 >>> -- BOFH excuse #118: the router thinks its a printer. From DavidRushby at gmail.com Tue Jun 19 10:31:58 2007 From: DavidRushby at gmail.com (David Rushby) Date: Tue, 19 Jun 2007 07:31:58 -0700 Subject: determine 32 or 64 bit architecture with python 2.2 In-Reply-To: <1182256124.727593.93360@z28g2000prd.googlegroups.com> References: <1182251830.835902.78210@n2g2000hse.googlegroups.com> <1182256124.727593.93360@z28g2000prd.googlegroups.com> Message-ID: <1182263518.734695.327620@w5g2000hsg.googlegroups.com> On Jun 19, 4:28 pm, John Machin wrote: > On Jun 19, 9:17 pm, Kai Rosenthal wrote: > > > Hello, > > how can I determine the architecture (32 or 64bit) with python 2.2 on > > Windows or Unix (AIX, Solaris) OS, without the modul platform? > > Thanks for your hints, Kai > > What happens when you fire up a 64-bit Python and type > import sys; sys.maxint > at it? That's not suitable, because of the differences between LP64 and LLP64 (http://en.wikipedia.org/wiki/64-bit#64-bit_data_models ). Try python -c "import struct; print struct.calcsize('P')" instead. That calculates the size of a pointer. From ikojba at gmail.com Mon Jun 25 09:26:12 2007 From: ikojba at gmail.com (AJK) Date: Mon, 25 Jun 2007 15:26:12 +0200 Subject: Capturing and sending keys {Esperanto} Message-ID: Hello there! I've been googleing yet, and suppose it's hopeless to try, but better ask it... I want to write a program which turns Cx to ?, cx to ? et al WHILE TYPING. (i.e. converting Esperanto x-system to real hats, for those who know about this.) Therefore I though will need to capture the last 2 typed characters (from any application), send a double backspace and after that send the correct letters (back to the same application)... However, it seems inpossible to capture those letters, and maybe to send them too... Or am I wrong? Greetings, LaPingvino (project: http://code.google.com/p/iksilo/ - SVN Repository is free viewable, project is GPL) -- ?ar Dio tiel amis la mondon, ke Li donis Sian solenaskitan Filon, por ke ?iu, kiu fidas al li, ne pereu, sed havu eternan vivon. -Johano 3:16, La sankta Biblio- ?oju ?iam, pre?u sen?ese, pri ?io donu dankon. -1 Tesalonikanoj 5:16-18a, La sankta Biblio- From gagsl-py2 at yahoo.com.ar Mon Jun 11 17:10:03 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 11 Jun 2007 18:10:03 -0300 Subject: Accessing global namespace from module References: <1181577768.728377.262720@m36g2000hse.googlegroups.com> <1181583469.562064.29440@p77g2000hsh.googlegroups.com> <1181585938.144294.119790@w5g2000hsg.googlegroups.com> <1181593775.957808.136050@m36g2000hse.googlegroups.com> Message-ID: En Mon, 11 Jun 2007 17:29:35 -0300, reubendb escribi?: > On Jun 11, 3:30 pm, "Gabriel Genellina" > wrote: >> En Mon, 11 Jun 2007 15:18:58 -0300, reubendb >> escribi?: >> >> > The problem is I don't define the functions AddPlot() and DrawPlots(). >> > It's built into the python interpreter of the CLI version of the >> > program I mentioned, and they are defined on the main script. I load >> > the main script using something like "software -cli -s >> > mainscript.py". >> > In the mainscript.py I import myModule, but of course myModule does >> > not have access to the functions defined in the global namespace of >> > mainscript.py. >> >> Don't you have some import statements at the top of mainscript.py that >> are >> responsible for bringing AddPlot and DrawPlots into the current >> namespace? >> Import the same things in your second module. > > No, I *don't* have any import statement mainscript.py. When using this > software's CLI, AddPlot and DrawPlots are available to me > automagically from mainscript.py. Hence my question: How do I make > this available from other module. Is there any way at all ? Yes: create your own module on-the-fly, using the recipe posted earlier by John Krukoff. If there are many functions, try enumerating them all: import sys from types import ModuleType as module plotModule = module('plot') for key,value in globals().items(): if key[:2] != '__': setattr(plotModule, key, value) sys.modules['plot'] = plotModule -- Gabriel Genellina From mcPas.De.Spam at mclaveauPas.De.Spam.com Wed Jun 6 02:02:30 2007 From: mcPas.De.Spam at mclaveauPas.De.Spam.com (Michel Claveau) Date: Wed, 06 Jun 2007 08:02:30 +0200 Subject: who know? Message-ID: Hi! This image show IronPython. But... what is it? Link : http://msdn2.microsoft.com/en-us/vstudio/bb510103.vss_IronPython_large.jpg -- @-salutations Michel Claveau From gagsl-py2 at yahoo.com.ar Fri Jun 29 00:15:05 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 29 Jun 2007 01:15:05 -0300 Subject: Threads Dying? References: <23984.0632690632$1183054560@news.gmane.org> Message-ID: En Thu, 28 Jun 2007 15:12:53 -0300, Robert Rawlins - Think Blue escribi?: > I've got an application that seems to be a little bit unstable and > freezes > quite a bit, and I'm suspecting it's something in one of my threads > that's > causing the problem, when does a thread die? After the run() method finishes, either normally or because an unhandled exception happened. > And how can I be sure that its > dyeing when its mean to be? I'm not sure what you are asking - you can check periodically inside run() for some condition (an Event object, a special object placed on a Queue, even a global variable in the simplest case) and exit when the condition is met. -- Gabriel Genellina From jstroud at mbi.ucla.edu Sat Jun 23 17:45:00 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sat, 23 Jun 2007 14:45:00 -0700 Subject: Python changing keywords name In-Reply-To: <1182630774.701295.50890@k79g2000hse.googlegroups.com> References: <1182630774.701295.50890@k79g2000hse.googlegroups.com> Message-ID: vedrandekovic at v-programs.com wrote: > Hello AGAIN, > > I on working on windows and Python 2.4. Where can I find and CHANGE > python > grammar. ( I just want to change the keywords ) > > PLEASE HELP ME > SOMEBODY!!!!!! > > THANKS!!!!!!!!!!!!!!!!! > 1. Download the source to python 2. Unpack the source 3. Change to the "Grammar" directory 5. Edit the "Grammar" file appropriately 6. Compile python 7. Your interpreter now has new keywords 8. Use at your own risk. For example, I changed a print statent in this file from print_stmt: 'print' ( [ test (',' test)* [','] ] | '>>' test [ (',' test)+ [','] ] ) to print_stmt: 'splodnik' ( [ test (',' test)* [','] ] | '>>' test [ (',' test)+ [','] ] ) And here are the results: Python 2.5 (r25:51908, Jun 23 2007, 14:42:05) [GCC 4.1.1] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> splodnik 'This is a splodnik statement.' This is a splodnik statement. You will also want to change every instance of the word "print" in every .py file to "splodnik" in the pythonsource before building, so that you won't break your standard lib. Also, no one else on the planet will be using this version of python, so you will not be able to use any one else's python code unless you replace keywords in their python source. Now that you know how to do this, please don't ask again. James From kyosohma at gmail.com Tue Jun 19 17:07:10 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Tue, 19 Jun 2007 14:07:10 -0700 Subject: wxpython: Redirect the stdout to a textctrl In-Reply-To: <1182284207.035976.92170@q19g2000prn.googlegroups.com> References: <1182284207.035976.92170@q19g2000prn.googlegroups.com> Message-ID: <1182287230.696722.247930@u2g2000hsc.googlegroups.com> On Jun 19, 3:16 pm, Alejandro wrote: > Hi: > > I want to redirect stdout to a textctrl I have. From what I read in > the wxpython documentation, I can use the wxLogTextCtrl class to do > this. I am doing the following: > > class MyGui(gui.MyFrame): #gui.MyFrame generated by wxGlade > def __init__(self, *args, **kwds): > gui.MyFrame.__init__(self, *args, **kwds) > # ... code removed ... > wx.Log_SetActiveTarget(wx.LogTextCtrl(self.text_ctrl_2)) > print 'foo' #to test the redirection > > if __name__ == "__main__": > app = wx.App(redirect=wx.LogTextCtrl) > wx.InitAllImageHandlers() > gui = MyGui(None, -1, "") > app.SetTopWindow(gui) > gui.Show() > app.MainLoop() > > However, the output instead of going to my textctrl, goes to a new > window named "xwPython: stdout/stderr". > > What am I missing? Give this a try: class XPinst(wx.App): def __init__(self, redirect=False, filename=None): wx.App.__init__(self, redirect, filename) def OnInit(self): self.frame = wx.Frame(None, -1, title='Redirect Test', size=(620,450), style=wx.STAY_ON_TOP| wx.DEFAULT_FRAME_STYLE) panel = wx.Panel(self.frame, -1) self.log = wx.TextCtrl(panel, -1, size=(500,400), style = wx.TE_MULTILINE|wx.TE_READONLY| wx.HSCROLL) redir=RedirectText(self.log) sys.stdout=redir print 'test' self.frame.Show() return True class RedirectText: def __init__(self,aWxTextCtrl): self.out=aWxTextCtrl def write(self,string): self.out.WriteText(string) Mike From fumanchu at amor.org Sat Jun 16 11:33:26 2007 From: fumanchu at amor.org (fumanchu) Date: Sat, 16 Jun 2007 08:33:26 -0700 Subject: Database Access using pyodbc. I've a problem In-Reply-To: <1181997323.384882.149020@i13g2000prf.googlegroups.com> References: <1181997323.384882.149020@i13g2000prf.googlegroups.com> Message-ID: <1182008006.091353.194490@e9g2000prf.googlegroups.com> On Jun 16, 5:35 am, Rajendran wrote: > Hi all, > > I've installed pyodbc module to access my database (MS Access). I've > setup a User level DSN to the database.mdb file. When I run my python > code in the command prompt it is retrieving the database contents and > displaying it (HTML output). > But when I run that python from webserver (http://localhost/cgi-bin/ > database.py) there comes an entry in the error log of Apache server > that says: > > [Sat Jun 16 17:55:57 2007] [error] [client 127.0.0.1] Premature end of > script headers: database.py > [Sat Jun 16 17:55:57 2007] [error] [client 127.0.0.1] Traceback (most > recent call last):\r > [Sat Jun 16 17:55:57 2007] [error] [client 127.0.0.1] File "C:/ > Apache Software Foundation/Apache2.2/cgi-bin/database.py", line 10, in > \r > [Sat Jun 16 17:55:57 2007] [error] [client 127.0.0.1] cnxn = > pyodbc.connect('DSN=Emp')\r > [Sat Jun 16 17:55:57 2007] [error] [client 127.0.0.1] pyodbc.Error: > ('HY000', "[HY000] [Microsoft][ODBC Microsoft Access Driver] The > Microsoft Jet database engine cannot open the file '(unknown)'. It is > already opened exclusively by another user, or you need permission to > view its data. (-1032); [HY000] [Microsoft][ODBC Microsoft Access > Driver] The Microsoft Jet database engine cannot open the file > '(unknown)'. It is already opened exclusively by another user, or you > need permission to view its data. (-1032)")\r > > Even though the MS Access file is closed. > > I've no administrator rights and I've installed all these as a normal > windows user. > > I don't have problem when I write a similar kind of code in PHP. What > could be the reason? Is it because I don't have administrator rights? > or something else? > Please help me out. Looks like a permissions problem at first glance. See http://httpd.apache.org/docs/2.2/mod/mpm_common.html#user and http://httpd.apache.org/docs/2.2/mod/mod_suexec.html#suexecusergroup Robert Brewer System Architect Amor Ministries fumanchu at amor.org From paddy3118 at googlemail.com Mon Jun 11 17:32:23 2007 From: paddy3118 at googlemail.com (Paddy) Date: Mon, 11 Jun 2007 21:32:23 -0000 Subject: Link Dictionary In-Reply-To: <1181596912.645709.263270@q75g2000hsh.googlegroups.com> References: <1181593466.934730.299660@i38g2000prf.googlegroups.com> <1181596764.090231.137820@x35g2000prf.googlegroups.com> <1181596912.645709.263270@q75g2000hsh.googlegroups.com> Message-ID: <1181597543.841494.174920@q69g2000hsb.googlegroups.com> > > dout = [[dict2[i],[dict2[k] for k in j]] > for i,j in data] > print dout > > - Paddy. Working from your original dict1: dout = [[dict2[i], [dict2[k] for k in setvalue]] for i,setvalue in dict1.iteritems()] - Paddy From danaraicute20 at gmail.com Wed Jun 27 16:04:10 2007 From: danaraicute20 at gmail.com (DI...) Date: Wed, 27 Jun 2007 13:04:10 -0700 Subject: =?utf-8?B?4paIIFdhdGNoIEZSRUUgU2F0ZWxsaXRlIFRWIG9uIHlvdXIgUEMhIOKWiA==?= Message-ID: <1182974650.293123.258360@n60g2000hse.googlegroups.com> Why pay over $90.00 a month for Cable or Satellite TV services? Instantly Turn your Computer into a Super TV Get over 3000 STATIONS on your PC or Laptop for FREE!! Watch hundreds of LIVE World Wide Channels on your PC, FREE of charge.... More Details, Just Follow The Link Below: http://tvonpc.50webs.com/ ACT NOW - The price WILL go up. Download it now! From siona at chiark.greenend.org.uk Fri Jun 1 10:07:07 2007 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 01 Jun 2007 15:07:07 +0100 (BST) Subject: c[:]() References: Message-ID: Warren Stringer wrote: >#-------------------------------------- >class do(list): > def __call__(self,*args,**kwargs): > return [f(*args,**kwargs) for f in self] > > >def a(): print 'a called' >def b(): print 'b called' >c = do() >c = [a,b] >do(c[:])() >do(c)() >#-------------------------------------- > >I prefer that last line, because [:] is very expensive to type from a cell >phone. And not because it's completely redundant? >Now, if I could only could do this: > > do(orchestra(conductor)).play() Something along the lines of: def __getattr__(self, name): return do(getattr(x, name) for x in self) ? -- \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 alejandro.weinstein at gmail.com Tue Jun 19 16:16:47 2007 From: alejandro.weinstein at gmail.com (Alejandro) Date: Tue, 19 Jun 2007 20:16:47 -0000 Subject: wxpython: Redirect the stdout to a textctrl Message-ID: <1182284207.035976.92170@q19g2000prn.googlegroups.com> Hi: I want to redirect stdout to a textctrl I have. From what I read in the wxpython documentation, I can use the wxLogTextCtrl class to do this. I am doing the following: class MyGui(gui.MyFrame): #gui.MyFrame generated by wxGlade def __init__(self, *args, **kwds): gui.MyFrame.__init__(self, *args, **kwds) # ... code removed ... wx.Log_SetActiveTarget(wx.LogTextCtrl(self.text_ctrl_2)) print 'foo' #to test the redirection if __name__ == "__main__": app = wx.App(redirect=wx.LogTextCtrl) wx.InitAllImageHandlers() gui = MyGui(None, -1, "") app.SetTopWindow(gui) gui.Show() app.MainLoop() However, the output instead of going to my textctrl, goes to a new window named "xwPython: stdout/stderr". What am I missing? From benedict.verheyen at gmail.com Fri Jun 8 08:36:36 2007 From: benedict.verheyen at gmail.com (Benedict Verheyen) Date: Fri, 08 Jun 2007 14:36:36 +0200 Subject: python-ldap for Python 2.5 on Windows? Message-ID: Hi, i found python-ldap for version Python 2.4. Is there i place i can find a version for 2.5? If not, how can i build it myself for Windows? Thanks, Benedict From carsten at uniqsys.com Fri Jun 15 12:33:16 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Fri, 15 Jun 2007 12:33:16 -0400 Subject: a_list.count(a_callable) ? In-Reply-To: <1181916937.648267.163070@z28g2000prd.googlegroups.com> References: <1181850818.567840.251090@x35g2000prf.googlegroups.com> <1181853479.914070.217270@i13g2000prf.googlegroups.com> <1181855184.511137.100870@z28g2000prd.googlegroups.com> <1181916937.648267.163070@z28g2000prd.googlegroups.com> Message-ID: <1181925196.3387.23.camel@dot.uniqsys.com> On Fri, 2007-06-15 at 14:15 +0000, Ping wrote: > using sum(1 ...) to mean count() isn't very intuitive I find it very intuitive, but then again, my years of studying Math may have skewed my intuition. > I would still prefer an expression like a_list.count(a_callable), > which is short, clean, and easy to understand. Did you see my alternative example on this thread? It allows you to use list.count in almost exactly that way, except that instead of passing the callable directly, you pass an object that defers to your callable in its __eq__ method. HTH, -- Carsten Haese http://informixdb.sourceforge.net From gregpinero at gmail.com Mon Jun 25 01:36:16 2007 From: gregpinero at gmail.com (gregpinero at gmail.com) Date: Mon, 25 Jun 2007 05:36:16 -0000 Subject: Chroot Jail Not Secure for Sandboxing Python? In-Reply-To: <1182748892.916068.146780@p77g2000hsh.googlegroups.com> References: <1182748892.916068.146780@p77g2000hsh.googlegroups.com> Message-ID: <1182749776.521391.39180@g4g2000hsf.googlegroups.com> On Jun 25, 1:21 am, "gregpin... at gmail.com" wrote: > This wiki page suggests using a chroot jail to sandbox Python, but > wouldn't running something like this in your sandboxed Python instance > still break you out of the chroot jail: > > os.execle ('/usr/bin/python','-c','import os; os.execlp("/bin/sh")', > {}) > > or maybe: > > del os.environ['LD_PRELOAD'] > os.execl ('/usr/bin/python','-c','import os; os.execlp("/bin/sh")') > > My ISP suggested these as counter-examples to my request for a chroot > jail. (I couldn't even get Python running in chroot to test this, nor > could I run these commands locally in Python on Ubuntu, though maybe > they opened sh?) > > So is a chroot jail not adequate for sandboxing Python? > > -Greg Edit: Google groups stripped out the URL. It's http://wiki.python.org/moin/How_can_I_run_an_untrusted_Python_script_safely_(i.e._Sandbox) (or the page titled this on the Python wiki if it strips out the url above again) "How can I run an untrusted Python script safely (i.e. Sandbox)" -Greg From jadamson at partners.org Thu Jun 21 11:06:45 2007 From: jadamson at partners.org (Joel J. Adamson) Date: Thu, 21 Jun 2007 11:06:45 -0400 Subject: The Modernization of Emacs: terminology buffer and keybinding References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182272495.990807.99110@a26g2000pre.googlegroups.com> <87tzt3ihev.fsf@kobe.laptop> <1182370216.961241.6960@n60g2000hse.googlegroups.com> <85zm2ufjpb.fsf@lola.goethe.zz> <1182372592.803332.288260@u2g2000hsc.googlegroups.com> <5dtk4tF34jrimU1@mid.dfncis.de> <1182375388.814275.227380@n2g2000hse.googlegroups.com> Message-ID: <87645h73ei.fsf@W0053328.mgh.harvard.edu> Twisted writes: > Yeah, and I abhor the elitist systems that are designed with the > philosophy that anyone who hasn't mastered years of arcane > memorization and training in just that one idiosyncratic system is / > ipso facto/ "stupid and unsophisticated". Most of us 6 and a half > billion people have better uses for our time, such as buckling in and > being promptly productive, once we're out of high school or college, > and fully three and a quarter of us are at least as smart as average, > and so /ipso facto/ *not* "stupid and unsophisticated". > You see, though, the problem is that computers are *not* easy to use. People only say that they've been made easy to use in order to *sell* things. The number one commodity in the technology business (with a huge profit-margin attached to it) is "user-friendly." And it's baloney! No one in my office that uses one of these supposedly user-friendly machines thinks that it's actually easy to use. They slam their keyboards and throw their hands up *every* day. The only solution that really works is for people to _learn_ how to use computers, and to accept that it will be a challenge. And as for the arcane commands needed to get to the help page, their on the splash screen. Have you used Emacs recently? Joel -- Joel J. Adamson Biostatistician Pediatric Psychopharmacology Research Unit Massachusetts General Hospital Boston, MA 02114 (617) 643-1432 (303) 880-3109 A webpage of interest: http://www.gnu.org/philosophy/sylvester-response.html From showell30 at yahoo.com Fri Jun 1 07:03:15 2007 From: showell30 at yahoo.com (Steve Howell) Date: Fri, 1 Jun 2007 04:03:15 -0700 (PDT) Subject: subexpressions In-Reply-To: Message-ID: <810441.52049.qm@web33511.mail.mud.yahoo.com> --- "A.T.Hofkamp" wrote: > > lambda x: (lambda y: sin(y) + cos(y))(x*x) > Elegant. I find the use of y confusing there (thinking about the unit circle), so I'd amend it to this: lambda x: (lambda x2: sin(x2) + cos(x2))(x*x) But I like the overall idea. ____________________________________________________________________________________ No need to miss a message. Get email on-the-go with Yahoo! Mail for Mobile. Get started. http://mobile.yahoo.com/mail From hat at se-162.se.wtb.tue.nl Fri Jun 29 09:15:24 2007 From: hat at se-162.se.wtb.tue.nl (A.T.Hofkamp) Date: Fri, 29 Jun 2007 15:15:24 +0200 Subject: equality & comparison by default References: <1182942154.185461.89620@e9g2000prf.googlegroups.com> <1i0cy8z.z94q5d1dxgexxN%aleax@mac.com> Message-ID: On 2007-06-29, Gabriel Genellina wrote: > En Thu, 28 Jun 2007 11:38:56 -0300, A.T.Hofkamp > escribi?: > >> The point I intended to make was that having a default __hash__ method on >> objects give weird results that not everybody may be aware of. >> In addition, to get useful behavior of objects in sets one should >> override >> __hash__ anyway, so what is the point of having a default >> object.__hash__ ? > > __hash__ and equality tests are used by the dictionary implementation, and > the default implementation is OK for immutable objects. I like the fact I don't understand exactly how mutability relates to this. The default __eq___ and __hash__ implementation for classes is ok if you never have equivalent objects. In that case, == and 'is' are exactly the same function in the sense that for each pair of arguments, they deliver the same value. This remains the case even if I mutate existing objects without creating equivalent objects. As soon as I create two equivalent instances (either by creating a duplicate at a new address, or by mutating an existing one) the default __eq__ should be redefined if you want these equivalent objects to announce themselves as equivalent with the == operator. > that I can use almost anything as dictionary keys without much coding. Most data-types of Python have their own implementation of __eq__ and __hash__ to make this work. This is good, it makes the language easy to use. However for home-brewn objects (derived from object) the default implementation of these functions may easily cause unexpected behavior and we may be better off without a default implementation for these functions. That would prevent use of such objects in combination with == or in sets/dictionaries without an explicit definition of the __eq__ and __hash__ functions, but that is not very bad, since in many cases one would have to define the proper equivalence notion anyway. > This must always be true: (a==b) => (hash(a)==hash(b)), and the > documentation for __hash__ and __cmp__ warns about the requisites (but > __eq__ and the other rich-comparison methods are lacking the warning). I don't know exactly what the current documentation says. One of the problems is that not everybody is reading those docs. Instead they run a simple test like "print set([Car(1),Car(2)])". That gives the correct result even if the "(a==b) => (hash(a)==hash(b))" relation doesn't hold due to re-definition of __eq__ but not __hash__ (the original designer never expected to use the class in a set/dictionary for example) , and the conclusion is "it works". Then they use the incorrect implementation for months until they discover that it doesn't quite work as expected, followed by a long debugging session to find and correct the problem. Without default __eq__ and __hash__ implementations for objects, the program would drop dead on the first experiment. While it may be inconvenient at that moment (to get the first experiment working, one needs to do more effort), I think it would be preferable to having an incorrect implementation for months without knowing it. In addition, a developer has to think explicitly about his notion of equivalence. Last but not least, in the current implementation, you cannot see whether there is a __eq__ and/or __hash__ equivalence notion. Lack of an explicit definition does not necessarily imply there is no such notion. Without default object implementation this would also be uniqly defined. Albert From doug at alum.mit.edu Fri Jun 15 18:36:54 2007 From: doug at alum.mit.edu (Douglas Alan) Date: Fri, 15 Jun 2007 18:36:54 -0400 Subject: Python's "only one way to do it" philosophy isn't good? References: <1181368143.874341.273140@r19g2000prf.googlegroups.com> <1181385768_30305@sp12lax.superfeed.net> <1181945198.152891.228520@q75g2000hsh.googlegroups.com> Message-ID: Kay Schluehr writes: > On 15 Jun., 22:58, Douglas Alan wrote: >> For instance, I believe that Python is now too big, and that much >> of what is in the language itself should be replaced with more >> general Scheme-like features. Then a good macro mechanism should >> be implemented so that all the conveniences features of the >> language can be implemented via macro definitions in the standard >> library. > And why sould anyone reimplement the whole standard library using > macro reductions? Because this is the "one obvious way to do it" for > people who are addicted to Scheme? (1) By, "should be replaced", I meant in an ideal world. I'm not proposing that this be done in the real world anytime soon. (2) I didn't suggest that a single line of the standard library be changed. What would need to be changed is the core Python language, not the standard library. If this idea were implemented, the core language could be made smaller, and the features that were thereby removed from the language core could be moved into the standard library instead. (3) My reasons for wanting this have nothing to do with being "addicted to Scheme", which I almost never use. It has to do more with my language design and implementation aesthetics, and my desire for a syntax extension mechanism so that I can add my own language features to Python without having to hack on the CPython source code. |>oug From gnewsg at gmail.com Wed Jun 20 15:49:27 2007 From: gnewsg at gmail.com (billiejoex) Date: Wed, 20 Jun 2007 12:49:27 -0700 Subject: How can I know the name of "caller" In-Reply-To: <9o2ei.15809$RX.8157@newssvr11.news.prodigy.net> References: <1182285024.048003.310120@n2g2000hse.googlegroups.com> <9o2ei.15809$RX.8157@newssvr11.news.prodigy.net> Message-ID: <1182368967.245868.307800@o61g2000hsh.googlegroups.com> On 20 Giu, 06:52, John Nagle wrote: > billiejoex wrote: > > Hi there, > > unfortunately, I'm compelled to apply a sort of monkey patching at the > > code of an existing libreary that I can't modify directly. > ... > > > ...(if it is possible) how can I get, from method "called", the name > > of function/method that called it (in this case "caller")? > > Bad idea. > > Note, though, that within Python, you can easily replace existing > function definitions with your own. This is something of a desperation > measure, but it works. > > I have a small collection of patches to the standard Python libraries > which I import. (I've reported all of them in the tracker as bugs, and some > later version of Python will contain the fixes. But that can take years.) > > John Nagle Yeah, it seems really horrible to me too. Python is awesome but stdlib, imo, lacks of properly maintenance. I sincerely don't know what to do... In a production environment what could be better? Overriding the bugged method or including the patched version of the entire module into the distribution? From mccredie at gmail.com Tue Jun 5 14:29:03 2007 From: mccredie at gmail.com (Matimus) Date: Tue, 05 Jun 2007 18:29:03 -0000 Subject: Sending cookies with python. When download with python In-Reply-To: <1181060091.747809.91520@p47g2000hsd.googlegroups.com> References: <1181060091.747809.91520@p47g2000hsd.googlegroups.com> Message-ID: <1181068143.156593.289930@x35g2000prf.googlegroups.com> On Jun 5, 9:14 am, moishyyeh... at gmail.com wrote: > I need to download files off a password protected website. So if I try > to download files off the site with python I will be blocked. Is there > anyway to send cookies with python. So I will be authenticated. Yes. I haven't done it but I know you should be looking at urllib2 and cookielib. I'm sure you can find some examples online. Dive Into Python (google it) has some examples that may help you get started with more general purpose use of urllib2. Matt From tjreedy at udel.edu Sun Jun 10 13:38:36 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 10 Jun 2007 13:38:36 -0400 Subject: Python's "only one way to do it" philosophy isn't good? References: <1181368143.874341.273140@r19g2000prf.googlegroups.com> <1181475395.749525.185520@m36g2000hse.googlegroups.com> Message-ID: wrote in message news:1181475395.749525.185520 at m36g2000hse.googlegroups.com... | > Terry Reedy wrote: | > > In Python, you have a choice of recursion (normal or tail) [snip Stroud questions] | I'm afraid Terry is wrong here, at least if he meant that CPython had | tail recursion *optimization*. NO!!! I did not mean that or imply that in any way. | (and just for those who don't know yet, it's not a shortcoming, it's a | design choice.) And I already noted in a followup that I am working on a Python Papers paper explaining that choice, including Guido's claim that 'for statements are better'. So frankly I am a little annoyed that you dragged my name into your answer to Stroud when you should have succintly said 'No, Never', or better, nothing at all, as someone else already did say that. Read more of the tread before jumping in and acribing ignorance to people. Terry Jan Reedy From hniksic at xemacs.org Fri Jun 29 06:57:24 2007 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Fri, 29 Jun 2007 12:57:24 +0200 Subject: Python's "only one way to do it" philosophy isn't good? References: <7x3b0nmkk6.fsf@ruckus.brouhaha.com> <7xejjzmk7u.fsf@ruckus.brouhaha.com> <7xy7i7xjl5.fsf@ruckus.brouhaha.com> <1182872972.417776.78650@o11g2000prd.googlegroups.com> <7xtzsuy7fe.fsf@ruckus.brouhaha.com> <1182955743.076746.114790@i38g2000prf.googlegroups.com> Message-ID: <877ipn9gff.fsf@mulj.homelinux.net> Douglas Alan writes: > I think you overstate your case. Lispers understand iteration > interfaces perfectly well, but tend to prefer mapping fuctions to > iteration because mapping functions are both easier to code (they > are basically equivalent to coding generators) and efficient (like > non-generator-implemented iterators). The downside is that they are > not quite as flexible as iterators (which can be hard to code) and > generators, which are slow. Why do you think generators are any slower than hand-coded iterators? Consider a trivial sequence iterator: $ python -m timeit -s 'l=[1] * 100 class foo(object): def __init__(self, l): self.l = l self.i = 0 def __iter__(self): return self def next(self): self.i += 1 try: return self.l[self.i - 1] except IndexError: raise StopIteration ' 'tuple(foo(l))' 10000 loops, best of 3: 173 usec per loop The equivalent generator is not only easier to write, but also considerably faster: $ python -m timeit -s 'l=[1] * 100 def foo(l): i = 0 while 1: try: yield l[i] except IndexError: break i += 1 ' 'tuple(foo(l))' 10000 loops, best of 3: 46 usec per loop From evan at yelp.com Tue Jun 12 13:24:03 2007 From: evan at yelp.com (Evan Klitzke) Date: Tue, 12 Jun 2007 10:24:03 -0700 Subject: how to kill a process In-Reply-To: <1181664061.381917.41270@a26g2000pre.googlegroups.com> References: <1181664061.381917.41270@a26g2000pre.googlegroups.com> Message-ID: On 6/12/07, Richard Rossel wrote: > But when the python code is called to kill the created process, the > process is left in a zombie state. If the process is left in a zombie state, it's because the parent process isn't calling wait(2). If the parent process is your own python script, you might try a call to os.wait after the kill statement. -- Evan Klitzke From bruno.42.desthuilliers at wtf.websiteburo.oops.com Thu Jun 28 06:20:44 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Thu, 28 Jun 2007 12:20:44 +0200 Subject: listing the type of an object In-Reply-To: References: <71af3$4682d18c$d443bb3a$9028@news.speedlinq.nl> <46836088$0$29024$426a74cc@news.free.fr> Message-ID: <46838b6a$0$23151$426a34cc@news.free.fr> stef a ?crit : > Bruno Desthuilliers wrote: >> Stef Mientki a ?crit : >>> How can I list a type of an object instance ? >>> >>> I tried: >>> >>> class tLED (tDevice): >> >> >> Do yourself (and the world) a favour and give up hungarian notation... >> This should be: >> >> class Led(Device): >> #... >> >> > Didn't know that this was called "Hungarian notation", > and although it's not my personal favorite, it is th? standard in Delphi, Yeps. I know. But Python is not Delphi. > but I admit that it's not a very good choice in a object oriented > language like Python. MHO is that it's not a very good choice, period. But that's another troll !-) > The program I'm writing now is might be an exception, > I'm writing a program that should be extended by non-Python-programmers, > even maybe non-programmers ! AFAICT, lots of "non-programmers" are using Python. > So I'm trying to use a simplest approach from the viewpoint of the end > users. I think the simplest approach is to use the simplest possible naming scheme. Which is to stick to the idiomatic naming conventions, most of them described in pep08. My 2 cents... From http Mon Jun 25 02:12:31 2007 From: http (Paul Rubin) Date: 24 Jun 2007 23:12:31 -0700 Subject: Python's "only one way to do it" philosophy isn't good? References: <7x3b0nmkk6.fsf@ruckus.brouhaha.com> <1182750077.570603.160240@q69g2000hsb.googlegroups.com> Message-ID: <7xir9cbm0g.fsf@ruckus.brouhaha.com> Douglas Alan writes: > And likewise, good macro programming can solve some problems that no > amount of linting could ever solve. I think Lisp is more needful of macros than other languages, because its underlying primitives are too, well, primitive. You have to write all the abstractions yourself. Python has built-in abstractions for a few container types like lists and dicts, and now a new and more general one (iterators), so it's the next level up. Haskell abstracts the concept of containers to something called monads, so operations like loops and list comprehensions fall out automatically (it took me a while to realize that--Haskell listcomps weren't a bright new idea someone thought of adding to an otherwise complete language: they were already inherently present in the list monad operations and their current syntax is just minor sugaring and is actually restricted on purpose to make the error messages less confusing). So, a bunch of stuff one needs macros to do conveniently in Lisp, can be done with Python's built-in syntax. And a bunch of stuff that Python could use macros for, are easily done in Haskell using delayed evaluation and monads. And Haskell is starting to grow its own macro system (templates) but that's probably a sign that an even higher level language (maybe with dependent types or something) would make the templates unnecessary. From grflanagan at yahoo.co.uk Fri Jun 8 03:01:59 2007 From: grflanagan at yahoo.co.uk (Gerard Flanagan) Date: Fri, 08 Jun 2007 00:01:59 -0700 Subject: howto obtain directory where current (running) py-file is placed? In-Reply-To: <1531d$46688d3a$d443bb3a$16554@news.speedlinq.nl> References: <1181198387.952428.163120@q75g2000hsh.googlegroups.com> <1181200735.220105.19250@q69g2000hsb.googlegroups.com> <1531d$46688d3a$d443bb3a$16554@news.speedlinq.nl> Message-ID: <1181286119.568549.125330@e65g2000hsc.googlegroups.com> On Jun 8, 1:01 am, Stef Mientki wrote: > Gerard Flanagan wrote: > > On Jun 7, 8:39 am, dmitrey wrote: > >> Hi all, > >> I guess this question was asked many times before, but I don't know > >> keywords for web search. > > >> Thank you in advance, D. > > > import os > > > d1 = os.path.dirname(__file__) > > here I get an error "__file__" is not defined ?? The code must be run from a script or module. If you run it from an interactive prompt, then you will get a NameError. > d2 = os.path.dirname(os.__file__) > > here I get a completely different path ?? > Is it the path of the os module? You can expect pure Python modules to have a __file__ attribute, but not every module has one - see the docs. > > > print d1 > > print d2 > > This seems to work (but I doubt it's always working !! ) > print os.getcwd() > > so what's the real answer ? > > thanks, > Stef Mientki From josiah.carlson at sbcglobal.net Mon Jun 18 00:14:01 2007 From: josiah.carlson at sbcglobal.net (Josiah Carlson) Date: Sun, 17 Jun 2007 21:14:01 -0700 Subject: smtp server simulation using Python In-Reply-To: References: Message-ID: William Gill wrote: > I have a (web) development computer w/o an SMTP server and want to test > form generated e-mail using a dummy SMTP server that delivers the mail > message to a file, or better yet, to a text editor instead of actually > sending it. Is it possible to extend the DebuggingServer class,and > override the process_message() method to accomplish this? If so, any > suggestions are appreciated. I would check out the smtpd module . It isn't documented, but the source is fairly straightforward for subclassing. - Josiah From grante at visi.com Tue Jun 26 12:40:48 2007 From: grante at visi.com (Grant Edwards) Date: Tue, 26 Jun 2007 16:40:48 -0000 Subject: Installing python under the linux References: <1182800785.231113.199750@n2g2000hse.googlegroups.com> <1182802267.969628.156960@o61g2000hsh.googlegroups.com> <1182845417.526433.59690@c77g2000hse.googlegroups.com> <4680F3DB.6040901@web.de> <1182867273.230244.151900@w5g2000hsg.googlegroups.com> <5ecn5bF38f35hU1@mid.uni-berlin.de> Message-ID: <1382gcgh2qljr7c@corp.supernews.com> On 2007-06-26, Diez B. Roggisch wrote: >>>No. The only way to change the keywords would be to edit the >>>Python source and re-compile it. >> >> This was very helpful information , I already know that but I >> don't know how to that.PLEASE HELP ME ABOUT THIS, I WILL BE >> VERY GRATEFUL TO YOU. >> >> (IF you can please step by step how to I install that source) > > Stop shouting. Start reading this: > > http://www.catb.org/~esr/faqs/smart-questions.html > > And for god's sake, follow the suggestions you got when asking > the same question over and over: Stop trying to do what you > want to do - altering python. That is _NOT_ the way to go. He's also already been told where to download the source and pointed towards instructions on building and installing it. He seems rather impervious to help. -- Grant Edwards grante Yow! Now I understand the at meaning of "THE MOD SQUAD"! visi.com From dak at gnu.org Thu Jun 21 02:48:24 2007 From: dak at gnu.org (David Kastrup) Date: Thu, 21 Jun 2007 08:48:24 +0200 Subject: The Modernization of Emacs: terminology buffer and keybinding References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182272495.990807.99110@a26g2000pre.googlegroups.com> <87tzt3ihev.fsf@kobe.laptop> <1182370216.961241.6960@n60g2000hse.googlegroups.com> <85zm2ufjpb.fsf@lola.goethe.zz> <1182372592.803332.288260@u2g2000hsc.googlegroups.com> <1182373419.522607.14500@g4g2000hsf.googlegroups.com> <1182374902.920671.171900@k79g2000hse.googlegroups.com> <85ir9ifgtx.fsf@lola.goethe.zz> <1182376044.852820.261530@n2g2000hse.googlegroups.com> Message-ID: <863b0lolaf.fsf@lola.quinscape.zz> Twisted writes: > On Jun 20, 5:37 pm, David Kastrup wrote: >> ...spewing...babbling... > > I won't dignify your insulting twaddle and random ad-hominem verbiage > with any more responses after this one. Something with actual logical > argumentation to rebut may be another matter of course. > > One more GG issue: those stupid star ratings. So potentially > prejudicial. So easy to game, as evidenced by your managing to somehow > vote 82 times(!) against one of my posts in a matter of minutes. It has not occured to you that actually thousands of people read those postings? And they are heavily crossposted to boot (redirecting followup to comp.emacs, I would suggest everybody else do the same). And you have really nothing worthwhile to contribute. So if there is some rating system (I don't use Google Groups so can't tell) in place, your postings would certainly be good candidates for downrating. Not that this posting of mine is much better, and actually the followup-to comp.emacs would indicate that this is about Emacs. However, you have still not given any information about what, if any, version of Emacs your very vaguely expressed experiences are supposed to have come from. > So far I've found a less-impressive method to game them -- it's not > hard to get throwaway accounts elsewhere, send yourself there a > gmail invite, and create many GG accounts. And you wonder that people don't find it worthwhile reading you... > Handy to get around their onerous posting limits. Handy for stuffing > the star-vote ballot boxes with multiple votes, too, but there's no > way I can see to generate 82 of them that fast by that method, and > that much logging in and out in that short a time using different > accounts but from just one IP address is sure to come up on Google's > radar somehow, with unpredictable but probably bad results. Uh, is there some monetary compensation for star ratings? Or what's the deal? Really, if somebody can come up with a better group for followups, feel free to direct there. > How did you do it? I'm guessing they stop the link for voting > appearing as a usable link on the page for a) your own posts and b) > the ones you've voted for, but the link's URL still works, so if you > use a script to keep fetching the appropriate URL ... What a crazy obsession. -- David Kastrup From deets at nospam.web.de Wed Jun 6 11:33:12 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 06 Jun 2007 17:33:12 +0200 Subject: lists - append - unique and sorted References: <1181143597.563633.241640@o5g2000hsb.googlegroups.com> Message-ID: <5co2doF31fu1eU1@mid.uni-berlin.de> rhXX wrote: > hi, > > can i append a item to a list using criterias: > > - UNIQUE - if there already exist don't append > - SORTED - INSERT in the correct place using some criteria? Both can be accomplished using the bisect-module. It will give you the leftmost/rightmost insertion point for a given item and a list, and then you have to see if it is contained in between (or something along these lines, I hope you get the gist of it) Diez From john at datavoiceint.com Tue Jun 12 15:04:39 2007 From: john at datavoiceint.com (HMS Surprise) Date: Tue, 12 Jun 2007 12:04:39 -0700 Subject: List sequential initialization In-Reply-To: <466ee02b$0$10192$9b4e6d93@newsspool4.arcor-online.net> References: <1181670619.086709.116730@g37g2000prf.googlegroups.com> <466ee02b$0$10192$9b4e6d93@newsspool4.arcor-online.net> Message-ID: <1181675079.553239.43010@d30g2000prg.googlegroups.com> Thanks for the explaination. It didn't seem natural and from the tutorial I read: A value can be assigned to several variables simultaneously: >>> x = y = z = 0 # Zero x, y and z Maybe I infer too much.... thanks again, jh From michele.simionato at gmail.com Mon Jun 25 01:08:00 2007 From: michele.simionato at gmail.com (Michele Simionato) Date: Mon, 25 Jun 2007 05:08:00 -0000 Subject: is this a valid import sequence ? In-Reply-To: References: <4f97$467c254d$d443bb3a$9522@news.speedlinq.nl> <137qo1egg4v1k04@corp.supernews.com> <1i0694u.1n6evsntoei0wN%aleax@mac.com> <1i06hm3.1ii0h87p707f2N%aleax@mac.com> Message-ID: <1182748080.330171.324800@g4g2000hsf.googlegroups.com> On Jun 24, 1:29 pm, Steven D'Aprano > I would like to hear your opinion of whether the > following two functions are equally as wrong: > > def f1(gizmo): > global spam # holds the frommet needed for the gizmo > gizmo.get_frommet(spam) > > def f2(gizmo): > # global spam holds the frommet needed for the gizmo > gizmo.get_frommet(spam) > > I'm sure they're both wrong, but I'd like to know if there are degrees of > wrongness. I am not Alex Martelli, but I will tell you my opinion anyway. To me f2 is not wrong: at worse you can say that the comment is redundant since it is already clear from the code that spam is a global, but it is not a big deal. As a code reviewer I would not have had issues with f2. OTOH I would have had serious issues with f1. Since the global statement in correct Python code is solely used to declare that a global variable is being set in an inner scope, I would have to guess that: 1. function f1 wrong; maybe the author cut and pasted it from someplace, forgetting the line where the global variable spam was set; 2. maybe f1 is right, but then the author forgot to remove the global declaration after the cut & paste; 3. the author does not know Python, and he believes that he has to use global to denote the fact that the method gizmo.get_frommet(spam) is setting a global variable. So I would have had to look at get_frommet to see that actually 'spam' is not set there, and finally I would have reached the conclusion that 4. the author was completely wrong and used global without knowing its meaning. All that analysis would have cost me some time, potentially a lot of time depending on the complexity of the code, and all that time would have been wasted time. So f1 is misleading code, and I consider misleading code actually *worse* than wrong code, since it makes you waste your time without a good reason. Michele Simionato From bruno.desthuilliers at gmail.com Sun Jun 10 07:50:05 2007 From: bruno.desthuilliers at gmail.com (bruno.desthuilliers at gmail.com) Date: Sun, 10 Jun 2007 04:50:05 -0700 Subject: Third-party libs in version control In-Reply-To: <466b6f7f$0$70264$c89e4b0f@news.dwx.com> References: <466b6f7f$0$70264$c89e4b0f@news.dwx.com> Message-ID: <1181476205.359681.171170@p77g2000hsh.googlegroups.com> On Jun 10, 5:26 am, Marcus wrote: > Good evening, > > I'm new to developing large subversion-controlled projects. This one > will involve a few third-party libraries like wxWidgets, and perhaps > Twisted. Ordinarily you could just install these into your system and > they'll end up globally (in Python's Lib/site-packages directory). Is it > proper practice to instead install the libraries into a separate [vendor > branch] of the repository and reference that instead? > > I've read about vendor branches, and I'm under the impression that > you're supposed to do that /instead/ of installing the libraries > globally into Python's subdirectories... is that correct? > As Mark already mentionned, svn's 'vendor branches' are only meaningfull when you do have to maintain a customized version of the third-party libs. For 'ordinary' dependencies, you can use eggs or just explicitly states the dependencies in the README or INSTALL doc. From paul at boddie.org.uk Fri Jun 1 13:48:10 2007 From: paul at boddie.org.uk (Paul Boddie) Date: Fri, 01 Jun 2007 10:48:10 -0700 Subject: Comments appreciated on Erlang inspired Process class. In-Reply-To: References: Message-ID: <1180720090.725582.168150@m36g2000hse.googlegroups.com> On 1 Jun, 19:34, "Brian L. Troutwine" wrote: > Lately I've been tinkering around with Erlang and have begun to sorely want > some of its features in Python, mostly the ease at which new processes can be > forked off for computation. To that end I've coded up a class I call, > boringly enough, Process. It takes a function, its args and keywords and runs > the function in another process using os.fork. Processes can be treated as > callables to retrieve the return value of the passed in function. This sounds familiar... http://wiki.python.org/moin/ParallelProcessing Do you have any opinions about those projects listed on the above page that are similar to your own? My contribution (pprocess), along with others (processing, pp...), can offer similar facilities, but the styles of interfacing with spawned processes may be somewhat different. Paul From vdicarlo at gmail.com Sat Jun 9 11:45:47 2007 From: vdicarlo at gmail.com (vdicarlo) Date: Sat, 09 Jun 2007 08:45:47 -0700 Subject: How Can I Increase the Speed of a Large Number of Date Conversions In-Reply-To: References: <1181266113.100863.174410@q19g2000prn.googlegroups.com> Message-ID: <1181403947.221140.8910@i38g2000prf.googlegroups.com> Many thanks for the lucid and helpful suggestions. Since my date range was only a few years, I used Some Other Guy's suggestion above, which the forum is saying will be deleted in five days, to make a dictionary of the whole range of dates when the script starts. It was so fast it wasn't even worth saving in a file. Made the script a LOT faster. I guess two thousand function calls must be faster than 200 million? Like maybe a hundred thousand times faster? I also benefitted from studying the other suggestons. I had actually implemented an on the fly dictionary caching scheme for one of my other calculations. I don't know why it didn't occur to me to do it with the dates, except I think I must be assuming, as a newbie Pythonista, that the less I do and the more I let the libraries do the better off I will be. Thanks for putting me straight. As someone I know said to me when I told him I wanted to learn Python, "the power of Python is in the dictionaries". Funny how long it's taking me to learn that. From borud-news at borud.no Wed Jun 27 06:35:00 2007 From: borud-news at borud.no (Bjorn Borud) Date: 27 Jun 2007 12:35:00 +0200 Subject: The Modernization of Emacs: terminology buffer and keybinding References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182272495.990807.99110@a26g2000pre.googlegroups.com> <87tzt3ihev.fsf@kobe.laptop> <1182370216.961241.6960@n60g2000hse.googlegroups.com> <85zm2ufjpb.fsf@lola.goethe.zz> <1182372592.803332.288260@u2g2000hsc.googlegroups.com> <1182373919.262388.100740@c77g2000hse.googlegroups.com> <85r6o6fhkb.fsf@lola.goethe.zz> <1182375045.626510.188170@m36g2000hse.googlegroups.com> <1182546050.465987.115740@q19g2000prn.googlegroups.com> <871wg3k8c8.fsf@thalassa.lan.informatimago.com> <1182546979.295368.146110@q19g2000prn.googlegroups.com> <87wsxviqol.fsf@thalassa.lan.informatimago.com> <1182552172.406571.116390@i38g2000prf.googlegroups.com> <1182902824.736206.37010@m36g2000hse.googlegroups.com> Message-ID: [Twisted ] | | Some people might say the same thing about emacs. A lot of unix tools | even. "Stubbornly insisting on being odd" appears to be a particularly | prevalent character flaw among the geeknoscenti. I think you are missing the point. you may find Emacs (and UNIX) to be odd, and you consistently parade this around as a reason not to even make an honest attempt at understanding how to use it (them). if the oddness still eclipses usefulness once you've made a proper attempt at understanding a tool, then the oddness is a problem. Emacs (and UNIX) don't exhibit these characteristics for a great number of people. -Bj?rn From p.lavarre at ieee.org Fri Jun 1 21:03:50 2007 From: p.lavarre at ieee.org (p.lavarre at ieee.org) Date: Fri, 01 Jun 2007 18:03:50 -0700 Subject: FAQ: how to vary the byte offset of a field of a ctypes.Structure In-Reply-To: References: <1180634138.944362.88590@d30g2000prg.googlegroups.com> Message-ID: <1180746230.156083.112110@g37g2000prf.googlegroups.com> > Often it helps to ask yourself the question: How would I do this in C? ... > > *Not* by using a structure. A structure is fine if the definition is fixed, > or at most has *one* variable sized field at the very end. http://docs.python.org/lib/module-pickle.html might be near where I'll find concise Python ways of pickling and unpickling the (0xFF ** N) possible ways of packing N strings of byte lengths of 0..xFE together ... I notice by now I need what ctypes does well often enough that I have to make my corrupt copy of a subset of ctypes coexist with ctypes per se. So I have two different BYTE definitions. One is the ctypes.c_ubyte. The other is my corrupt copy. And likewise for a big- endian BIG_WORD and so on. So I end up naming the one BYTE and the other BITE, the one BIG_WORD and the other BIG_WURD, yuck. From semanticist at gmail.com Fri Jun 22 02:34:09 2007 From: semanticist at gmail.com (Miles) Date: Thu, 21 Jun 2007 23:34:09 -0700 Subject: "assert" annoyance In-Reply-To: <7xmyys368j.fsf_-_@ruckus.brouhaha.com> References: <7xmyys368j.fsf_-_@ruckus.brouhaha.com> Message-ID: <1182494049.327182.205310@u2g2000hsc.googlegroups.com> On Jun 22, 1:31 am, Paul Rubin wrote: > What I really want is for any assertion failure, anywhere in the > program, to trap to the debugger WITHOUT blowing out of the scope > where the failure happened, so I can examine the local frame. That > just seems natural, but I don't see an obvious way to do it. You could run the entire program through pdb: ---- #!/usr/bin/env python -m pdb print "Hello!" assert False print "...world!" ---- From ptmcg at austin.rr.com Fri Jun 8 09:09:15 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: Fri, 08 Jun 2007 06:09:15 -0700 Subject: Bragging about Python In-Reply-To: References: Message-ID: <1181308155.710540.287110@n4g2000hsb.googlegroups.com> On Jun 7, 6:15 pm, Steve Howell wrote: > Programs like this were posted on this thread: > > > > > > > def fib(): > > generation, parent_rabbits, baby_rabbits = 1, > > 1, 1 > > while True: > > yield generation, baby_rabbits > > generation += 1 > > parent_rabbits, baby_rabbits = \ > > baby_rabbits, parent_rabbits + > > baby_rabbits > > > for pair in fib(): > > if pair[0] > 100: > > break > > print "Generation %d has %d (baby) rabbits." > > % pair > > One goal behind the SimplePrograms page is to give > people that are new to Python a *gentle* immersion > into Python code. I prefer simple: > > parent_rabbits, baby_rabbits = (1, 1) > while baby_rabbits < 100: > print 'This generation has %d rabbits' % > baby_rabbits > parent_rabbits, baby_rabbits = (baby_rabbits, > parent_rabbits + baby_rabbits) > > Somebody commented in another reply that they'd prefer > the variable names "a" and "b," but other than that, I > think it's hard to simplify this. > > The problem of counting rabbits is not sufficiently > rich to motivate a solution with generator functions, > and "yield" statements are just gonna scare people > away from the Python, unless they've had a chance to > see simpler idioms first. > > I do think there's a place on the page for a good > generators example, but it needs to solve a > sufficiently complex problem that the use of > generators actually simplifies the solution. > > So I'm throwing down the gauntlet--can somebody write > a short program (maybe 10 to 20 lines) where you solve > a problem more simply than a similar > non-generator-using solution would solve it? Maybe > something like Eight Queens? > > -- Steve > > P.S. FWIW the page does already include examples of > generator expressions and the itertools module, but it > does not yet show any code that actually implements a > generator. I would greatly welcome the addition of a > good example. > > ___________________________________________________________________________?_________ > Yahoo! oneSearch: Finally, mobile search > that gives answers, not web links.http://mobile.yahoo.com/mobileweb/onesearch?refer=1ONXIC- Hide quoted text - > > - Show quoted text - Well, I misread your "gauntlet throwing", and implemented a brief 8- queens using recursion and exceptions. Perhaps this could serve as the "before" to an "after" using generators. (I note that neither recursion nor exceptions are covered in your examples.) Also, in googling about for other 8-queens solutions in Python, most are quite complicated - this one uses only 24 lines, and works for boards of any size. I also think this line for printing out the board: print "\n".join( "."*q+"Q"+"."*(BOARD_SIZE-q-1) for q in queens ) illustrates a couple of interesting idioms of Python (joining a list, generator expression, "."*repetition to give "...."). Worthy of your page? -- Paul BOARD_SIZE = 8 def validate(queens): left = right = col = queens[-1] for r in reversed(queens[:-1]): left,right = left-1,right+1 if r in (left, col, right): raise Exception def add_queen(queens): for i in range(BOARD_SIZE): testQueens = queens+[i] try: validate(testQueens) if len(testQueens)==BOARD_SIZE: return testQueens else: return add_queen(testQueens) except: pass raise Exception queens = add_queen([]) print queens print "\n".join( "."*q+"Q"+"."*(BOARD_SIZE-q-1) for q in queens ) From jadestar at idiom.com Fri Jun 29 03:56:11 2007 From: jadestar at idiom.com (James T. Dennis) Date: Fri, 29 Jun 2007 07:56:11 -0000 Subject: Subprocess with and without shell References: <1179194910.310317.38730@y80g2000hsf.googlegroups.com> <1179233834.596515.147010@k79g2000hse.googlegroups.com> Message-ID: <1183103771.221438@smirk> George Sakkis wrote: > On May 15, 5:30 am, Nick Craig-Wood wrote: >> George Sakkis wrote: >>> I'm trying to figure out why Popen captures the stderr of a specific >>> command when it runs through the shell but not without it. IOW: >>> cmd = [my_exe, arg1, arg2, ..., argN] >>> if 1: # this captures both stdout and stderr as expected >>> pipe = Popen(' '.join(cmd), shell=True, stderr=PIPE, stdout=PIPE) >>> else: # this captures only stdout >>> pipe = Popen(cmd, shell=False, stderr=PIPE, stdout=PIPE) >>> # this prints the empty string if not run through the shell >>> print "stderr:", pipe.stderr.read() >>> # this prints correctly in both cases >>> print "stdout:", pipe.stdout.read() >>> Any hints ? >> Post an example which replicates the problem! > I would, but the specific executable being spawned is not a python > script, it's a compiled binary (it's not an extension module either; > it's totally unrelated to python). I don't claim there is a bug or > anything suspicious about Popen, but rather I'd like an explanation of > how can a program display different behavior depending on whether it > runs through the shell or not. > George Well, I would try inspecting your environment ... in the shell and from within your Python process. See if there's anything there. If run a command via an interactive shell and it behaves differently when run via Popen then see if perhaps it's doing something like checking to see if it's stdin, or stdout are TTYs (using the C library functions like isatty() for example). You might try running the program under a Pexpect rather than SubProcess (since Pexpect will run the process with it's std* descriptors connected to pty devices). Alternatively try running the program in a shell pipeline to see if it behaves more like you're seeing when you run it under Python. (Since running it in the middle of a pipeline, perhaps with 2>&1 as well, is ensuring that all of the std* descriptors are connected to pipes. (You could also run with 2>/tmp/some.FIFO after doing a mknod p /tmp/some.FIFO (Linux) or mkfifo /tmp/some.FIFO (BSD) to create the named pipe, of course). If none of that worked ... try running the program under stace, truss, ktrace or whatever system call tracing facility your OS provides ... or under gdb. -- Jim Dennis, Starshine: Signed, Sealed, Delivered From flebber.crue at gmail.com Fri Jun 8 09:00:58 2007 From: flebber.crue at gmail.com (flebber) Date: Fri, 08 Jun 2007 13:00:58 -0000 Subject: read xml file from compressed file using gzip In-Reply-To: <1181303144.910159.326690@z28g2000prd.googlegroups.com> References: <1181278784.312152.99910@r19g2000prf.googlegroups.com> <4668E996.9020006@web.de> <1181303144.910159.326690@z28g2000prd.googlegroups.com> Message-ID: <1181307658.812854.143180@d30g2000prg.googlegroups.com> On Jun 8, 9:45 pm, flebber wrote: > On Jun 8, 3:31 pm, Stefan Behnel wrote: > > > flebber wrote: > > > I was working at creating a simple program that would read the content > > > of a playlist file( in this case *.k3b") and write it out . the > > > compressed "*.k3b" file has two file and the one I was trying to read > > > was maindata.xml. > > > Consider using lxml. It reads in gzip compressed XML files transparently and > > provides loads of other nice XML goodies. > > >http://codespeak.net/lxml/dev/ > > > Stefan > > I will, baby steps at the moment for me at the moment though as I am > only learning and can't get gzip to work This is my latest attempt #!/usr/bin/python import os import zlib class gzip('/home/flebber/oddalt.k3b', 'rb') main_data = os.system(open("/home/flebber/maindata.xml")); for line in main_data: print line main_data.close() From waldemar.osuch at gmail.com Mon Jun 11 21:45:46 2007 From: waldemar.osuch at gmail.com (Waldemar Osuch) Date: Mon, 11 Jun 2007 18:45:46 -0700 Subject: python-ldap for Python 2.5 on Windows? In-Reply-To: References: <1181323389.805143.236480@i38g2000prf.googlegroups.com> Message-ID: <1181612746.393335.324940@o11g2000prd.googlegroups.com> On Jun 11, 6:42 am, Benedict Verheyen wrote: > Thorsten Kampe schreef: > > > >> I'm on Vista (boohoo :(), what's your platform? > > > XP SP2 > > Hmmm it thought so. > So in my case it would be interesting to know how to build it so i can > make a build that works on Vista too. > I have also build it on XP SP2. I have wrapped the files from "setup.py build" and all required .dll using Inno Setup. Maybe Vista does not like the executable produced by Inno. If you still want to try then unzip the following: http://www.osuch.org/python-ldap.zip into your "site-packages" and see how far you can get. The detailed instructions on how to build would be quite long and I'm sure I have forgotten some of the steps already but if you know about "./configure make make install" dance and know how to use Google you should be OK. 1. First install MinGW, Msys and msysDTK. 2. Then you need to compile openldap. See: http://mail.gnome.org/archives/gnomemeeting-devel-list/2005-September/msg00019.html for reference. You will need regex but you can skip Berkley DB before you start. 3. I have compiled openssl too but I have seen ready made libraries for download. I do not have link handy at the moment. 4. The last step would be to run "setup.py build" for python-ldap. Remove sasl2 from setup.cfg since cyrus-sasl does not seem to be available for MinGW. See how far you can get with the above instructions. If you get stuck send me a private email and I will try to help you. If you could keep track of the steps and came up with better instructions than my pitiful attempt above that would be great. Waldemar From martin at see.sig.for.address Wed Jun 20 19:24:40 2007 From: martin at see.sig.for.address (Martin Gregorie) Date: Thu, 21 Jun 2007 00:24:40 +0100 Subject: The Modernization of Emacs In-Reply-To: <1182370884.853838.321440@c77g2000hse.googlegroups.com> References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182344981.372713.298580@w5g2000hsg.googlegroups.com> <1182370884.853838.321440@c77g2000hse.googlegroups.com> Message-ID: <2jpok4-ajt.ln1@zoogz.gregorie.org> Twisted wrote: > This seems to be a closer analogy with emacs versus normal Windows > text editors. > Windows text editors are not normal: most are devoid of all but the most primitive functions and are further hampered by having an interface that required frequent time wasting hand transfers from keyboard to mouse because, if they provide keyboard equivalents at all, these are remarkably unmemorable and/or undocumented. Ask anybody who used early versions of Word and you'll hear just how much faster Word for DOS 5 was than any of its Windows incarnations. This was because all commands were keystrokes so a skilled typist could keep both hands on the keyboard all the time. WinWord's interface is a clunker by comparison. As for documentation, lets look at vi. Not a great editor, but every *nix variation has it installed and any fool can learn to use it in about 2 hours flat and it does at least have good pattern matching. Can't find its documentation? Never heard of manpages ("man vi") or apropos ("apropos vi")? My copy of vi understands ":help" and tells you so if you start it without any arguments. Amongst its benefits are that you can do anything its capable of by using only a standard QUERTY keyboard plus ESC - no function keys, etc are needed - which can save your bacon if somebody misconfigured your console or the computer is dieing. Beyond that it has user-configurable KEY BINDINGS so you can also set it up to suit both yourself and that fancy keyboard in front of you. > Arguably even the weird controls are superior in some > way -- but only if you got used to them, > You mean that Alt-Esc or Windows-e aren't weird? How long is it since you tried to use Windows with a dead mouse? There are a set of arcane keystrokes to replace anything you can do with a mouse but I bet 99% of windows users don't know any of them apart from TAB and CTRL-ALT-DEL. > The above applies equally to vi and its derivatives, if not more so -- > vi is like taking that same already-wacky car with the two separate > throttles and adding, in a fit of quaint nostalgia, the need to > actually crank-start its engine. ;) > If you can't learn enough vi to get by with in half a morning you're probably well out of your depth here on comp.lang.java.programmer. Oh, I forgot: you don't read manuals so you ARE out of your depth. -- martin@ | Martin Gregorie gregorie. | Essex, UK org | From joswig at corporate-world.lisp.de Wed Jun 27 12:34:31 2007 From: joswig at corporate-world.lisp.de (joswig at corporate-world.lisp.de) Date: Wed, 27 Jun 2007 09:34:31 -0700 Subject: Python's "only one way to do it" philosophy isn't good? In-Reply-To: <7x4pkt6aq9.fsf@ruckus.brouhaha.com> References: <7x3b0nmkk6.fsf@ruckus.brouhaha.com> <1182750077.570603.160240@q69g2000hsb.googlegroups.com> <7xir9cbm0g.fsf@ruckus.brouhaha.com> <7xejjzmk7u.fsf@ruckus.brouhaha.com> <7xy7i7xjl5.fsf@ruckus.brouhaha.com> <7x4pkt6aq9.fsf@ruckus.brouhaha.com> Message-ID: <1182962071.350283.289570@c77g2000hse.googlegroups.com> On Jun 27, 10:51 am, Paul Rubin wrote: > I personally use Emacs Lisp every day and I think Hedgehog Lisp (a > tiny functional Lisp dialect intended for embedded platforms like cell > phones--the runtime is just 20 kbytes) is a very cool piece of code. > But using CL for new, large system development just seems crazy today. It seems that many of the hardcore Lisp developers are busy developing the core of new airline system software (pricing, reservation, ...) in Common Lisp. It replaced already some mainframes... Kind of crazy. I guess that counts as very large systems development. There is sure also lots of Python involved, IIRC. From paul at boddie.org.uk Fri Jun 15 10:44:40 2007 From: paul at boddie.org.uk (Paul Boddie) Date: Fri, 15 Jun 2007 07:44:40 -0700 Subject: MySQL - Jython2.2 In-Reply-To: <1181917879.186507.176140@u2g2000hsc.googlegroups.com> References: <1181917879.186507.176140@u2g2000hsc.googlegroups.com> Message-ID: <1181918680.723806.149290@p77g2000hsh.googlegroups.com> On 15 Jun, 16:31, HMS Surprise wrote: > I thought I had a winner mySql-python but it require2 python 2.3-5 and > the tool I am using (maxq) is based on jython 2.2. Is there another > way that I could perform queries from python? For Jython you should use the JDBC driver for the database system in question (MySQL Connector/J in this case, I believe [1]), either writing code which uses the JDBC API directly, or using the zxJDBC module for DB-API compatibility (such as that provided by most other Python database modules). See here for details: http://www.jython.org/docs/zxjdbc.html Paul [1] http://www.mysql.com/products/connector/j/ From mcu87992 at bigpond.net.au Sun Jun 10 00:57:52 2007 From: mcu87992 at bigpond.net.au (Mike) Date: Sun, 10 Jun 2007 04:57:52 GMT Subject: MI5 Persecution: Goldfish and Piranha 29/9/95 (5104) References: Message-ID: And this is here because ....??? wrote in message news:m07050813525824 at 4ax.com... |I just thought I'd let you know what I've been reading into the | "Crusader" spam. I don't want to post this to usenet because somebody | might try to tie that in to my posts in some way (someone already has, in | uk.misc). | | First of all, I'd like to ask you to believe that my phone line in my | apartment is bugged, and has been for many months. I have moved a couple | of times this year, but "they" have faithfully been on my trail. | | Anyway, let's suppose my phone line is bugged. Now, when I talk to my | internet service provider, it's over a SLIP (now PPP) connection. So if | you wanted to bug what was said, either you'd listen in over the line and | have to decode the transmission, or you could go to the service provider | (more difficult) and ask them to decode a particular user's connection. | | OK, so now they're listening to everything I do over my SLIP/PPP | connection. A couple of months ago I was messing around with faking | articles through nntp servers and through anonymous remailers. I chose a | nice inconspicuous newsgroup for my little tests, something no-one would | ever notice. Guess which newsgroup I chose??? Yes, _FISH_!!! or | rec.aquaria to be precise | | And guess what articles I tried to post? Goldfish, Koi carp and, you'll | never guess... PIRANHA!!! The goldfish article and the Koi went through, | but the piranha didn';t appear. | | by now you probably think this is too silly for words. But if you look in | the papers a few eeks ago you will find John Major, Tonny Blair and Paddy | Ashdown sharing a "private joke" about Major's sunburnt goldfish. We | haven't had anything about Koi yet (they must be too dull ). Now, sent by | someone who clearly knew what they were doing (they chose an Italian | backbone site for their launch point) we have many thousands of messages | to people all over the globe. All about piranha, and with the punchline | "that gives you something to think about, doesn't it?" | | The way it works is that they're trying to kill two birds with one stone | again. I don't knoiw why they should be against these national alliance | people, but my interpretation is that they simultaneously try to | discredit them, and stem the flow of Corley articles. | | ================================================================= | | In article , | Mike Corley wrote: | > | >John J Smith (J.J.Smith at ftel.co.uk) wrote: | > | >: b) we do know who you are. Or are you someone else we don't know about? | >: You are currently known as "That bloody persistant net nutter, who's | >: expanding from uk.misc to the rest of the world". | > | >I think the point I was trying to make is that I could tell you things | >from my personal life, at home and at work, which would add credibility | >to my story. But if I named people, then (a) they would object violently | >to being included in this shenanigans, and (b) I would be revealing my | >identity which would be bad for my personal life and my work life. Of | >course some people in my personal life, and at work, do know who "mike | >corley" is. But at least we're observing a studied silence for now. | | :People can always be called "MR X", to save them being named. | : | :I'm completely perplexed as to what you mean by b). Revealing identity? | :To who? And why would this be bad for any part of your life when you | :already have a less than respectful reputation here? | | I'll just enumerate one or two things that I can still remember. Sometime | around August/Sept 1992 I was living in a house in Oxford, and coming out | of the house was physically attacked by someone - not punched, just grabbed | by the coat, with some verbals thrown in for good measure. That was something | the people at work shouldn't have known about... but soon after a couple of | people were talking right in front of me about, "yeah, I heard he was | attacked". | | Again, one I went for a walk in some woods outside Oxford. The next day, | at work, someone said "you know he went to the forest yesterday". | | I don't want to put details on usenet of what happened because to do so | would be to risk it happening again. If you put ideas in peoples' heads | then you can find them reflecting back at you, and I don't want that. | Also I can't remember that much from three years ago. From november 1992 | I started taking "major tranquilizers" and just blotted the whole thing | from my mind. | | >This is a feature time and time again, that the security services | >(presumed) get at you by manipulating other people around you to get at | >you. If you have their contacts, manpower, resources and technology then | >you can do that sort of thing. | | :But why? Are you a threat? | | They pretend they "have" to get at me. After the first few weeks they had | to find a reason to spy and abuse. You can't abuse someone unless they're | in the wrong in some way. What I did "wrong" was to be ill. So it became | "nutter" and "monster" and "he's going to attack us" coupled with | "ha ha ha, he can't do anything to defend himself, it was so funny". That | obvious contradiction within their propaganda is something they | blithely ignore. | | :So, the Security Services never *actually* appear, and you assume that | :they get someone else to do your dirty work. This is a bit of a big | :logical step, here: That person doesn't like me, or is causing me trouble, | :it's not because they've got problems themselves, it must be the "Security | :Services". Yes. Because people are infallible. Or is there more? | | A single source is indicated because of the range of harassment. | BBC + Capital + manipulated_public_at_large + set_up_situations, | what does that add up to? Add in the technology to carry out the | covert spying and the manpower and knowhow to follow you around for | five years without being spotted. It smells very much of the security | services, because there is no other organization (to my knowledge) | which does the things I've seen these people do. | | Remember, they have deliberately chosen the softest of soft targets | to victimize. They purposely chose a mentally ill person who they thought | would be likely to kill himself anyway, so that they could get away with | murder. | | And in all likelihood it will have started as a personal vendetta by someone. | Who could that be? I don't know, but I can give you some clues. | | The first possibility (deep breath) is that someone from my college set me | up. Six years ago I graduated from university in the UK, during the last | year there I was steadily getting more and more ill. I know that I was | talking in my sleep; although I don't know what I was saying, it got | me a reputation, and if someone from my college talked afterwards to | the "wrong" people then that could be the reason for all that has followed. | | I think that's the strongest contender for source. Directly beneath my | room lived another bloke who frequently had his friends round late at | night, after the time that I went to sleep. So they could have heard what | I was saying in my sleep, and that could have got me the reputation for | "talking to myself". | | What I don't know is why that should have rebounded a year after I left. | You'd think it would have happened sooner; it's a bit odd to wait for a | year and then start abuse. That leads me to question what in particular | happened around May/June 1990 for them to start then. | | >What I don't know is how it looks from the other side, from the side of | >the people who are being manipulated to get at me. On a couple of | >occasions I have challenged people to tell the truth of the matter, but | >they have alwats ducked the challenge. | | :Have you ever considered the possibility, that you have made a mistake, and | :the people don't know what you are talking about? | | Yes. I am currently considering the possibility that some people around me | know only what is being posted on Usenet, and have not been "contacted" | by "them". But I _know_ that others have been contacted. | | :What words? Are they in common use? Could they be a catchphrase of a | :popular comedian?: "Nice to see you, to see you nice"? | | In England the all-time No. 1 is "nutter". Easter this year, returning home | from Clapham police station to report five years of harassment ("we're not | saying it's happening and we're not saying it isn't happening"), another | "not happening" incident of harassment when a cowardly little slut did her | country proud by yelling "nutter, nutter, nutter" in the face of the | hated enemy. | | What can you do about that? You can't yell abuse back in their face, because | they know they're supported by their peers, by the media, by the murderers in | the security forces. You can't put them down when the fascist establishment | is on their side. You can't hit them, because they would deny their abuse, | they would deny knowing anything, and bring charges against the "nutter" | who attacked them "at random". | | >You know, you're | >passing saomeone, they're hardly going to construct an argument for your | >benefit, so they work a word of abuse into the conversation which they | >can giggle at. | | :Abuse such as what? We're all adults here, we can take it. Is this abuse | :aimed at you? How can you tell it is? | | I think I've said already what the words are. Thing is, at any given time | the language is consistent. In January everyone's calling you X, then a | few weeks later people stop calling you X and start calling you Y. | | You can tell it's aimed at me, because when people repeatedly say the same | words are you walk past, then laugh, you would have to be hard of | understanding not to recognize it. | | >Or they repeat something that's been said somewhere else... the PE thing | >being a case in point. PE says it, then other people pick up the refrain. | | :Remind me who PE is again. | | PE = "Private Eye" | | >: >To give you an example, which I mentioned in another posting. In around | >: >October 1992, Private Eye ran a cover with the heading "Major's support | >: >lowest ever", with John calling to Norma on the cover "come back, Norma". | >: >Only one obvious interpretation to that, isn';;t there? I certainly | >: >thought so when I saw that cover. Wrongo!! Down the pub with people from work | >: >Simon says to phil, "don';t you think it's wrong then?" phil says, "well | >: >private eye are usuallyright"..."hislop strikes again.. | > | >: Erm. Mike? Heeeelllllooo? What are you on about. What is the other | >: interpretation then? Norma having an affair? Seems a bit wrong, with the | >: heading "Majors support Lowest ever"... | > | >No, this one isn't obvious , it really does need to be explained. I | >certainly didn't understand it when I first saw it. You see, the kernel | >of vitriol is in the words "come back". At the time, the themes of | >abuse were centred around interpretations of those two words (stretch your | >mind a little bit, I don't have to spell it out for you, surely). | | :You did in your mail item. | : | :You seem to be scouting about something called a "Double Entendre". The | :inference being "Come" = Ejaculation, "Back" = Anus (not the first part | :of the body I would have went for, I would have foolishly gone for "Back", | :silly old me). | : | :You see to have picked a sodomy double entendre out of a Private Eye | :headline. They are everywhere. The English language has much double | :meaning in it, and if you put your mind to it, you could pull a double | :entendre out of a randomly chosen page of the bible. So what? | | >The point is that when Simon pointed it out to Phil, he did recognise | >what it meant after a moment's thought... and so did I... and so did the | >people who repeated it several times later... so however murky it may | >seem to you, that is the meaning they intended it to have... | | I still don't really know if the meaning was intended when that headline was | written, or if it was simply "found" after the fact. The reason I think it | might be the former is that I got quite a lot of abuse along the lines of | "sound-alike" or "double-entendre" at work, in particularly from Steve. | So "double" inevitably came to mean split-personality, "two people in one"; | "back" inevitably came to mean "backside", "come" inevitably meant you-know- | what, "split" (well, we'd better split now) again you can guess, "bent" (of | a similar bent), the list goes on forever. These aren't "nice" double- | entendres intended for comedy, they're nasty words to humiliate and cause | pain. If I could turn the clock back three years then I would sue my | former employers for harassment and I would almost certainly win. I had to | take pills after a year of Oxford, so they wouldn't be able to lie their | way out of it. Actually, I could still take them to court - the main | obstacle being that three years after the fact is a bit late and much | of what happened, the details that would be necessary for a case to go | to court, has just been obliterated by time. | | : Smid | | ============================================== | From: flames at flames.cityscape.co.uk (Peter Kr|ger) | Newsgroups: uk.misc,soc.culture.british,alt.conspiracy,uk.media,uk.legal | Subject: Re: Mike Corley - a (helpful) suggestion | Date: Mon Oct 2 05:43:42 1995 | | In article <812551172snz at objmedia.demon.co.uk>, Snail says: | | >Indeed, I feel that my Usenet access is censored simply because I don't want | >to download groups he is partaking in, because of his behaviour. | > | >I wasn't that bothered, but I am starting to get seriously pissed off | >with him. Which takes a lot. | | | Hi Snail | | This person Corley seems quite interesting for three reasons. I put the | following at the end of a post in another thread just to see if he was | reading any other threads in uk.media. | | It seems he is probably not. | | ----------------------------------------------------------------------- | Heres an interesting little story from back in the early days of CCD | technology. There was this miniature camera which was designed to fit | behind the infrared receiver lens of the remote control system (just | beside the IR sensor itself) the camera clocked out the data in 256 lines | of 256 pixels from a Fairchild chip and fed it out, a line at a time, | into the VBI within the TV set itself. The signal could be picked up | remotely from a standard license detector van from where it was stripped | out of the surrounding RF signal and relayed back to the TV station where | it was displayed as a slowscan monochrome image in a corner of the news | readers monitor. | | 5104 | From tjreedy at udel.edu Tue Jun 5 18:26:50 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 5 Jun 2007 18:26:50 -0400 Subject: c[:]() References: <00b301c7a690$25af37d0$240110ac@Muse> <015701c7a7a4$584fac00$240110ac@Muse> Message-ID: "Warren Stringer" wrote in message news:015701c7a7a4$584fac00$240110ac at Muse... | I am porting code that only uses this form | a[:4]b() | | Which translates to: | | for i in range(4): | a[i].b() Or, more directly and perhaps more efficiently: for e in a[:4]: e.b() tjr From bronger at physik.rwth-aachen.de Tue Jun 26 09:04:23 2007 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Tue, 26 Jun 2007 15:04:23 +0200 Subject: text-mode tree viewer? References: <873b0fj9n5.fsf@wilson.homeunix.com> <46810112$0$6273$edfadb0f@dread14.news.tele.dk> Message-ID: <87y7i6j294.fsf@wilson.homeunix.com> Hall?chen! Martin Skou writes: > Not quite, but almost: > > > data=[["Peter", > ["Ian", > [["Randy", > ["Clara"]]]]], > "Paul", > ["Mary", > ["Arthur"]]] This was flawed, there were two brackets too much: data=[["Peter", ["Ian", ["Randy", ["Clara"]]]], "Paul", ["Mary", ["Arthur"]]] > def show(data,level): > for i in data: > if i.__class__.__name__=='list': > show(i,level+1) > else: > print '%s->%s' % ('-'*level,i) > > > show(data,0) It doesn't show Paul and Mary on the same level. I (think I) solved the problem with this: def print_tree(tree, line_columns=[0]): for i, item in enumerate(tree): current_line = u"" for j, pos in enumerate(line_columns): current_line += (pos - j) * " " + "|" print current_line if isinstance(item, list): print current_line[:-1] + "+---> " + item[0] new_line_columns = line_columns + [line_columns[-1] + 6 + len(item[0]) // 2] if i == len(tree) - 1: del new_line_columns[-2] print_tree(item[1], new_line_columns) elif isinstance(item, basestring): print current_line[:-1] + "+---> " + item Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus Jabber ID: bronger at jabber.org (See http://ime.webhop.org for ICQ, MSN, etc.) From http Sat Jun 30 04:32:31 2007 From: http (Paul Rubin) Date: 30 Jun 2007 01:32:31 -0700 Subject: PEP 3107 and stronger typing (note: probably a newbie question) References: <1182369568.941307.316260@p77g2000hsh.googlegroups.com> <5dveb4F360un0U1@mid.individual.net> <467a9209$0$22165$426a74cc@news.free.fr> <1182858785.886469.93060@n60g2000hse.googlegroups.com> <46824d8d$0$2324$426a74cc@news.free.fr> <4682eddc$0$23164$426a74cc@news.free.fr> <5ehokpF38ov3jU2@mid.individual.net> <4683d5cd$0$8993$426a74cc@news.free.fr> <7xps3e3g9x.fsf@ruckus.brouhaha.com> <468565a0$0$3686$426a74cc@news.free.fr> Message-ID: <7xhcopj10g.fsf@ruckus.brouhaha.com> Bruno Desthuilliers writes: > > [A type system is a] tractable syntactic method for proving the > > absence of certain program behaviors by classifying phrases > > according to the kinds of values they compute. (Pierce 2002)." > > Is this supposed to contradict my assertion that *static* typing is > for compilers ? Yes, the main benefit these days is to prove the absence of certain types of bugs in the program. The article "What To Know Before Debating Type Systems" is pretty informative (though it doesn't go as far as to call C/C++ untyped): http://cdsmith.twu.net/types.html > > C and C++ are basically untyped languages. > > Hem... This assertion is at least debatable. Care to post this on > c.l.c or c.l.c++, so we get some feedback ? I wouldn't consider the aficionados of those dinosaur languages to be authorities on such a question. From cam.ac.uk at mh391.invalid Mon Jun 25 08:53:18 2007 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Mon, 25 Jun 2007 13:53:18 +0100 Subject: socket on cygwin python In-Reply-To: <1182748882.617588.190230@c77g2000hse.googlegroups.com> References: <1182748882.617588.190230@c77g2000hse.googlegroups.com> Message-ID: bacon.chao at gmail.com wrote: > I've installed cygwin with latest python 2.5.1, but it seems that the > socket lib file do NOT support IPv6(cygwin\lib\python2.5\lib-dynload > \_socket.dll), what can I do if I want to use IPv6? I don't think Cygwin supports IPv6. Use the native Windows Python. -- Michael Hoffman From mcl.office at googlemail.com Sun Jun 3 14:05:58 2007 From: mcl.office at googlemail.com (mosscliffe) Date: Sun, 03 Jun 2007 11:05:58 -0700 Subject: Cookie: Not understanding again In-Reply-To: <1180781405.520876.63430@m36g2000hse.googlegroups.com> References: <1180709394.151350.103200@q69g2000hsb.googlegroups.com> <1180743184.755904.155510@m36g2000hse.googlegroups.com> <1180773126.214516.218140@q69g2000hsb.googlegroups.com> <1180781405.520876.63430@m36g2000hse.googlegroups.com> Message-ID: <1180893958.075422.33110@m36g2000hse.googlegroups.com> On 2 Jun, 11:50, David Wahler wrote: > On Jun 2, 9:32 am, mosscliffe wrote: > > > David, > > > Thanks for your help. > > > I spent all last night trying to get it to work, but I can not work > > out how to force mycookieinto the response header. The most > > annoying part is on one occasion it did and thecookiesat there until > > I killed the session. By the time I discovered 'pageinfo' add-in for > > firefox, thecookiehad gone. > > Your CGI script needs to produce output of the form: > > Header-1: ... > Header-2: ... > > response data goes here... > > Each line before the blank line is an HTTP header. To send cookies to > the browser, you need to generate a header of the form: > > Set-Cookie: name=value > > Printing the SimpleCookie object does this for you. > > > I have read a lot about cookies, but the grey matter is very slow at > > absorbing nowadays. I was wondering if I should add the 'path=/' to > > mycookie, as I am using a host that has numbers for the IP address > > and my domain name when used, is via a frame. Although the python bit > > to display the contents (when it did work), did not show any value for > > 'path'. > > If you specify a path attribute, then the browser will only send thecookieon requests that begin with that path. If you don't, it > defaults to the URL of the page that generates thecookie. For a > single test script like this, there's no need to bother with it, but > you can set it like this: > > >>>cookie["someCookieName"]["path"] = "/path/to/whatever" > > Could I create the response header in python and get it executed as > > part of my form submission ? > > > Obviously, still struggling. > > Here's a simple, complete example to get you started, based loosely on > your original code: > > ###################################################################### > > importCookie, os > import cgitb; cgitb.enable() > > def getCookie(): > c =Cookie.SimpleCookie() > if 'HTTP_COOKIE' in os.environ: > c.load(os.environ['HTTP_COOKIE']) > > if os.environ['QUERY_STRING'] == 'reset' or 'mysession' not in c: > c['mysession'] = 0 > else: > c['mysession'] = int(c['mysession'].value) + 1 > > return c > > if __name__ == '__main__': > > print "Content-type: text/html" > myCookie = getCookie() > print myCookie > > if os.environ['QUERY_STRING'] == 'reset': > print "Status: 302 Moved" > print "Location:", os.environ['SCRIPT_NAME'] > print > else: > print > print 'Current Value: ', myCookie['mysession'].value > print '
Reset Counter' > > ###################################################################### > > Hope this helps! > > -- David David, Thank you very much for your detailed reply. As soon as I get a chance to try it all out, I will let you know how I get on. Thanks again Richard From antroy at gmail.com Fri Jun 15 11:00:25 2007 From: antroy at gmail.com (Ant) Date: Fri, 15 Jun 2007 08:00:25 -0700 Subject: MySQL - Jython2.2 In-Reply-To: <1181917879.186507.176140@u2g2000hsc.googlegroups.com> References: <1181917879.186507.176140@u2g2000hsc.googlegroups.com> Message-ID: <1181919625.603723.104040@q66g2000hsg.googlegroups.com> On Jun 15, 3:31 pm, HMS Surprise wrote: > I thought I had a winner mySql-python but it require2 python 2.3-5 and > the tool I am using (maxq) is based on jython 2.2. Is there another > way that I could perform queries from python? If you want to query via Jython, use the jdbc driver from www.mysql.com, and you an then use JDBC from within Jython. You'll just need to add the mysql jdbc jar to your classpath. HTH. -- Ant... http://antroy.blogspot.com/ From rhamph at gmail.com Fri Jun 1 00:12:27 2007 From: rhamph at gmail.com (Adam Olsen) Date: Thu, 31 May 2007 22:12:27 -0600 Subject: Thread-safety of dict Message-ID: It seems to be a commonly held belief that basic dict operations (get, set, del) are atomic. However, since I know searching the hash table is a multistep process, I thought I'd check it out for sure. First, my assumption is that one thread is attempting to get a single key, while other threads are getting, setting, and deleting different keys. Obviously you could fail anyway if they were modifying the same key. The avenue of attack I'm interested in is when lookdict() calls PyObject_RichCompareBool(). If this calls out to Python code then the GIL can/will be released. Many builtin types won't release the GIL though, notably str, so you're safe if they're all you use. Assuming your dict did get modified, lookdict() then has some checks to protect itself (which it does by restarting the search). It checks if mp->ma_table got changed and then it checks if ep->me_key got changed. So to attack it we need to: 1) have the same table address it had before, 2) keep the key it was checking when the change happened the same, 3) cause your target key to move to an entry it already searched. Getting the target key to move entries without deleting it is hard. The only time that happens is when the dict gets resized. It's much easier to strip the dummies from ma_table when copying from another table, and since it's normally going to a different size it makes sure it always has a copy. That means the table address will always change (violating requirement #1), but there's two catches. First, ma_smalltable always has the same address. If we could get it to resize while staying in ma_smalltable we'd have succeeded. However, various things come together to make that impossible: * PyDict_MINSIZE is 8 * dictresize() uses a loop that increases newsize (which defaults to PyDict_MINSIZE) so long as newsize <= minused * dictresize() is only called by PyDict_SetItem after a new key is added, but since our target key must have been there the whole time, it will be (at least) the 2nd key in the dict * PyDict_SetItem multiplies the number of keys by 4 before passing it to dictresize(), meaning our 2 becomes 8. However, that's big enough for dictresize()'s loop to go to the next-bigger size (it's just on the limit), so we won't get ma_smalltable after all. It's fragile and undocumented, and it's quite possible future versions will break it, but for now this part is thread-safe. The second catch is not thread-safe however. dictresize() always allocates a new table. However, if you call dictresize() *twice*, it could get the original table back again. This allows us to meet the 3 conditions I outlined, letting the attack succeed. So there you have it: if you're using a dict with custom classes (or anything other than str) across multiple threads, and without locking it, it's possible (though presumably extremely rare) for a lookup to fail even through the key was there the entire time. -- Adam Olsen, aka Rhamphoryncus From hg at nospam.org Sat Jun 9 20:36:52 2007 From: hg at nospam.org (hg) Date: Sat, 09 Jun 2007 19:36:52 -0500 Subject: pyexe "format" Message-ID: Hi, Is there a clean way to figure out that a .exe was actually generated by pyexe ? hg From arkanes at gmail.com Thu Jun 28 13:04:49 2007 From: arkanes at gmail.com (Chris Mellon) Date: Thu, 28 Jun 2007 12:04:49 -0500 Subject: Help needed for Pmw and WxPython Interface In-Reply-To: <1ef9860e0706280928l2d000ba8g555d568228ee1b7b@mail.gmail.com> References: <1ef9860e0706280928l2d000ba8g555d568228ee1b7b@mail.gmail.com> Message-ID: <4866bea60706281004v34159717s4f0aec35582618d5@mail.gmail.com> On 6/28/07, senthil arasu wrote: > Is it possible to integrate the functionalities of libraries WxPython and > pmw.? > No. From robin at reportlab.com Mon Jun 4 13:50:54 2007 From: robin at reportlab.com (Robin Becker) Date: Mon, 04 Jun 2007 18:50:54 +0100 Subject: safe cgi parameter Message-ID: <466450FE.5080306@chamonix.reportlab.co.uk> I'm trying to pass xml into a cgi script and have some problems because I both want to escape all my inputs (to avoid the possibility of an html injection attack) and also allow my xml to be obtained in its original form. I thought of this from xml.sax.saxutils import escape as xmlEscape class SafeCgiParam(str): def __new__(cls,v): return str.__new__(cls,xmlEscape(v)) def __init__(self,v): self.__raw__ = v so >>> x=SafeCgiParam('a<&>b') >>> print x a<&>b >>> print x.__raw__ a<&>b ie always wrap the value, but access to the original is possible via __raw__. However, if you do anything like x.strip() the original is lost. I'm not sure that's a bad thing, but I thought I would ask what others do for this problem. -- Robin Becker From tjollans at googlemail.com Mon Jun 4 06:47:50 2007 From: tjollans at googlemail.com (tjollans@g-NOSPAM-mail.com) Date: Mon, 04 Jun 2007 10:47:50 -0000 Subject: WSGI/wsgiref: modifying output on windows ? In-Reply-To: <1180905084.438849.326640@m36g2000hse.googlegroups.com> References: <1180905084.438849.326640@m36g2000hse.googlegroups.com> Message-ID: <1180954070.953137.247680@o5g2000hsb.googlegroups.com> On Jun 3, 10:11 pm, "tjoll... at g-NOSPAM-mail.com" wrote: > Might this be a bug in wsgiref ? I will hopefully be able to do some > more testing, ... The following simple CGI script should, AFAIK, on any platform, output exactly the file specified in code. It does not on Apache 2 on Windows; I believe this to be a bug in wsgiref.handlers.CGIHandler. Can someone test this in a similar environment (Windows+a web server?) to confirm this ? (The first two lines need to be edited depending on the site) #!c:\python25\python.exe fname, type = r'c:\hdr.png', 'image/png' from wsgiref.handlers import CGIHandler def wsgiapp(env, start_response): f = file(fname, 'rb') start_response('200 OK', [('Content-Type', type)]) return [f.read()] CGIHandler().run(wsgiapp) From tommy.nordgren at comhem.se Wed Jun 13 06:16:02 2007 From: tommy.nordgren at comhem.se (Tommy Nordgren) Date: Wed, 13 Jun 2007 12:16:02 +0200 Subject: In C extension .pyd, sizeof INT64 = 4? In-Reply-To: <1181642594.963433.132750@g37g2000prf.googlegroups.com> References: <1181642594.963433.132750@g37g2000prf.googlegroups.com> Message-ID: On 12 jun 2007, at 12.03, Allen wrote: > My C extension works wrong, and debug it, found that sizeof (INT64) = > 4, not 8. > I compile on Windows XP platform. > Please tell me how to fix it to support INT64? > Thanks. > > -- > http://mail.python.org/mailman/listinfo/python-list On compilers that can gnerate both 32 and 64 bit executables, the size of some data types vary according to compiler options. You are probably using a typedef long INT64; In order for INT64 to always be 64 bits/8bytes you should declare: typedef long long INT64; ------------------------------------- This sig is dedicated to the advancement of Nuclear Power Tommy Nordgren tommy.nordgren at comhem.se From andrew at nospam.com Sat Jun 2 17:57:40 2007 From: andrew at nospam.com (Andrew Holme) Date: Sat, 2 Jun 2007 22:57:40 +0100 Subject: Help with win32 com_error exception References: Message-ID: "Richard Gordon" wrote in message news:cqk8i.3573$bZ1.2348 at trnddc08... > Sorry if this is sent twice, but I didn't see it get posted the first > time. > > I've got a fatal bug using Parente's pyTTS with Python 2.3 on Windoze 32 > using MS SAPI 5.1 and Hammond's win32 module. The test program is > import pyTTS > tts = pyTTS.Create() > tts.Speak('Hello world.') > > The resulting debug trace is: > > PythonWin 2.3.5 (#62, Feb 8 2005, 16:23:02) [MSC v.1200 32 bit (Intel)] > on win32. > Portions Copyright 1994-2006 Mark Hammond - see 'Help/About PythonWin' > for > further copyright information. > Traceback (most recent call last): > File > "C:\PROGRA~1\Python23\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py", > line 307, in RunScript > debugger.run(codeObject, __main__.__dict__, start_stepping=0) > File > "C:\PROGRA~1\Python23\Lib\site-packages\pythonwin\pywin\debugger\__init__.py", > line 60, in run > _GetCurrentDebugger().run(cmd, globals,locals, start_stepping) > File > "C:\PROGRA~1\Python23\Lib\site-packages\pythonwin\pywin\debugger\debugger.py", > line 631, in run > exec cmd in globals, locals > File "C:\yakitome\test\examples\ex1.py", line 4, in ? > tts.Speak('Hello world.') > File "C:\PROGRA~1\Python23\Lib\site-packages\pyTTS\sapi.py", line 213, > in Speak > self.speech.Speak(text, flagsum) > File "C:\Program > Files\Python23\lib\site-packages\win32com\gen_py\C866CA3A-32F7-11D2-9602-00C04F8EE628x0x5x0.py", > line 2637, in Speak > , Flags) > com_error: (-2147352567, 'Exception occurred.', (0, None, None, None, > 0, -2147201015), None) > >>> > > The system does not have a sound card --- could that be an issue? Could be. -2147352567 = 0x80020009 -2147201015 = 0x80045009 If you search for these numbers in hex, you may have more luck. e.g. SPERR_NO_DRIVER 0x80045009 -2147201015 There is no wave driver installed. >From https://msdn2.microsoft.com/en-us/library/ms717306.aspx From andreengels at gmail.com Wed Jun 13 03:56:49 2007 From: andreengels at gmail.com (Andre Engels) Date: Wed, 13 Jun 2007 09:56:49 +0200 Subject: a question about unicode in python In-Reply-To: References: <1181663182.251071.10540@i13g2000prf.googlegroups.com> Message-ID: <6faf39c90706130056n5c32cff3v534dceccd339b570@mail.gmail.com> 2007/6/12, WolfgangZ : > hzqij schrieb: > > i have a python source code test.py > > > > # -*- coding: UTF-8 -*- > > > > # s is a unicode string, include chinese > > s = u'??' > > > > then i run > > > > $ python test.py > > UnicodeDecodeError: 'utf8' codec can't decode bytes in position 0-1: > > invalid data > > > > by in python interactive, it is right > > > >>>> s = u'??' > > > > why? > > > > > > just an idea: is your text editor really supporting utf-8? In the mail > it is only displayed as '??' which looks for me as the mail editor did > not send the mail as utf. Try to attach a correct text file. That must be your mail client, not his text editor or mail client. I do see two Chinese characters in the message. -- Andre Engels, andreengels at gmail.com ICQ: 6260644 -- Skype: a_engels From newsgroups at nospam.demon.co.uk Mon Jun 4 05:12:46 2007 From: newsgroups at nospam.demon.co.uk (Douglas Woodrow) Date: Mon, 4 Jun 2007 10:12:46 +0100 Subject: int vs long References: <1180839659.196587.194200@p77g2000hsh.googlegroups.com> <7xr6otiv4l.fsf@ruckus.brouhaha.com> <1180895701.813483.326780@k79g2000hse.googlegroups.com> <7xabvgj33p.fsf@ruckus.brouhaha.com> <1hz4uas.7jeyyu192pb8tN%aleax@mac.com> Message-ID: On Mon, 4 Jun 2007 10:50:14, Peter Otten <__peter__ at web.de> wrote >>> >>> This is fixed in Python2.5: >>> >> Hm, my test above was from 2.5!? > >Then your installation is broken. What does > >>>> import itertools >>>> itertools >'/usr/local/lib/python2.5/lib-dynload/itertools.so'> > >print? Maybe it's a problem with the Windows build of Python 2.5 ,---- | Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 | 32 bit (Intel)] on win32 | Type "help", "copyright", "credits" or "license" for more information. | >>> import sys | >>> import itertools | >>> itertools | | >>> c = itertools.count(sys.maxint) | >>> c.next() | Traceback (most recent call last): | File "", line 1, in | OverflowError: cannot count beyond LONG_MAX | >>> `---- -- Doug Woodrow From michael at jedimindworks.com Tue Jun 5 12:00:21 2007 From: michael at jedimindworks.com (Michael Bentley) Date: Tue, 5 Jun 2007 11:00:21 -0500 Subject: Beginning Python In-Reply-To: <1181053786.724436.132900@n15g2000prd.googlegroups.com> References: <1181053786.724436.132900@n15g2000prd.googlegroups.com> Message-ID: <6A5A8C3E-91B6-42B2-B22E-C5A2D43D5D76@jedimindworks.com> On Jun 5, 2007, at 9:29 AM, abhiee wrote: > Hello , I have just begun learning python...and I'm loving it...Just > wanted to ask you that how much time would it take me to learn python > completely and which languages should i learn alongwith python to be a > good professional programmer?...Now i only know C.... > thanx in advance! How long is a piece of rope? Seriously, there is no way for anyone to predict how long it will take you to learn something. In this case, that something (Python) is a moving target -- there are a few things I use daily that weren't even part of the language when I started. I do believe that it takes about three years to get reasonably competent at anything. And about ten years to get really good at it. And probably another ten years to be a master (I'm only guessing though -- because I haven't been doing anything for twenty years yet). Of course, by my metrics I guess even Guido wouldn't be a master at Python so perhaps I'm full of crap :-) Hope this helps, Michael --- "I use tuples simply because of their mellifluous appellation." -- Neil Cerutti From steven.bethard at gmail.com Thu Jun 14 14:22:09 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Thu, 14 Jun 2007 12:22:09 -0600 Subject: SimplePrograms challenge In-Reply-To: References: <466F27A3.8000106@gmail.com> Message-ID: rzed wrote: > Steven Bethard wrote in >> def iter_primes(): >> # an iterator of all numbers between 2 and +infinity >> numbers = itertools.count(2) >> >> # generate primes forever >> while True >> >> # generate the first number from the iterator, >> # which should always be a prime >> prime = numbers.next() >> yield prime >> >> # lazily remove all numbers from the iterator that >> # are divisible by prime we just selected >> numbers = itertools.ifilter(prime.__rmod__, numbers) >> >> I think that's 17-ish, though you could shrink it down by >> removing some of the spaces. > > How about including a driver? Yes, absolutely a good idea. Fortunately, the other Steve borrowed the time machine already and added this to the end:: for p in iter_primes(): if p > 1000: break print p http://wiki.python.org/moin/SimplePrograms STeVe From grante at visi.com Thu Jun 21 20:30:36 2007 From: grante at visi.com (Grant Edwards) Date: Fri, 22 Jun 2007 00:30:36 -0000 Subject: Collections of non-arbitrary objects ? References: <1182449993.223262.229500@z28g2000prd.googlegroups.com> <87k5twx4hf.fsf@benfinney.id.au> Message-ID: <137m61ct07mniaf@corp.supernews.com> On 2007-06-21, Ben Finney wrote: > walterbyrd writes: > >> Python seems to have a log of ways to do collections of >> arbitrary objects: lists, tuples, dictionaries. But what if I >> want a collection of non-arbitrary objects? Lists never contain arbitrary objects, they contain only objects that you put there. The reason that other languages have typed containers (e.g. array of type T) is that the elements of the array don't know what type they are, so you've got to limit what you put in there. In python, all objects know what type they are, so there's no point in labelling the references to the objects with type info as well. >> A list of records, or something like that? > > Then collect them in a non-arbitrary way. > > That's a flippant response, but I don't understand the > question. What are you asking for that you don't already have? > A list can contain a sequence of objects of the same type > already. What are you expecting that a list does not provide? I was also a bit baffled by the question. The only things I could think of are: 1) a "container" that raised an exception if the type of a new item doesn't match the type of what's in it already. I don't really see much benefit in that. If you want a list to contain only objects of type T, then only put that type of objects in it. 2) an "array" that contains a large number of small things (e.g. integer or floating point numbers) that need to be stored with minimal overhead. That's a useful thing, and there are several packages that do that -- numpy is the one generally recommended for new designs. -- Grant Edwards grante Yow! Are the STEWED PRUNES at still in the HAIR DRYER? visi.com From skip at pobox.com Tue Jun 5 15:32:14 2007 From: skip at pobox.com (skip at pobox.com) Date: Tue, 5 Jun 2007 14:32:14 -0500 Subject: Does Boost.Python participate in cyclic gc? Message-ID: <18021.47678.620340.721689@montanaro.dyndns.org> We encountered a situation today where it appeared that a Boost.Python-provided class didn't participate in Python's cyclic garbage collection. The wrapped C++ instance held a reference to a method in the Python object which referenced the Boostified C++ instance, e.g.: class Foo: def __init__(self, ...): self.over_there = BoostifiedClass() self.over_there.set_callback(self.boost_callback) ... def boost_callback(self, ...): ... When an instance of Foo went out of scope the BoostifiedClass instance it referred to didn't disappear. (We could tell because it made connections to another server which didn't disappear.) The solution was to recognize when we where finished with it to set self.over_there to None. It would be nice if Boost.Python knew how to play in the gc sandbox, but I suspect it may not. Thx, Skip From python at jayloden.com Tue Jun 26 11:34:54 2007 From: python at jayloden.com (Jay Loden) Date: Tue, 26 Jun 2007 11:34:54 -0400 Subject: Help needed with translating perl to python In-Reply-To: <1182871026.250669.296590@q69g2000hsb.googlegroups.com> References: <1182870250.890390.28970@g37g2000prf.googlegroups.com> <1182871026.250669.296590@q69g2000hsb.googlegroups.com> Message-ID: <4681321E.4070500@jayloden.com> vj wrote: > I posted too soon: > >> Statement 1: >> my $today = sprintf("%4s%02s%02s", [localtime()]->[5]+1900, >> [localtime()]->[4]+1, [localtime()]->[3]) ; > > 1. is localtime the same as time in python? http://perldoc.perl.org/functions/localtime.html It's more like time.localtime() One key thing you'll notice here is the adding of 1900 - the year returned by Perl's localtime is 'number of years since 1900' so in order to convert it to the actual year you have to add 1900. > 2. What does -> ? do in perl? In this case, it's accessing localtime similar to something like localtime[5]. -> can basically be considered similar to dotted notation in Python, used to access items in a container object. > 3. What is 'my' http://perldoc.perl.org/functions/my.html It's a way of declaring a local variable in Perl. >> Statement 2: >> my $password = md5_hex("$today$username") ; > > is md5_hex the same as md5.new(key).hexdigest() in python? http://www.xav.com/perl/site/lib/Digest/MD5.html#functions >> $msglen = bcdlen(length($msg)) ; > > 1. here the funciton is being called with the length of variable msg. > However the function def below does not have any args > >> sub bcdlen { >> my $strlen = sprintf("%04s", shift) ; >> my $firstval = substr($strlen, 2, 1)*16 + substr($strlen, 3, 1) ; >> my $lastval = substr($strlen, 0, 1)*16 + substr($strlen, 1, 1) ; >> return chr($firstval) . chr($lastval) ; >> >> } Perl subroutines (functions) can be declared without any arguments if desired, and then you can use 'shift' to access any arguments. So: sub printMe { my $arg = shift; print $arg; } would print the first argument passed to it, e.g. printMe("foo"); would output foo. > > 2. What does shift do above? http://perldoc.perl.org/functions/shift.html See above, it's used for accessing the first value of an array, in this case an arry of arguments to a subroutine. > 3. is the '.' operator just + in python? '.' operator is used for string concatenation in Perl, so + would be the equivalent in Python, yes. -Jay From bearophileHUGS at lycos.com Wed Jun 13 06:31:43 2007 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Wed, 13 Jun 2007 03:31:43 -0700 Subject: Convert String to Int and Arithmetic In-Reply-To: <1181659583.424110.194340@r19g2000prf.googlegroups.com> References: <1181658761.300066.118210@a26g2000pre.googlegroups.com> <1181659583.424110.194340@r19g2000prf.googlegroups.com> Message-ID: <1181730703.164441.46200@i13g2000prf.googlegroups.com> Kay Schluehr: > >>> int(cpuSpeed.split(":")[1].strip()) Probably this suffices: int(cpuSpeed.split(":")[1]) Bye, bearophile From info at thegrantinstitute.com Mon Jun 25 04:29:33 2007 From: info at thegrantinstitute.com (Anthony Jones) Date: 25 Jun 2007 01:29:33 -0700 Subject: Professional Grant Proposal Writing Workshop (September 2007: Simon Fraser University) Message-ID: <20070625012932.D06A1A66806B9871@thegrantinstitute.com> An HTML attachment was scrubbed... URL: From fdu.xiaojf at gmail.com Tue Jun 12 13:12:48 2007 From: fdu.xiaojf at gmail.com (fdu.xiaojf at gmail.com) Date: Wed, 13 Jun 2007 01:12:48 +0800 Subject: questions about solving equations in scipy Message-ID: <466ED410.2010507@gmail.com> Hi all, I have two questions about scipy. 1) When I was trying to solve a single variable equations using scipy, I found two methods: scipy.optimize.fsolve, which is designated to find the roots of a polynomial, and scipy.optimize.newton, which is used for Scalar function root finding according to the help(). I have tried both, and it seemed that both worked well, and fsolve ran faster. My questions is, which is the right choose ? 2) I have to solve a linear equation, with the constraint that all variables should be positive. Currently I can solve this problem by manually adjusting the solution in each iteration after get the solution bu using scipy.linalg.solve(). Is there a smart way ? Thanks in advance. Xiao Jianfeng From jstroud at mbi.ucla.edu Thu Jun 7 06:09:42 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Thu, 07 Jun 2007 03:09:42 -0700 Subject: =?windows-1252?Q?=93On_Your_Desktop=94=3A_the_celebr?= =?windows-1252?Q?ity_posting_editorial_blog?= In-Reply-To: References: Message-ID: Steve Holden wrote: > The first post comes from Ian Bicking: > > http://onyourdesktop.blogspot.com/ > "Linux was a remote possibility: just why is it so bad as a laptop OS?" I'm a diehard os x man myself, but I spent about 1.5 days setting up ubuntu feisty on an Acer Travel Mate TM2480-2779 ($459 after rebate from newegg). Set up wireless (got WEP going but WPA was beyond my patience), full resolution from the monitor, and the soundcard going 100%. None of this was straightforward but it was all plenty doable with sufficient diligence. You will have to compile a kernel module or 2. It makes for a nice little linux box once you get everything configured. The acer hardware is pretty respectable, especially for the price. I'm not quite ready to trade in my 15" Core2Duo MBP, though, as there is no substitute for tasty apple hardware. From george.sakkis at gmail.com Sun Jun 3 12:18:10 2007 From: george.sakkis at gmail.com (George Sakkis) Date: Sun, 03 Jun 2007 16:18:10 -0000 Subject: Python rocks In-Reply-To: References: <4661700a$0$19261$da0feed9@news.zen.co.uk> <1180807432.351720.123860@p47g2000hsd.googlegroups.com> Message-ID: <1180887490.024955.61380@p47g2000hsd.googlegroups.com> On Jun 2, 4:58 pm, a... at pythoncraft.com (Aahz) wrote: > In article <1180807432.351720.123... at p47g2000hsd.googlegroups.com>, > George Sakkis wrote: > > > > >I had probably stumbled on many/most of the common pitfalls usually > >mentioned (e.g.http://www.ferg.org/projects/python_gotchas.html, > >http://zephyrfalcon.org/labs/python_pitfalls.html) while learning, but > >picked them up easily after the first or second time. Off the top of > >my head, two errors that keep coming back even years after are: > >- Comparing instances of (semantically) incomparable types (http:// > >www.ibm.com/developerworks/library/l-python-elegance-1.html). > >Thankfully this will be fixed in Py3k. > >- Strings being iterable; unfortunately this will stay in Py3K. > > I'll repeat the comment I made on python-3000: > > "...string iteration isn't about treating strings as sequences of > strings, it's about treating strings as sequences of characters. The > fact that characters are also strings is the reason we have problems, > but characters are strings for other good reasons." No, the reason we have problems is that far more often than not strings are treated as atomic values, not sequences of smaller strings or characters. A classic example is flatten(), where most people are surprised if flatten([1, (3.14, 'hello')]) returns [1, 3.14, 'h', 'e', 'l', 'l', 'o']. > Thing is, the fact that you can e.g. slice strings just like other > sequence types creates the consequence that you can also iterate over > strings -- moreover, some of us actually do iterate over strings (though > of course we could if necessary create lists/tuples of characters). In > the grand scheme of things, I rarely see people running into problems > with iterating over strings. One class of problems is functions such as flatten() that expect "a collection or an atom", with strings being typically considered atomic. A second common pitfall are functions that expect file-like objects but are given file names instead: def process_file(input_file): for line in input_file: do_stuff(line) process_file('/home/george/.bashrc') # oops I now try to remember to write such functions as: def process_file(input_file): if isinstance(input_file, basestring): input_file = open(input_file) for line in input_file: ... It's not a huge impediment by any means but it's certainly a gotcha. George From evan at yelp.com Tue Jun 26 17:14:27 2007 From: evan at yelp.com (Evan Klitzke) Date: Tue, 26 Jun 2007 14:14:27 -0700 Subject: Chroot Jail Not Secure for Sandboxing Python? In-Reply-To: <1182831792.579644.296820@q75g2000hsh.googlegroups.com> References: <1182748892.916068.146780@p77g2000hsh.googlegroups.com> <467f55f7$0$20850$9b622d9e@news.freenet.de> <1182782910.811850.284350@u2g2000hsc.googlegroups.com> <1182787116.717732.35390@q75g2000hsh.googlegroups.com> <1182831792.579644.296820@q75g2000hsh.googlegroups.com> Message-ID: On 6/25/07, gregpinero at gmail.com wrote: > On Jun 25, 11:58 am, Paul Boddie wrote: > > On 25 Jun, 16:48, "gregpin... at gmail.com" wrote: > > > > > > > > > I followed up with my ISP. Here's the answer I got: > > > > > The os.exec call prepends the chroot directory to the absolute path, > > > but does NOT provide chroot for the child process. However, as long > > > as the environment is maintained, which contains an LD_PRELOAD, the > > > "chroot" will also be maintained. If LD_PRELOAD is removed or > > > ignored, then the chroot is ineffective. > > > > So it appears that as long as LD_PRELOAD is set (possibly to link the > > process to some other libraries than is usually the case), any > > affected processes are effectively jailed. This doesn't really sound > > like a traditional chroot environment, though. > > > > > Another way of saying it is that every process is responsible for > > > providing and maintaining the chroot through the LD_PRELOAD variable. > > > Those processes only maintain the chroot if that variable remains set. > > > > Right. > > > > > The only solution that would bypass this problem altogether would be a > > > statically linked python. (is that possible?) It would have to be > > > statically linked to a custom-modified glibc to provide the virtual > > > chroot environment. > > > > Some solutions depend on linking to restricted libraries, and the Wiki > > page you referenced probably talks about them as well. I was thinking > > that if I were to attempt to properly sandbox any current version of > > CPython, I'd start off linking it to restricted libraries which > > provide compatible interfaces for things like opening file handles; > > then I'd put various policy controls in those libraries so that you > > can have some control over what your programs do. Finally, you'd have > > to stop arbitrary (extension) module loading in order to prevent > > programs importing some nice modules and getting round the controls: > > for example, importing socket or os to get access to file handles (or > > to process creation which might get around the controls as suggested > > above). Eventually, this arrives more or less at where Brett Cannon is > > supposed to be right now with his sandboxed Python, perhaps by a > > different route and with some different outcomes. > > It looks the like only option available to me right now is fakechroot, > which really doesn't sound like it's going to work. So I'm going to > give Bett Cannon's stuff (http://sayspy.blogspot.com/2007/05/i-have- > finished-securing-python.html) a try. To launch a child process in a chroot you can easily just fork and then make the chroot syscall in the child process immediately after the fork. -- Evan Klitzke From frank at chagford.com Mon Jun 11 06:10:43 2007 From: frank at chagford.com (Frank Millman) Date: Mon, 11 Jun 2007 03:10:43 -0700 Subject: Postpone creation of attributes until needed In-Reply-To: References: <1181553891.447344.109390@g4g2000hsf.googlegroups.com> Message-ID: <1181556643.693661.179280@g4g2000hsf.googlegroups.com> On Jun 11, 11:47 am, Phil Thompson wrote: > On Monday 11 June 2007 10:24 am, Frank Millman wrote: > > > Hi all > > > I have a small problem. I have come up with a solution, but I don't > > know if it is a) safe, and b) optimal. > > > I have a class with a number of attributes, but for various reasons I > > cannot assign values to all the attributes at __init__ time, as the > > values depend on attributes of other linked classes which may not have > > been created yet. I can be sure that by the time any values are > > requested, all the other classes have been created, so it is then > > possible to compute the missing values. > > > Properties... > > @property > def z(self): > return self.x * self.y > In my simple example I showed only one missing attribute - 'z'. In real life I have a number of them, so I would have to set up a separate property definition for each of them. With my approach, __getattr__ is called if *any* of the missing attributes are referenced, which seems easier and requires less maintenance if I add additional attributes. Another point - the property definition is called every time the attribute is referenced, whereas __getattr__ is only called if the attribute does not exist in the class __dict__, and this only happens once. Therefore I think my approach should be slightly quicker. Frank From borud-news at borud.no Fri Jun 22 10:52:28 2007 From: borud-news at borud.no (Bjorn Borud) Date: 22 Jun 2007 16:52:28 +0200 Subject: The Modernization of Emacs: terminology buffer and keybinding References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182272495.990807.99110@a26g2000pre.googlegroups.com> <87tzt3ihev.fsf@kobe.laptop> <1182370216.961241.6960@n60g2000hse.googlegroups.com> <85zm2ufjpb.fsf@lola.goethe.zz> <1182372592.803332.288260@u2g2000hsc.googlegroups.com> <1182373919.262388.100740@c77g2000hse.googlegroups.com> <85r6o6fhkb.fsf@lola.goethe.zz> <1182375045.626510.188170@m36g2000hse.googlegroups.com> <85myyufgwj.fsf@lola.goethe.zz> <1182375528.985142.293900@q69g2000hsb.googlegroups.com> Message-ID: [Robert Uhl ] | | Why should the ignorant decide? Do you leave the decision of what great | art is to 3 year olds and their doting parents? Do you leave the | decision of what great food is to the ignorant, unwashed, | McDonald's-devouring masses? Why then do you leave the decision of | what's a useful interface to those with insufficient experience? Robert does have a point; however, one needs to take into account that it is very difficult to judge the quality of an interface if it is one that is very familiar to you or if the inner workings are obvious to you. this is why programmers often make bad UI designers: we are intimately familiar with the inner workings, and to us it is okay if the UI is just a thin layer on top of a system we've made. (I'd say the web is a better showcase for this. there seems to be no end to the number of websites that have awkward interaction modes. nor do people seem particularly shy about adding "just one more" thing to an already crowded interface -- because they're blind to the wall of complexity it presents to the occasional user). editors like Emacs is not something which is designed for the casual user, so what the casual user thinks is irrelevant. (also note that the definition of "casual user" has changed). -Bj?rn From bscrivener42 at gmail.com Sat Jun 9 11:24:38 2007 From: bscrivener42 at gmail.com (BartlebyScrivener) Date: Sat, 09 Jun 2007 15:24:38 -0000 Subject: VIM editor question In-Reply-To: References: <1181393067.068779.265610@g4g2000hsf.googlegroups.com> Message-ID: <1181402678.897037.253470@h2g2000hsg.googlegroups.com> On Jun 9, 9:56 am, "Joe Riopel" wrote: > I use vim on both Windows and UNIX/Linux, and found this vimrc file.http://darksmile.net/software/.vimrc.html > > It's pretty good and has good comments. You might want to take a look > at that and customize it. > > Plus this is great:http://www.usf.uni-osnabrueck.de/infoservice/doc/localhtml/vim/if_pyt... This one also good, especially for those of us who sometimes wrap text: http://www.cs.cornell.edu/~djm/ubuntu/vimrc.txt From bj_666 at gmx.net Fri Jun 1 06:57:28 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Fri, 01 Jun 2007 12:57:28 +0200 Subject: c[:]() References: <1180504190.055427.173610@h2g2000hsg.googlegroups.com> <1180554872.3356.30.camel@dot.uniqsys.com> <465DF3DE.40404@cc.umanitoba.ca> <1180566831.239580.199300@m36g2000hse.googlegroups.com> <005401c7a31a$136f7fe0$240110ac@Muse> <135tobve86qj808@corp.supernews.com> <135tru124pie2b3@corp.supernews.com> <135tv1bjqgbmsc9@corp.supernews.com> <002801c7a3fb$56cc8030$240110ac@Muse> <9qudnbBRU9SHIcLbnZ2dnUVZ_rLinZ2d@speakeasy.net> Message-ID: In , Warren Stringer wrote: > I like your use case. Am I correct in assuming that `y = x[:]; y()` is NOT > to be found in working code? If that is the case, then nothing gets broken. > It would be instructive to have a use case where enabling c[:]() would break > existing code. What does "enabling c[:]()" mean? Do you expect after "enabling it" ``c()`` and ``c[:]()`` to be different for the same list or tuple `c`? > My use case is this: > > do(orchestra(score)).pickle() > do(orchestra(conductor)).sequence() This isn't a use case unless you also say what the involved objects are and what semantic you expect from this source snippet. Just guessing, but might the following do what you want without the need to make lists and tuples callable? def do(iterable, func): for item in iterable: func(item) do(orchestra(score), pickle) do(orchestra(conductor), sequence) Ciao, Marc 'BlackJack' Rintsch From tcrane at REMOVETHISuiuc.edu Tue Jun 12 15:58:04 2007 From: tcrane at REMOVETHISuiuc.edu (T. Crane) Date: Tue, 12 Jun 2007 19:58:04 GMT Subject: file open default location References: <1181655985.895174.116540@o11g2000prd.googlegroups.com><1181659712.584485.305780@d30g2000prg.googlegroups.com> Message-ID: "Gabriel Genellina" wrote in message news:mailman.9018.1181675163.32031.python-list at python.org... > En Tue, 12 Jun 2007 11:48:32 -0300, escribi?: >> On Jun 12, 9:09 am, "Richard Brodie" wrote: > >>> If you open a DOS window and run Python from there, it will write the >>> files >>> in whatever directory you were in when you typed the command. >>> >>> If you are running Python directly from Windows, or from an IDE, it's up >>> to the OS or the IDE to decide what your default directory is. Often it >>> will be the home directory from your user profile. >> >> Oops. My bad. I didn't know that the IDE behaved differently than the >> DOS window. > > You almost certainly use a shortcut to open the program, either in your > desktop or Start menu. Right click on it, choose Properties, Shortcut tab, > and see what it says for "Startup Directory" (or something like that). > That will be the original "current directory" when the program starts; but > it may be changed afterwards. AHA! thank you :) I checked the shortcut and NO start up directory was specified, which caused it for some reason to choose the K: drive. After specifying the startup directory it works as I want it to. thanks, trevis > -- > Gabriel Genellina > From no-sp at m-from.net Tue Jun 5 18:49:56 2007 From: no-sp at m-from.net (Giuseppe Di Martino) Date: Wed, 06 Jun 2007 00:49:56 +0200 Subject: PATH or PYTHONPATH under Windows ??? References: <90155$4665db45$d443bb3a$16812@news.speedlinq.nl> Message-ID: Il Tue, 05 Jun 2007 23:57:15 +0200, Stef Mientki ha scritto: > hello, > > after cleaning up a PC, Python can't find any libraries anymore. > But happily I've still one PC, where Python is running perfect. > Now I always read about the environment variable "PYTHONPATH". > But on neither PC there exists a "PYTHONPATH". > > On the PC that works ok, > there is the standard "PATH" environment variable, > and indeed there are all the Python Library references. > > Please enlighten me. > > thanks, > Stef Mientki Download pyrun.exe (http://developer.berlios.de/projects/pyrun) and copy it in your Python's folder; to exec python.exe use pyrun python or to exec script.py use pyrun python script.py Giuseppe From goldtech at worldpost.com Mon Jun 4 19:05:42 2007 From: goldtech at worldpost.com (leegold) Date: Mon, 04 Jun 2007 23:05:42 -0000 Subject: pythonwin closes unexpectedlyI In-Reply-To: <1180840891.765666.42000@j4g2000prf.googlegroups.com> References: <1180831832.591780.203780@q66g2000hsg.googlegroups.com> <1180840891.765666.42000@j4g2000prf.googlegroups.com> Message-ID: <1180998342.016945.301480@g4g2000hsf.googlegroups.com> snip... Slight off-topic fix for anyone whose search comes here: Recommend to patch ESRI application to newest update. You might also see error message: OLE error 0x80040212 http://support.esri.com/index.cfm?fa=knowledgebase.techarticles.articleShow&d=30524 gp.SetProduct("ArcView") is fix > > Steps to try: > > 1. Add > raise > after the print statement. > 2. Get pythonwin out of the equation; run your script from the command > line. > 3. If that doesn't give you a clue what the error is, remove the try/ > accept/GP.AddMessage.../print lines and run it again from the command > line. > > HTH, > John From moishyyehuda at gmail.com Thu Jun 7 12:41:55 2007 From: moishyyehuda at gmail.com (moishyyehuda at gmail.com) Date: Thu, 07 Jun 2007 16:41:55 -0000 Subject: updating db with csv Message-ID: <1181234515.502945.43770@q66g2000hsg.googlegroups.com> #1 If any one familiar with godaddy hosting. They have apparently have a hosing server i.e.(scripts, html files etc.), and a server for databases. How can I import from my script, with a csv. if the db is on a different server than the script server. #2 I would like to update and insert with the same csv file. Is there a way to tell the database for some lines to update, and for some lines to insert. From nejtak... Tue Jun 26 16:33:07 2007 From: nejtak... (Troels Thomsen) Date: Tue, 26 Jun 2007 22:33:07 +0200 Subject: ironpython exception line number Message-ID: <46817805$0$25410$edfadb0f@dread11.news.tele.dk> Hello , When an exeption occurs in a IronPython executet script, and I print the sys.exc , i get something ugly like the example below. How can I get the fileName and line number? Thx in advance Troels 26-06-2007 13:19:04 : IronPython.Runtime.Exceptions.PythonIndentationError: unexpected token def ved IronPython.Compiler.SimpleParserSink.AddError(String path, String message, String lineText, CodeSpan span, Int32 errorCode, Severity severity) ved IronPython.Compiler.CompilerContext.AddError(String message, String lineText, Int32 startLine, Int32 startColumn, Int32 endLine, Int32 endColumn, Int32 errorCode, Severity severity) ved IronPython.Compiler.Parser.ReportSyntaxError(Location start, Location end, String message, Int32 errorCode) ved IronPython.Compiler.Parser.ReportSyntaxError(Token t, Int32 errorCode, Boolean allowIncomplete) ved IronPython.Compiler.Parser.ParseSuite() ved IronPython.Compiler.Parser.ParseFuncDef() ved IronPython.Compiler.Parser.ParseStmt() ved IronPython.Compiler.Parser.ParseSuite() ved IronPython.Compiler.Parser.ParseClassDef() ved IronPython.Compiler.Parser.ParseStmt() ved IronPython.Compiler.Parser.ParseFileInput() ved IronPython.Hosting.PythonEngine.Compile(Parser p, Boolean debuggingPossible) ved IronPython.Hosting.PythonEngine.CompileFile(String fileName) ved IronPython.Hosting.PythonEngine.ExecuteFile(String fileName) From steve at laniels.org Wed Jun 27 08:02:21 2007 From: steve at laniels.org (Stephen R Laniel) Date: Wed, 27 Jun 2007 08:02:21 -0400 Subject: PEP 3107 and stronger typing (note: probably a newbie question) In-Reply-To: <46824d8d$0$2324$426a74cc@news.free.fr> References: <1182369568.941307.316260@p77g2000hsh.googlegroups.com> <5dveb4F360un0U1@mid.individual.net> <467a9209$0$22165$426a74cc@news.free.fr> <1182858785.886469.93060@n60g2000hse.googlegroups.com> <46824d8d$0$2324$426a74cc@news.free.fr> Message-ID: <20070627120212.GC15675@slaniel-laptop.itasoftware.com> On Wed, Jun 27, 2007 at 01:44:17PM +0200, Bruno Desthuilliers wrote: > Indeed - static typing is for compilers, not for programmers. When done well, static typing helps the programmer -- just like writing good unit tests. It's not a magic bullet, but it can help. I'd like to point again to Mark-Jason Dominus's explanation of how strong static typing can be done well: http://perl.plover.com/yak/typing/notes.html The example toward the end of how ML actually spots an infinite loop at compile time seems to me to be "for programmers" rather than "for compilers." -- Stephen R. Laniel steve at laniels.org Cell: +(617) 308-5571 http://laniels.org/ PGP key: http://laniels.org/slaniel.key From bdesth.quelquechose at free.quelquepart.fr Sat Jun 30 01:06:12 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sat, 30 Jun 2007 07:06:12 +0200 Subject: ORM layer In-Reply-To: References: Message-ID: <46857432$0$24675$426a74cc@news.free.fr> David a ?crit : > I am looking for an ORM for Python that fulfills a few simple needs. > > - ability to support a number of backends (probably mysql and sqlite > at present, csv a bonus) I didn't knew csv was a relational database. > - ability to be used easily from console python scripts, a bonus if I > can add a simple web GUI later using some framework > - decent documentation a definite plus > > I do not need: > > - massively complex joins (I could write these myself if needed) > - something engineered for hundreds of tables, I have only a few and > don't need overkill > > Any recommendations? The best hi-level RDBMS integration package in Python is probably SQLAlchemy. I say "hi-level RDBMS integration" because it's much more than an ORM. It's already used by some web applications (Trac amongst other) and frameworks (Pylons, Turbogears, ...) and the documentation is more than correct. So it matches most of your specs. OTHO, while fairly usable, it's not the simplest system around - even if some extensions like Elixir try to make things simpler-, so you may also want to have a look at other packages like SQLObject. > David From horpner at yahoo.com Sun Jun 17 08:05:52 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Sun, 17 Jun 2007 12:05:52 GMT Subject: Python's "only one way to do it" philosophy isn't good? References: <1181368143.874341.273140@r19g2000prf.googlegroups.com> <1hzrsp4.7vjuav1aegg0tN%aleax@mac.com> <7SSci.35627$G23.1695@newsreading01.news.tds.net> <7xejkb23fe.fsf@ruckus.brouhaha.com> <6dXci.35643$G23.6531@newsreading01.news.tds.net> <7xr6obmg7c.fsf@ruckus.brouhaha.com> Message-ID: On 2007-06-17, Paul Rubin wrote: > Neil Cerutti writes: >> I don't know that much about ML. I know is does a really nice job >> of generic containers, as does C++. But can it 'foo' any type as >> easily as C++? >> >> template T foo(T); > > I don't know enough C++ to understand what the above means > exactly, It means that foo can take an object of any type, T, as a parameter, and returns an object of type T. > but I think the answer is approximately "yes". I actually > don't know ML either, so I'm thinking in terms of Haskell types > which are similar. The following academic paper seems to be exactly what we're looking for: A comparitive study of language support for generic programming http://faculty.cs.tamu.edu/jarvi/papers/cmp_gp.pdf According to the paper, ML have a similar level of support for generic programming, though in C++ three of the eight features must be provided in code with template meta-programming. -- Neil Cerutti From steve at holdenweb.com Mon Jun 25 11:34:34 2007 From: steve at holdenweb.com (Steve Holden) Date: Mon, 25 Jun 2007 11:34:34 -0400 Subject: How to save initial configuration? (program installation) In-Reply-To: <1182784231.530101.258640@q75g2000hsh.googlegroups.com> References: <1182783746.718276.209460@w5g2000hsg.googlegroups.com> <1182784231.530101.258640@q75g2000hsh.googlegroups.com> Message-ID: kyosohma at gmail.com wrote: > On Jun 25, 10:02 am, Jason Zapman II wrote: >> I've written a program. To install this program, I'm going to need to >> initialize some stuff for the users environment, specifically the name/ >> location of an internal state file. >> >> Currently, I'm hard coding the location of this file, but that's in- >> elegant. What I'd like to do is just ask the user, with a suggested >> default. >> >> My question is how do I save this answer? It's kind of a chicken-and- >> egg problem. >> >> The only solution I've thought of is to write something that's self >> modifying, but that's ugly (go in, grep for this variable >> initialization, re-write that line with the new value, quit). Is >> there a better way to do this? There almost has to be... >> >> If not, are there some 'best practices' on how to do the self- >> modification? >> >> Thanks for any help; >> Jason > > I would think you could pop-up some dialog when the program is first > run to ask where they want the file to be. On the first run though, > you can just have the config file located in the current working > directory with the script file itself. Then just move it or save a new > copy to the new location and delete the original. > > Mike > Or, better still, leave it in place to act as the defaults for the next user who wants to start using this package? regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From david at boddie.org.uk Thu Jun 28 18:54:37 2007 From: david at boddie.org.uk (David Boddie) Date: Fri, 29 Jun 2007 00:54:37 +0200 Subject: Memory leak in PyQt application Message-ID: <200706290054.37858.david@boddie.org.uk> On Thu Jun 28 19:21:36 CEST 2007, Alexander Eisenhuth wrote: > I've a memory leak in a PyQt application and no idea how to find it. What > happens in the application ? > > From QWindow a QDialog is called on a button "pressed()" signal, that > instantiate a QThread and waits for it. If the thread has finished, the > QDialog closes. Do you delete the dialog when you close it? Did you create it with a parent object? > I've stipped down everything that nothing more happens (to me obviously). > Boost.Python is used to wrap a C++ Lib (used in the thread). Every time > memory usage increases for ~70 KB. > > Sometimes the application crash on closing QWindow. (QtCore.dll) > > - One thing I ask me is weather garbage collection is done in the PyQt main > loop? Some objects will be garbage collected but others may will be kept around if they are used from C++. > What hints do you have to find the leak? You may need to show us some of your code so that we can see exactly what you're doing. If you can post the stripped down example you have here, we can take a look at it. David From horpner at yahoo.com Sun Jun 17 06:41:50 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Sun, 17 Jun 2007 10:41:50 GMT Subject: Goto References: <1181762459.749538.151730@z28g2000prd.googlegroups.com> Message-ID: On 2007-06-17, Tina I wrote: > Back then I took a course in structured BASIC programming (now > there is a contradiction in terms) and the instructor warned > about goto time and time again. But his biggest mistake was to > tell us that if we had to use goto at least we should explain > it in a comment. So we would turn in programs with sections > like: > > 100 IF S$="YES" THEN GOTO 150 > 110 REM Go to line 150 if S$ is Yes Once I learned GOSUB (in Commodore BASIC) I used it instead of GOTO all the time. I used it for functions long before I learned about functions in Programming 101. 100 NAME$="TED" 110 AGE=40 120 GOSUB 1000 1000 PRINT NAME$, " IS ", AGE, " YEAR(S) OLD." 1010 RETURN Named functions are so much nicer than numbered ones. -- Neil Cerutti From gherron at islandtraining.com Thu Jun 7 17:13:00 2007 From: gherron at islandtraining.com (Gary Herron) Date: Thu, 07 Jun 2007 14:13:00 -0700 Subject: How does os.walk work? In-Reply-To: <1181249728.519175.305290@q66g2000hsg.googlegroups.com> References: <1181249728.519175.305290@q66g2000hsg.googlegroups.com> Message-ID: <466874DC.7020800@islandtraining.com> gregpinero at gmail.com wrote: > In the example from help(os.walk) it lists this: > > 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 > > What I'm wondering is how does the "dirs.remove('CVS')" line prevent > os.walk from visiting that directory? how does the walk function know > what you do to the dirs variable? I tried looking at the code in > os.py but it wasn't clear to me there either. > Simple: os.walk builds the list to contain all the subdirectories. After giving you a chance to modify that list, ow.walk then goes through the list (whatever contents it has at that point) and visits any subdirectory. I'd guess your trouble with understanding this has to do with wondering how the modified list gets from your code back to os.walk. But in fact they are not two separate lists, but one list, passed by reference from os.walk into your code. Gary Herron > Thanks, > > Greg > > From kinch1967 at gmail.com Sun Jun 10 06:58:44 2007 From: kinch1967 at gmail.com (bullockbefriending bard) Date: Sun, 10 Jun 2007 03:58:44 -0700 Subject: matching objects by a tuple field criterion Message-ID: <1181473124.790391.293120@r19g2000prf.googlegroups.com> i have a large collection of python objects, each of which contains an integer 6-tuple as part of its data payload. what i need to be able to do is select only those objects which meet a simple tuple element wildcard matching criterion. e.g. given the following python objects: object A includes tuple (1,2,3,4,5,6) object B includes tuple (1,4,4,4,11,1) object C includes tuple (1,3,9,1,1,1) all tuples are unique. for what it's worth, the values in each field are independent of the other fields and range from 1 to 14. although 'large', my collection is sparse cf. the 14^6 possible tuples. i want to search on *one only* tuple field/value. if my search criterion is (*,*,*,4,*,*), then i want to find object A and object B. if (1,*,*,*,*,*), i want to find objects A, B, and C, etc. i will only ever specify an integer match for one tuple field. i can think of some naive approaches, but is there an elegant way to do this? From enleverlesX.XmcX at XmclaveauX.com Mon Jun 4 07:38:57 2007 From: enleverlesX.XmcX at XmclaveauX.com (Méta-MCI) Date: Mon, 4 Jun 2007 13:38:57 +0200 Subject: Python, Dutch, English, Chinese, Japanese, etc. References: Message-ID: <4663fe2a$0$5068$ba4acef3@news.orange.fr> Et le klingon ? Please, don't forget klingons SVP, n'oubliez pas les klingons ;o) From S.Mientki-nospam at mailbox.kun.nl Fri Jun 22 15:28:18 2007 From: S.Mientki-nospam at mailbox.kun.nl (Stef Mientki) Date: Fri, 22 Jun 2007 21:28:18 +0200 Subject: configparser shuffles all sections ? In-Reply-To: References: Message-ID: <12a8b$467c21b3$d443bb3a$28298@news.speedlinq.nl> Nick Craig-Wood wrote: > stef wrote: >> I just used configparser for the first time and discovered that it >> shuffled all my sections, >> and the contents of the sections too. >> >> This makes human manipulation of the file impossible. >> >> Is there a way to prevent this shuffling, > > You could try getting yourself an ordered dictionary implmentation, > say > > http://www.voidspace.org.uk/python/odict.html > > Then doing something like this (untested) > > class MyConfigParser(SafeConfigParser): > def __init__(self, defaults=None): > SafeConfigParser.__init__(defaults) > self._sections = odict() > self._defaults = odict() > This might be good alternative, I'll check that. thank you all for the answers, it's always good to know that I've not missed the simple solution ;-) cheers, Stef Mientki From exarkun at divmod.com Tue Jun 26 17:02:59 2007 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Tue, 26 Jun 2007 17:02:59 -0400 Subject: Non-blocking keyboard read In-Reply-To: <468178FC.8000706@shopzeus.com> Message-ID: <20070626210259.4947.526591444.divmod.quotient.4539@ohm> On Tue, 26 Jun 2007 22:37:16 +0200, Laszlo Nagy wrote: >pinkfloydhomer at gmail.com wrote: >> I am writing a curses application, but the getch() does not seem to >> give me all I want. Of course, if I press "d", it returns an ord("d") >> and so on. But I want to be able to detect whether alt, shift or ctrl >> has been pressed also. Shift is normally covered by returning an >> uppercase character instead and ctrl seems to return control codes (as >> is normal, I guess), but alt I can't detect with getch, it seems. >> >> Preferably, I would like one of two things: >> >> 1) Having a getch() (or other function) that returns a code like now, >> but with different codes depending on the status of the ctrl, alt or >> shift keys, for instance by setting higher bits or something. Just as >> long as I can differentiate between "d", "D", ctrl+"d", alt+"d", shift >> +"d" and maybe ctrl+alt+"d" and ctrl+shift+"d" etc. >> >You can try to combine select.select with sys.stdin. I have never tried >this, but it is my platform independent idea. select won't work on stdin on windows, and it won't work to read anything less than a line on posix either, unless you put the pty into unbuffered mode first (but then it will work). Twisted has a more abstract API for this kind of thing which works on POSIX and Windows which might be worth investigating. Take a look at stdin.py and stdiodemo.py, linked from http://twistedmatrix.com/projects/core/documentation/examples/ Jean-Paul From aahz at pythoncraft.com Sat Jun 16 12:00:21 2007 From: aahz at pythoncraft.com (Aahz) Date: 16 Jun 2007 09:00:21 -0700 Subject: Want to learn Python References: <1181907696.878873.214760@i13g2000prf.googlegroups.com> <1181950960.793735.304570@c77g2000hse.googlegroups.com> Message-ID: In article <1181950960.793735.304570 at c77g2000hse.googlegroups.com>, 7stud wrote: > >I am of the opposite opinion: I recommend that people get any book but >"Beginning Python: Novice to Professional". In my opinion, that book >is horribly written, the examples are terrible, some subjects are only >covered in passing so the info is too parse to be of any use, and >there are no problems at the end of the chapters to work on. I think >a beginner might be fooled into thinking Beginning Python is a good >book because they won't know how many holes their knowledge of python >is riddled with, and since there are no problems to work on, they may >not even realize how little they learned. I think an experienced >programmer would spot all the blunders in the book straight away. I'm curious, have you tried _Python for Dummies_? I don't want to be shilling my own book -- but I'd also like to know how it stacks up. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "as long as we like the same operating system, things are cool." --piranha From evan at yelp.com Wed Jun 27 02:43:36 2007 From: evan at yelp.com (Evan Klitzke) Date: Tue, 26 Jun 2007 23:43:36 -0700 Subject: Set builtin lookups Message-ID: I have a question about the internal representation of sets in Python. If I write some code like if x in some_list: do_something() the lookup for the in statement is O(n), where n is the number of elements in the list. Is this also true if I am using a set or are sets represented by a hash table? -- Evan Klitzke From jeff.self at gmail.com Wed Jun 27 10:04:52 2007 From: jeff.self at gmail.com (jeffself) Date: Wed, 27 Jun 2007 14:04:52 -0000 Subject: Getting importError: No module named _md5 Message-ID: <1182953092.454946.321760@k29g2000hsd.googlegroups.com> I'm running Python 2.5.1 which I'm getting from the MacPort package system. I just installed Django and tried to start up the Django server and I got the following error: ImportError: No module named _md5 I'm pretty sure this is a python problem, not Django problem. I'm looking in the python2.5 directory and I see md5.py, md5.pyc and md5.pyo files. Any suggestions? From horpner at yahoo.com Wed Jun 13 21:28:27 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Thu, 14 Jun 2007 01:28:27 GMT Subject: Method much slower than function? References: <1181781612.939800.238890@q19g2000prn.googlegroups.com> Message-ID: <%Q0ci.35541$G23.26580@newsreading01.news.tds.net> On 2007-06-14, idoerg at gmail.com wrote: > Hi all, > > I am running Python 2.5 on Feisty Ubuntu. I came across some code that > is substantially slower when in a method than in a function. > > ################# START SOURCE ############# > # The function > > def readgenome(filehandle): > s = '' > for line in filehandle.xreadlines(): > if '>' in line: > continue > s += line.strip() > return s > > # The method in a class > class bar: > def readgenome(self, filehandle): > self.s = '' > for line in filehandle.xreadlines(): > if '>' in line: > continue > self.s += line.strip() > > ################# END SOURCE ############## > When running the function and the method on a 20,000 line text file, I > get the following: > >>>> cProfile.run("bar.readgenome(open('cb_foo'))") > 20004 function calls in 10.214 CPU seconds > > Ordered by: standard name > > ncalls tottime percall cumtime percall > filename:lineno(function) > 1 0.000 0.000 10.214 10.214 :1() > 1 10.205 10.205 10.214 10.214 reader.py:11(readgenome) > 1 0.000 0.000 0.000 0.000 {method 'disable' of > '_lsprof.Profiler' objects} > 19999 0.009 0.000 0.009 0.000 {method 'strip' of 'str' > objects} > 1 0.000 0.000 0.000 0.000 {method 'xreadlines' of > 'file' objects} > 1 0.000 0.000 0.000 0.000 {open} > > >>>> cProfile.run("z=r.readgenome(open('cb_foo'))") > 20004 function calls in 0.041 CPU seconds > > Ordered by: standard name > > ncalls tottime percall cumtime percall > filename:lineno(function) > 1 0.000 0.000 0.041 0.041 :1() > 1 0.035 0.035 0.041 0.041 reader.py:2(readgenome) > 1 0.000 0.000 0.000 0.000 {method 'disable' of > '_lsprof.Profiler' objects} > 19999 0.007 0.000 0.007 0.000 {method 'strip' of 'str' > objects} > 1 0.000 0.000 0.000 0.000 {method 'xreadlines' of > 'file' objects} > 1 0.000 0.000 0.000 0.000 {open} > > > The method takes > 10 seconds, the function call 0.041 seconds! > > Yes, I know that I wrote the underlying code rather > inefficiently, and I can streamline it with a single > file.read() call instead if an xreadlines() + strip loop. > Still, the differences in performance are rather staggering! > Any comments? It is likely the repeated attribute lookup, self.s, that's slowing it down in comparison to the non-method version. Try the following simple optimization, using a local variable instead of an attribute to build up the result. # The method in a class class bar: def readgenome(self, filehandle): s = '' for line in filehandle.xreadlines(): if '>' in line: continue s += line.strip() self.s = s To further speed things up, think about using the str.join idiom instead of str.+=, and using a generator expression instead of an explicit loop. # The method in a class class bar: def readgenome(self, filehandle): self.s = ''.join(line.strip() for line in filehandle) -- Neil Cerutti From andreengels at gmail.com Mon Jun 11 10:53:39 2007 From: andreengels at gmail.com (Andre Engels) Date: Mon, 11 Jun 2007 16:53:39 +0200 Subject: skip next item in list In-Reply-To: <1181573389.186279.108590@g37g2000prf.googlegroups.com> References: <1181573389.186279.108590@g37g2000prf.googlegroups.com> Message-ID: <6faf39c90706110753w7522c4f9q2f912495f56a19a8@mail.gmail.com> 2007/6/11, ahlongxp : > list=('a','d','c','d') > for a in list: > if a=='a' : > #skip the letter affer 'a' > > what am I supposed to do? There might be better ways to do it, but I would do: flag_last_a = False for a in list: if flag_last_a: flag_last_a = False continue if a=='a': flag_last_a = True # Whatever is done when you don't skip -- Andre Engels, andreengels at gmail.com ICQ: 6260644 -- Skype: a_engels From gherzig at fmed.uba.ar Fri Jun 1 07:55:22 2007 From: gherzig at fmed.uba.ar (Gerardo Herzig) Date: Fri, 01 Jun 2007 08:55:22 -0300 Subject: Delete a file from a CGI In-Reply-To: References: Message-ID: <4660092A.7070602@fmed.uba.ar> When you execute a cgi, the program runs under the "apache user" (ussualy www or wwwrun or so), so THAT user needs permissions for deleting the file. Other approach could be suid'ing the cgi program. Gerardo >HI! > >I want to delete a file from a CGI, but I always get a Permission denied >error. > >I've tryed this after creating the file (from a normal script): > >os.chmod(".lock",stat.S_IMODE(stat.S_IRWXU | stat.S_IRWXO | stat.S_IRWXG)) >os.chown(".lock",pwd.getpwnam("nobody")[2],pwd.getpwnam("nobody")[3]) > >but the CGI still can't delete the file. > >I will appreciate very much your help. > >Thanks a lot. > > > > From max at alcyone.com Fri Jun 1 02:26:33 2007 From: max at alcyone.com (Erik Max Francis) Date: Thu, 31 May 2007 23:26:33 -0700 Subject: c[:]() In-Reply-To: References: <1180504190.055427.173610@h2g2000hsg.googlegroups.com> <1180554872.3356.30.camel@dot.uniqsys.com> <465DF3DE.40404@cc.umanitoba.ca> <1180566831.239580.199300@m36g2000hse.googlegroups.com> <005401c7a31a$136f7fe0$240110ac@Muse> <135tobve86qj808@corp.supernews.com> <135tru124pie2b3@corp.supernews.com> <135tv1bjqgbmsc9@corp.supernews.com> <002801c7a3fb$56cc8030$240110ac@Muse> Message-ID: <9qudnbBRU9SHIcLbnZ2dnUVZ_rLinZ2d@speakeasy.net> Warren Stringer wrote: > `c[:]()` is unambiguous because: > > def c(): print 'yo' > > c() # works, but > c[:]() # causes: > > Traceback (most recent call last)... > c[:]() # causes: > TypeError: unsubscriptable object > > There are many `c()` to be found in the wild and no `c[:]()`, thus > unambiguous. To be honest, I wasn't sure, until testing this, just now. >>> c = 'not quite' >>> c[:] 'not quite' >>> c[:]() Traceback (most recent call last): File "", line 1, in ? TypeError: 'str' object is not callable You also seem to be under the impression that `x[:]()` is somehow special syntax that is treated differently than `y = x[:]; y()`. It is not. Besides, _ambiguity_ was never the problem. _Functionality_ is the problem. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM, Y!M erikmaxfrancis To endure what is unendurable is true endurance. -- (a Japanese proverb) From eadmund42 at NOSPAMgmail.com Sat Jun 23 01:32:43 2007 From: eadmund42 at NOSPAMgmail.com (Robert Uhl) Date: Fri, 22 Jun 2007 23:32:43 -0600 Subject: The Modernization of Emacs: terminology buffer and keybinding References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182272495.990807.99110@a26g2000pre.googlegroups.com> <87tzt3ihev.fsf@kobe.laptop> <1182370216.961241.6960@n60g2000hse.googlegroups.com> <85zm2ufjpb.fsf@lola.goethe.zz> <1182372592.803332.288260@u2g2000hsc.googlegroups.com> <1182373919.262388.100740@c77g2000hse.googlegroups.com> <85r6o6fhkb.fsf@lola.goethe.zz> <1182375045.626510.188170@m36g2000hse.googlegroups.com> <1182453375.531950.141460@m36g2000hse.googlegroups.com> <1182535516.594974.243910@q69g2000hsb.googlegroups.com> Message-ID: Falcolas writes: > >> It's Mac OS and Windows which are inconsistent. Emacs has been >> around since they were mere glimmers in the eye of Jobs & Gates... > > Inconsistent? I would have to disagree. They changed paradigms - > terminal text based interfaces to GUIs. You wouldn't expect a piece of > software built for a terminal to be backwards compatibility to punch > card interfaces, would you? Why would a GUI based program limit itself > to functionality as defined by a terminal application? You're making the assumption that Mac OS in 1984 offered some textual capability (textual, since we're discussing text editing) which emacs did not. It didn't. -- Robert Uhl A: Top posting Q: What's the most annoying thing about Usenet? From danb_83 at yahoo.com Wed Jun 27 21:20:47 2007 From: danb_83 at yahoo.com (Dan Bishop) Date: Wed, 27 Jun 2007 18:20:47 -0700 Subject: How can I 'compound' streams? In-Reply-To: References: Message-ID: <1182993647.727276.29090@w5g2000hsg.googlegroups.com> On Jun 27, 7:40 pm, XiaQ wrote: > I need to build a stream that writes to stdout and a file at the same > time. Is there already a function in the Python library to do this? class FileAndStdout(file): def write(self, data): file.write(self, data) sys.stdout.write(data) From aleax at mac.com Wed Jun 20 00:37:54 2007 From: aleax at mac.com (Alex Martelli) Date: Tue, 19 Jun 2007 21:37:54 -0700 Subject: Permutation over a list with selected elements References: <1182238025.739189.208970@a26g2000pre.googlegroups.com> Message-ID: <1hzz4a8.13g72fy1tvbckgN%aleax@mac.com> weidongtom at gmail.com wrote: > Hi, > > I have been working at this problem, and I think I need a permutation > algorithm that does > the following: > > Given a list of elements that are either a character or a character > follows by a number, e.g. > > ['a', 'b', 'c1', 'd', 'e1', 'f', 'c2', 'x', 'e2'] > > find all the permutations that are given by switching the positions of > the elements that: > (1) begins with the same letter, and > (2) follows by a number. > > With the above list, some possible permutations are: > > ['a', 'b', 'c2', 'd', 'e1', 'f', 'c1', 'x', 'e2'] > ['a', 'b', 'c1', 'd', 'e2', 'f', 'c2', 'x', 'e1'] > ['a', 'b', 'c2', 'd', 'e2', 'f', 'c1', 'x', 'e1'] > > Can anyone help me out? Thanks in advance. I would proceed in 2 steps: 1. find all the sets of indices that are to be permuted 2. produce all the permutations given said sets Now (1) is pretty easy: import collections def find_sets_of_indices_to_permute(L): set_by_letter = collections.defaultdict(list) for i, elem in enumerate(L): if len(elem)>1: set_by_letter[elem[0]].append(i) return set_by_letter.values() For (2), it looks like we need 2 sub-steps: 2.1. do all permutations of a list given ONE set of indices to permute 2.2. apply the function sub (2.1) to all the sets of indices to permute let's do 2.1 the lazy way, i.e., recursively: def all_permutations_given_indices(L, indices): yield L if len(indices) < 2: return x = indices.pop() pivot = L[x] for y in indices: L[x] = L[y] L[y] = pivot for permut in all_permutations_given_indices(L, indices): yield permut L[y] = L[x] L[x] = pivot indices.append(x) This suggests doing 2.2 recursively as well: def all_permutations_with_constraints(L, constraints): if len(constraints) == 1: for p in all_permutations_given_indices(L, constraints[0]): yield L return indices = constraints.pop() for p in all_permutations_given_indices(L, indices): for pp in all_permutations_with_constraints(p, constraints): yield pp constraints.append(indices) and, putting it all together: def do_it_all(L): sets_of_indices = find_sets_of_indices_to_permute(L) for p in all_permutations_with_constraints(L, sets_of_indices): print p Applied to your example list, this gives: brain:~ alex$ python cp.py ['a', 'b', 'c1', 'd', 'e1', 'f', 'c2', 'x', 'e2'] ['a', 'b', 'c2', 'd', 'e1', 'f', 'c1', 'x', 'e2'] ['a', 'b', 'c1', 'd', 'e2', 'f', 'c2', 'x', 'e1'] ['a', 'b', 'c2', 'd', 'e2', 'f', 'c1', 'x', 'e1'] Warning: untested beyond this single run, and _definitely_ not optimal in either clarity, style, or speed -- just a quick hack to get you started. Alex From sjdevnull at yahoo.com Thu Jun 14 14:49:53 2007 From: sjdevnull at yahoo.com (sjdevnull at yahoo.com) Date: Thu, 14 Jun 2007 11:49:53 -0700 Subject: Method much slower than function? In-Reply-To: <7xtztbdstq.fsf@ruckus.brouhaha.com> References: <1181781612.939800.238890@q19g2000prn.googlegroups.com> <1181795969.141307.94140@i13g2000prf.googlegroups.com> <7xtztbdstq.fsf@ruckus.brouhaha.com> Message-ID: <1181846993.626541.160760@q19g2000prn.googlegroups.com> On Jun 14, 1:10 am, Paul Rubin wrote: > "sjdevn... at yahoo.com" writes: > > take virtually the same amount of time on my machine (2.5), and the > > non-join version is clearer, IMO. I'd still use join in case I wind > > up running under an older Python, but it's probably not a big issue here. > > You should not rely on using 2.5 I use generator expressions and passed-in values to generators and other features of 2.5. Whether or not to rely on a new version is really a judgement call based on how much time/effort/money the new features save you vs. the cost of losing portability to older versions. > or even on that optimization staying in CPython. You also shouldn't count on dicts being O(1) on lookup, or "i in myDict" being faster than "i in myList". A lot of quality of implementation issues outside of the language specification have to be considered when you're worried about running time. Unlike fast dictionary lookup at least the += optimization in CPython is specified in the docs (as well as noting that "".join is greatly preferred if you're working across different versions and implementations). > Best is to use StringIO or something comparable. Yes, or the join() variant. From lew at lewscanon.nospam Thu Jun 21 11:11:32 2007 From: lew at lewscanon.nospam (Lew) Date: Thu, 21 Jun 2007 11:11:32 -0400 Subject: The Modernization of Emacs In-Reply-To: <87k5tx7444.fsf@W0053328.mgh.harvard.edu> References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182344981.372713.298580@w5g2000hsg.googlegroups.com> <86y7ieoiv7.fsf@lola.quinscape.zz> <1182347061.347199.133480@g4g2000hsf.googlegroups.com> <874pl2eg2j.fsf@W0053328.mgh.harvard.edu> <1182370016.986915.202150@u2g2000hsc.googlegroups.com> <87k5tx7444.fsf@W0053328.mgh.harvard.edu> Message-ID: Joel J. Adamson wrote: > My point is that I'm the sort of person that has a mind set up for > Emacs. I had none of the difficulties that someone else might have, > who's used to other kinds of software. > > However, I'll also point out that my wife has used Emacs a couple > times, and she's never done more than point and click with a computer, > and she's had no frustration whatsoever. A new user of two hours' experience. A father of a six-year old whose child hums along happily with emacs. A computer widow who "had no frustration whatsoever" with it. To the claim that "emacs is too hard for the beginner" we have a mounting pile of steaming evidence that refutes. It may still be true that it is too hard for some beginners, but then again the power cord can be too hard for some people. (I used to help customers find the Big Red Switch when they first got a computer. There were many who needed it.) To the claim that emacs has arcane keystrokes comes the evidence that modern revs have "normal" keystrokes like right-arrow, F1, Ctrl-End. To the claim that the help is too hard to use comes the evidence that three simple keystroke patterns are all one needs to know, and anecdotal evidence of the help system's utility. Some will refuse to face the truth. To the open-minded, let the facts speak for themselves. I bet Xah Les is all over smiles about how well his controversy bloomed. -- Lew From paul.nospam at rudin.co.uk Mon Jun 11 14:46:51 2007 From: paul.nospam at rudin.co.uk (Paul Rudin) Date: Mon, 11 Jun 2007 19:46:51 +0100 Subject: Repository - file scanner References: <1181331239.609059.320740@g4g2000hsf.googlegroups.com> <1181515276.379978.136400@z28g2000prd.googlegroups.com> <1181581520.733087.253380@q66g2000hsg.googlegroups.com> Message-ID: <87zm36uy5g.fsf@rudin.co.uk> HMS Surprise writes: >> >> Why not use grep? > > With Windows XP? www.cygwin.com From paddy3118 at googlemail.com Sat Jun 23 05:16:08 2007 From: paddy3118 at googlemail.com (Paddy) Date: Sat, 23 Jun 2007 09:16:08 -0000 Subject: Collections of non-arbitrary objects ? In-Reply-To: <1182559502.069773.321620@i38g2000prf.googlegroups.com> References: <1182449993.223262.229500@z28g2000prd.googlegroups.com> <87k5twx4hf.fsf@benfinney.id.au> <1182559502.069773.321620@i38g2000prf.googlegroups.com> Message-ID: <1182590168.597299.216540@w5g2000hsg.googlegroups.com> On Jun 23, 1:45 am, walterbyrd wrote: > On Jun 21, 5:38 pm, Ben Finney > wrote: > > > That's a flippant response, but I don't understand the question. > > Everybody here seems to have about the same response: "why would you > ever want to do that?" > > Maybe it's something that doesn't "need" to be done, but it seems to > me that would give you a certain level of built-in integrity - you > could be sure about what's in the structure. I would not expect that > all of python would be that rigid, but I thought it might be > worthwhile if there were one such structure. > > Think of this: why use tuples when lists are available? You can use a > tuple to index a dictionary, but not a list - why? I the answer may > be that sometimes you want some degree on inherent enforced structure. > I'm sure the language could have designed to allow lists to index > dictionary, but you would have to awfully careful with those lists. > The burden would be on the programmer to make certain that those lists > didn't change. But, it could be done, therefore tuples are not > "needed" right? > > Languages like C are often criticized as being too rigid - you have to > pre-define your variables, and pre-allocate your array sizes. But, > languages like Perl and BASIC, are often criticized as being to > sloppy - too few restrictions tend to lead to sloppy code. So I guess > there is a sort of trade-off. > > I suppose I could use a database, that might give me some degree of > assured integrity - depending on what database I used. Hi Walterbyrd, What happens when you are given good advice that may be contrary to intuition? Unfortunately its how we usually do things in Python and do NOT suffer because of it. Try writing your application without it. Test without it. Write other applications without it. Others do, successfully. - Paddy. From sc0rp at hot.pl Sat Jun 23 18:47:45 2007 From: sc0rp at hot.pl (Jacek Trzmiel) Date: Sun, 24 Jun 2007 00:47:45 +0200 Subject: database design help In-Reply-To: <467D9E64.70803@bryant.edu> References: <467D9E64.70803@bryant.edu> Message-ID: <467DA311.5060300@hot.pl> Hi, Brian Blais wrote: > I am trying to design a system for people to submit a series of documents to a > project. I want users to have the ability to submit updates to any documents, so > that there should be a history (or sequence) for each document. [...] > project1: > document 1, document 1a, document 1b > document 2 > document 3, document 3a > > project 2: > document 4, document 4a > > etc... > > I want to be able to query the history of any single document, so I can get a list of > document 1, 1a, and 1b. or document 3 and 3a, etc... > > So I have something like this (omitting a few lines, for clarity) to set up the > record structure: > > users.create(('name',str), > ('email',str)) > > project.create( ('description',str), > ('label',str), > ('creation_date',date), > ('submitter',users)) > > documents.create(('filename',str), > ('submit',date), > ('submitter',users), > ('type',str), > ('project',project)) Split document into separate document and revision concept, i.e. something like this: documents.create(('type',str), ('project',project)) revisions.create(('filename',str), ('submit',date), ('submitter',users), ('document',documents)) (I'm not sure how you will use 'type', so maybe it should belong to revision.) Best regards, Jacek. From phus at live.com Sat Jun 16 12:00:57 2007 From: phus at live.com (jigloo) Date: Sat, 16 Jun 2007 09:00:57 -0700 Subject: retrieve / find out an image's dimensions In-Reply-To: <1181989666.584877.308920@i13g2000prf.googlegroups.com> References: <1181989666.584877.308920@i13g2000prf.googlegroups.com> Message-ID: <1182009657.421025.312580@z28g2000prd.googlegroups.com> http://www.pycode.com/modules/?id=32 On 6 16 , 6 27 , Adam Teale wrote: > hey guys > > Is there a builtin/standard install method in python for retrieving or > finding out an image's dimensions? > > A quick google found me this:http://www.pythonware.com/library/pil/handbook/introduction.htm > > but it looks like it is something I will need to install - I'd like to > be able to pass my script around to people without them needing any > additional modules > > Any help would be fantastic! > > Cheers > > Adam > python 2.3.5 > osx 10.4.9 From grante at visi.com Fri Jun 1 22:40:56 2007 From: grante at visi.com (Grant Edwards) Date: Sat, 02 Jun 2007 02:40:56 -0000 Subject: c[:]() References: <1180504190.055427.173610@h2g2000hsg.googlegroups.com> <1180554872.3356.30.camel@dot.uniqsys.com> <465DF3DE.40404@cc.umanitoba.ca> <1180566831.239580.199300@m36g2000hse.googlegroups.com> <005401c7a31a$136f7fe0$240110ac@Muse> <135tobve86qj808@corp.supernews.com> <135tru124pie2b3@corp.supernews.com> <135tv1bjqgbmsc9@corp.supernews.com> <9qudnbFRU9QHJsLbnZ2dnUVZ_rKvnZ2d@speakeasy.net> <005f01c7a471$6f4b8b30$240110ac@Muse> Message-ID: <1361m5o29boci28@corp.supernews.com> On 2007-06-02, Gabriel Genellina wrote: > En Fri, 01 Jun 2007 14:22:29 -0300, Warren Stringer > escribi?: > >> I am not insisting on anything. I use ``c[:]()`` as shorthand >> way of saying "c() for c in d where d is a container" > > I begin to think you are some kind of Eliza experiment with > Python pseudo-knowledge injected. I wish I'd said that. > Anyway, the code below defines a simple "callable" list; it > just calls each contained item in turn. Don't bother to use > [:], it won't work. > > py> class CallableList(list): > ... def __call__(self): > ... for item in self: > ... item() Now all we need are user-definable matched-pair-delimiter-constructors for anonymous user-classed objects. ;) -- Grant Edwards grante Yow! I smell a RANCID at CORN DOG! visi.com From aahz at pythoncraft.com Sat Jun 9 10:23:04 2007 From: aahz at pythoncraft.com (Aahz) Date: 9 Jun 2007 07:23:04 -0700 Subject: Where can I suggest an enchantment for Python Zip lib? References: Message-ID: In article , durumdara wrote: > > [...] Click your heels together three times and say, "Abracadabra!" (Sorry, couldn't resist.) -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "as long as we like the same operating system, things are cool." --piranha From richard_gordon at verizon.net Sat Jun 2 14:51:14 2007 From: richard_gordon at verizon.net (Richard Gordon) Date: Sat, 02 Jun 2007 14:51:14 -0400 Subject: com_error 'Exception occurred' Message-ID: <02a301c7a547$0f2e44a0$4101a8c0@WEHEHNOTEBOOK> I've got a fatal bug using Parente's pyTTS with Python 2.3 on Windoze 32 using MS SAPI 5.1 and Hammond's win32 module. The test program is import pyTTS tts = pyTTS.Create() tts.Speak('Hello world.') The resulting debug trace is: PythonWin 2.3.5 (#62, Feb 8 2005, 16:23:02) [MSC v.1200 32 bit (Intel)] on win32. Portions Copyright 1994-2006 Mark Hammond - see 'Help/About PythonWin' for further copyright information. Traceback (most recent call last): File "C:\PROGRA~1\Python23\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py", line 307, in RunScript debugger.run(codeObject, __main__.__dict__, start_stepping=0) File "C:\PROGRA~1\Python23\Lib\site-packages\pythonwin\pywin\debugger\__init__.py", line 60, in run _GetCurrentDebugger().run(cmd, globals,locals, start_stepping) File "C:\PROGRA~1\Python23\Lib\site-packages\pythonwin\pywin\debugger\debugger.py", line 631, in run exec cmd in globals, locals File "C:\yakitome\test\examples\ex1.py", line 4, in ? tts.Speak('Hello world.') File "C:\PROGRA~1\Python23\Lib\site-packages\pyTTS\sapi.py", line 213, in Speak self.speech.Speak(text, flagsum) File "C:\Program Files\Python23\lib\site-packages\win32com\gen_py\C866CA3A-32F7-11D2-9602-00C04F8EE628x0x5x0.py", line 2637, in Speak , Flags) com_error: (-2147352567, 'Exception occurred.', (0, None, None, None, 0, -2147201015), None) >>> The system does not have a sound card --- could that be an issue? My head is about to explode trying to solve this problem, so your help and suggestions will be much appreciated. -------------- next part -------------- An HTML attachment was scrubbed... URL: From horpner at yahoo.com Wed Jun 27 14:31:01 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Wed, 27 Jun 2007 18:31:01 GMT Subject: Reversing a string References: Message-ID: On 2007-06-27, Scott wrote: > Yeah I know strings == immutable, but question 1 in section > 7.14 of "How to think like a computer Scientist" has me trying > to reverse one. No, it just wants to to print the characters in reverse, one per line. > I've come up with two things, one works almost like it should > except that every traversal thru the string I've gotten it to > repeat the "list" again. This is what it looks like: > >>>>mylist = [] That's bad. If you need to use a list in the rev function, you should bind a new list to a local variable inside rev. >>>>def rev(x): > for char in x: > mylist.append(char) > mylist.reverse() > print mylist Here's an debugging exercise that you should try. Please explain what you think each line in the above is supposed to do. Pretend you are trying to convince me that the above program works correctly. I bet you will see find your errors right away as a result of this exercise. > [/code] > So I figured maybe make it a generator (I'm not TO familiar > with generators yet so don't laugh) which changed my code just > a slight bit: Experimentation with stuff you don't fully understand is a great way to learn, but not that useful for solving exercises. ;) -- Neil Cerutti This team is one execution away from being a very good basketball team. --Doc Rivers From s.mientki at id.umcn.nl Tue Jun 5 08:23:48 2007 From: s.mientki at id.umcn.nl (stef) Date: Tue, 05 Jun 2007 14:23:48 +0200 Subject: how to convert a bitmap file to an array ? In-Reply-To: <5cl23kF30kuprU1@mid.uni-berlin.de> References: <5cl23kF30kuprU1@mid.uni-berlin.de> Message-ID: Diez B. Roggisch wrote: > stef wrote: > > >> hello >> >> I can find all kind of procedures to convert an array to a bitmap >> (wxPython, PIL), >> but I can't find the reverse, >> either >> - convert a bitmap to an array >> or >> - read a bitmap file to an array >> > > Not true for PIL, Image.getdata and Image.putdata are your friends. > > thanks Diez, I really overlooked that. cheers, Stef Mientki From S.Mientki-nospam at mailbox.kun.nl Sat Jun 16 09:22:34 2007 From: S.Mientki-nospam at mailbox.kun.nl (Stef Mientki) Date: Sat, 16 Jun 2007 15:22:34 +0200 Subject: Inserting breakpoints ... Message-ID: <1393$4673e30a$d443bb3a$26599@news.speedlinq.nl> hello, for the simulation of some micro language (JAL), the original language is (with a minimal effort) translated into Python, after which the code is run in Python. I want to add a call to a debug routine, called JSM(linenr), which performs task like wait, update user feedback, etc. Now I can't find a nice solution, to add the debug call in a if/for/while statement. The orginal language looks like this For 16 * hardware_column loop Write_lcd_2bytes ( write_text , 0 ) This attempt doesn't work, because apparently I've to choose between - 1 statement behind the ":" - all statements in the line below for xxx in xrange ( 16 * hardware_column ): JSM(78) Write_LCD_2Bytes ( write_text , 0 ) ;JSM(79) This works, but doesn't give a nice output for xxx in xrange ( 16 * hardware_column ): JSM(78) Write_LCD_2Bytes ( write_text , 0 ) ;JSM(79) any other ideas ? thanks, Stef Mientki From sturlamolden at yahoo.no Mon Jun 4 17:58:53 2007 From: sturlamolden at yahoo.no (sturlamolden) Date: Mon, 04 Jun 2007 14:58:53 -0700 Subject: another thread on Python threading In-Reply-To: References: <1180906374.041535.296410@k79g2000hse.googlegroups.com> <1180956762.091381.274750@p47g2000hsd.googlegroups.com> Message-ID: <1180994333.607830.33900@p77g2000hsh.googlegroups.com> On Jun 4, 10:11 pm, Josiah Carlson wrote: > lock = threading.Lock() > > with lock: > #synchronized block! > pass True, except that the lock has to be shared among the threads. This explicit initiation of an reentrant lock is avoided in a Java synchronized block. From rbann11 at hotmail.com Wed Jun 6 18:00:30 2007 From: rbann11 at hotmail.com (rbann11 at hotmail.com) Date: Wed, 06 Jun 2007 15:00:30 -0700 Subject: tkSnack and Pmw Scrollcanvas Message-ID: <1181167230.680604.82410@z28g2000prd.googlegroups.com> Thanks in advance, Hi, I am trying to put tkSnack's Minwave.py demo into Pmw Scrollcanvas, without success. I have included the sample, the error message and the documentation tkSnack says should work. Can someone tell me what I am doing wrong? and If someone has some sample code it would be greatly appreciated. Roger ============ Code Here =========== from Tkinter import * import tkSnack import Pmw root = Tk() Pmw.initialise() tkSnack.initializeSnack(root) sc = Pmw.ScrolledCanvas(root, borderframe=0, labelpos=N, label_text='ScrolledCanvas', usehullsize=1, hull_width=40, hull_height=200) s = tkSnack.Sound(load='r3.wav') tkSnack.createWaveform(sc._canvas, sound=s, width=400) sc.pack(padx = 5, pady = 5, fill = 'both', expand = 1) sc.resizescrollregion() root.mainloop() ===================== Error Msg: Traceback (most recent call last): File "D:\ROGER\Python\tkinter\scrollcanvas3.py", line 16, in tkSnack.createWaveform(sc._canvas, sound=s, width=400) File "C:\Python25\lib\tkSnack.py", line 552, in createWaveform return canvas._create('waveform', args, kw) File "C:\Python25\lib\lib-tk\Tkinter.py", line 2138, in _create cnf = args[-1] IndexError: tuple index out of range =========================== >From the tkSnack documentation: Putting SnackCanvas items on regular Canvases It's possible to draw these new canvas items onto any canvas in your program, not just those that are instances of SnackCanvas. You might need to do this if you're using elaborations or subclasses of Canvas that have been written by other people, for example, if you want to draw a waveform on a ScrolledCanvas from the Python Megawidget collection. To accomplish this, tkSnack provides module-level versions of create_waveform , create_section, and create_spectrogram. Simply use the non-Snack canvas as the first argument. Instead of: NonSnackCanvas.create_waveform(sound=tada) use: tkSnack.createWaveform(NonSnackCanvas, sound=tada) If you're using Pmw Scrolled Canvas, remember that you're drawing onto the ScrolledCanvas's Canvas object. In that case, you'll need to do: tkSnack.createWaveform(myScrolledCanvas._canvas, sound=tada) Roger From john106henry at hotmail.com Sat Jun 23 03:02:09 2007 From: john106henry at hotmail.com (John Henry) Date: Sat, 23 Jun 2007 00:02:09 -0700 Subject: Adding method to a class on the fly In-Reply-To: References: <1182538969.522044.209560@q19g2000prn.googlegroups.com> <1182543862.369337.36880@z28g2000prd.googlegroups.com> <1182547065.295969.258820@g37g2000prf.googlegroups.com> <1182547724.690874.279230@g37g2000prf.googlegroups.com> <1182548694.545515.81060@e9g2000prf.googlegroups.com> Message-ID: <1182582129.462036.84560@m37g2000prh.googlegroups.com> On Jun 22, 7:36 pm, Steven D'Aprano wrote: > On Fri, 22 Jun 2007 14:44:54 -0700, John Henry wrote: > > The above doesn't exactly do I what need. I was looking for a way to > > add method to a class at run time. > > > What does work, is to define an entire sub-class at run time. Like: > > > class DummyParent: > > def __init__(self): > > return > > > def method_static(self, text): > > print text > > return > > > text = "class Dummy(DummyParent):" > > text += "\n\t" + "def __init(self):" > > text += "\n\t" + "\tDummyParent.__init__(self)" > > text += "\n\t" + "def method_dynamic(self):" > > text += "\n\t" + "\tself.method_static(\"it's me\")" > > > exec text > > (By the way, you misspelled __init__.) > > The correct way to add methods to an instance is with the > instancemethod() function. > > class Parrot: > def __init__(self): > import new > # define a function > def method_dynamic(self, *args): > args.insert(0, "hello, it's me!") > return self.method_static(*args) > # convert it into an instance method > method = new.instancemethod(function, self, self.__class__) > # add it to self > self.method_dynamic = method > def method_static(self, text): > return text > > And here is how I use it: > > >>> p = Parrot() > >>> p.method_dynamic() # call from an instance > "it's me" > >>> Parrot.method_dynamic # does it exist in the class? > > Traceback (most recent call last): > File "", line 1, in ? > AttributeError: class Parrot has no attribute 'method_dynamic' > > BUT, having said all that, are you sure this is what you want to do? This > is probably a better way to get the same results: > > class Parrot: > def __init__(self): > self.text = "hello, it's me!" > def method_dynamic(self): > return self.method_static(self.text) > def method_static(self, text): > return text > > Earlier in the thread, you said you wanted a CLASS method, which is very > different. You can use the classmethod built-in function (no need to > import new) to create class methods: > > class Parrot: > def method_dynamic(cls): > return cls.method_static(cls(), "hello it's me") > # or alternatively cls().method_static("hello it's me") > method_dynamic = classmethod(method_dynamic) > def method_static(self, text): > return text > > Note: if you are using recent versions of Python, instead of saying > "method = classmethod(method)" AFTER the block, you can use a decorator > before the block. > > Making method_dynamic a class method and calling an instance method is not > a good way of doing things, since the class method has to create a new > instance before calling method_static, only to throw it away afterwards. > That is wasteful and could be very expensive. > > A better way is to change your class so that method_static is a class > method too, especially since it doesn't use self: > > class Parrot: > @classmethod > def method_dynamic(cls): > return cls.method_static("hello it's me") > @classmethod > def method_static(cls, text): > return text > > (Actually, since method_static doesn't even use the class, you could use > staticmethod instead of classmethod. Remember to remove the "cls" argument.) > > Hope this helps, > > -- > Steven. Thanks everybody for your responses. I know my terminology isn't quite exact. Hopefully that didn't confuse you too much. I used that example hoping to simplify the question. As you'll see below, it takes more if I have to explain the entire story. Of all the answers, I think the new.instancemethod is most appropriate. I'll try to explain: With a PythonCard application, if you want to have a button, normally you use the layout editor which creates a dictionary representing the button, and you would have a function for each of the events it has to handle. For instance, a simple one button ap might look like this: #!/usr/bin/python """ __version__ = "$Revision: 1.6 $" __date__ = "$Date: 2004/08/17 19:46:06 $" """ from PythonCard import model rsrc = {'application':{'type':'Application', 'name':'Minimal', 'backgrounds': [ {'type':'Background', 'name':'bgMin', 'title':'Minimal PythonCard Application', 'size':(200, 100), 'components': [ {'type':'Button', 'name':'Button1', 'position':(5, 35), 'label':'Button1'}, ] # end components } # end background ] # end backgrounds } } class Minimal(model.Background): def on_initialize(self, event): pass def on_Button1_mouseClick(self, event): print "Clicked Button1" if __name__ == '__main__': app = model.Application(Minimal, None, rsrc) app.MainLoop() Notice that the event handler for mouseClick to Button1 is done via the function on_Button1_mouseClick. This is very simple and works great - until you try to create the button on the fly. Creating the button itself is no problem. You simply do a: self.components['Button1'] = {'type':'Button', 'name':'Button1', 'position':(5, 35), 'label':'Button1'} But then how do I create the on_Button1_mouseClick function? With the application I have to come up with, I have a tree on the left, and then depending which branch the user clicks, I have to create various controls on the right. So, it becomes some what of a nightmare for me (since I have lots of branches and they are all quite different). Each time the use click a branch, I have to create the buttons, data entry-fields, and so forth on the fly - along with all of the functions to handle them. This is what I came up with so far (before reading your messages): #!/usr/bin/python """ __version__ = "$Revision: 1.6 $" __date__ = "$Date: 2004/08/17 19:46:06 $" """ from PythonCard import model rsrc = {'application':{'type':'Application', 'name':'Minimal', 'backgrounds': [ {'type':'Background', 'name':'bgMin', 'title':'Minimal PythonCard Application', 'size':(200, 300), 'components': [ ] # end components } # end background ] # end backgrounds } } class Minimal(model.Background): def on_initialize(self, event): return nButtons = 7 text="class MinimalChild(Minimal):" text += "\n\t" + "def on_initialize(self, event):" text += "\n\t" + "\tMinimal.on_initialize(self,event)" for iButton in xrange(nButtons): name = "Button"+str(iButton+1) text += "\n\t" + "\tself.components['"+name+"'] = {" +\ "'type':'Button', " +\ "'name':'"+name+"', " +\ "'label':'"+name+"', "+\ "'position':(5, "+str(35+iButton*30)+")}" if iButton!=nButtons-1: text += "\n\t" + "def on_"+name+"_mouseClick(self, event):" exec(text) if __name__ == '__main__': app = model.Application(MinimalChild, None, rsrc) app.MainLoop() With this approach, each time I click a button, a new one gets created, along with a new handler for mouseClick of that new button. Now, knowing the new.instancemethod way, may be I can simplify the above somewhat and improve the efficiencies but I still don't see how one can do it without using the exec function. Regards, From eric.talevich at gmail.com Tue Jun 5 22:13:51 2007 From: eric.talevich at gmail.com (Eric) Date: Wed, 06 Jun 2007 02:13:51 -0000 Subject: which "GUI module" you suggest me to use? In-Reply-To: References: Message-ID: <1181096031.383425.81580@r19g2000prf.googlegroups.com> On Jun 5, 4:17 pm, ZioMiP wrote: > Cameron Laird ha scritto: > > > > > In article , > > ZioMiP wrote: > >> Hi to all... > > >> I'm actually using Tkinter for my GUI... but I need to "put a piece of a > >> web-page in a widget" how can I do? > > >> which GUI module do you suggest me to use for do that? > > >> or which GUI module do you suggest me to use at all? > > >> I'm acutally using Windows Xp but I also use Linux... > > >> I know that WxPython work only under Windows and PyGTK work only under > >> Linux... there's some other modules? > > > ? wxPython is available for Linux and Mac OS X. PyGTK is > > available for Windows. > > > Apparently you want to embed Web content in a Tkinter widget. > > There are several ways to do this. Do you need a live browser, > > or is it enough to render HTML? > > I think is like a "live browser"... not only render HTML because the > webpage got a bit of javascript inside... Is this webpage untouchable, or is HTML rendering just a shortcut to avoid redesigning part of the app? If you need faithful rendering of an arbitrary webpage along with a Javascript runtime, that's a bigger issue, and you might want to look at some of the Mozilla tools, particularly XULRunner: http://developer.mozilla.org/en/docs/Building_XULRunner_with_Python Otherwise, wxPython's HTML widget or TkHtml should be fine -- your code will probably be easier to maintain and debug if you translate that bit of Javascript to Python (language constructs are similar, especially with xml.dom.minidom). From garrickp at gmail.com Fri Jun 29 17:22:21 2007 From: garrickp at gmail.com (Falcolas) Date: Fri, 29 Jun 2007 14:22:21 -0700 Subject: appending file In-Reply-To: <0Jchi.16365$2v1.11172@newssvr14.news.prodigy.net> References: <0Jchi.16365$2v1.11172@newssvr14.news.prodigy.net> Message-ID: <1183152141.228790.74690@n60g2000hse.googlegroups.com> On Jun 29, 1:04 pm, Kuo wrote: > # FPGA CLOCK^M > NET "SYSCLK_A" loc = N16 | TNM_NET = SYSCLK_A;^M > NET "SYSCLK_AN" loc = M16 | TNM_NET = SYSCLK_A;^M I see those bloody ^M's anytime I have to deal with a DOS file (since it's the carrage return \r character). Is 'pin' a DOS generated file? If you want to deal with a file which contains them, look for and get rid of the \r character. From gagsl-py2 at yahoo.com.ar Sat Jun 23 00:15:42 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 23 Jun 2007 01:15:42 -0300 Subject: EMBEDDING > Run Python & Run C Function References: <1182524980.596661.228390@c77g2000hse.googlegroups.com> Message-ID: En Fri, 22 Jun 2007 12:09:40 -0300, escribi?: > At the moment i can run python-string-code from C (MinGW, WinXP) > > But how can i register a C-function in python-RUNTIME and call this C > function from python - without wrapper dll's or libs??? You can use ctypes: http://www.python.org/doc/lib/module-ctypes.html -- Gabriel Genellina From lars.spam at nocrew.org Mon Jun 25 07:54:41 2007 From: lars.spam at nocrew.org (Lars Brinkhoff) Date: Mon, 25 Jun 2007 13:54:41 +0200 Subject: The Modernization of Emacs References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182370894.001918.36590@k79g2000hse.googlegroups.com> <1182372821.298343.316860@g4g2000hsf.googlegroups.com> <1182375321.067664.190780@o61g2000hsh.googlegroups.com> <86hcp1l6hb.fsf@lola.quinscape.zz> <864pl1l56i.fsf@lola.quinscape.zz> Message-ID: <85hcownta6.fsf@junk.nocrew.org> David Kastrup writes: > I should think that version 2.3.1 would not even try ftp. Is that > on Multics? Note that the GNU Emacs version jumped directly from 1.12 to 13. See etc/ONEWS.1. From kyosohma at gmail.com Sun Jun 24 21:01:31 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Mon, 25 Jun 2007 01:01:31 -0000 Subject: Which XML? In-Reply-To: References: Message-ID: <1182733291.251144.211760@k79g2000hse.googlegroups.com> On Jun 24, 7:04 pm, Bruno Barberi Gnecco wrote: > I've found a lot of XML libraries for Python. Any advices on which > one to use (or *not* to use)? My requirements are: support for XPath, > stability (a must, segfaults are not an option), with DOM API and good > performance desirable. > > Thanks for any advice. > > -- > Bruno Barberi Gnecco I use the minidom module for most of my XML work, but I don't think it has much in the way of XPath. I think lxml might work better for that sort of thing and I think it's part of ElementTree: http://codespeak.net/lxml/dev/objectify.html This guy kind of reviews the major XML modules: http://www.oreillynet.com/onlamp/blog/2005/01/code_respecting_xpath_xml_pyth.html Mike From itsanushshetty at gmail.com Mon Jun 11 17:19:24 2007 From: itsanushshetty at gmail.com (anush shetty) Date: Mon, 11 Jun 2007 21:19:24 -0000 Subject: Link Dictionary In-Reply-To: References: <1181593466.934730.299660@i38g2000prf.googlegroups.com> Message-ID: <1181596764.090231.137820@x35g2000prf.googlegroups.com> On Jun 12, 2:10 am, James Stroud wrote: > anush shetty wrote: > > Hi, > > I have two dictionaries > > > dict1={'B8': set(['I8', 'H8', 'B2', 'B7', 'F8', 'C9', 'G8', 'B4', > > 'B5', 'B6', 'C8', 'E8', 'D8', 'B3', 'A9', 'A8', 'C7', 'B9', 'A7', > > 'B1']), 'B9': set(['I9', 'H9', 'A7', 'F9', 'B3', 'B6', 'G9', 'B4', > > 'B5', 'C9', 'B7', 'E9', 'B1', 'B2', 'D9', 'A9', 'A8', 'C8', 'B8', > > 'C7']), 'D1': set(['F1', 'F2', 'F3', 'G1', 'I1', 'D2', 'H1', 'A1', > > 'D4', 'B1', 'D8', 'D9', 'D6', 'D7', 'C1', 'D5', 'E1', 'D3', 'E3', > > 'E2'])} > > > and > > dict2= > > {'I6': '0', 'H9': '9', 'I2': '0', 'E8': '0', 'H3': '0', 'H7': '0', > > 'I7': '3', 'I4': '0', 'H5': '0', 'F9': '0', 'G7': '5', 'G6': '9', > > 'G5': '0', 'E1': '7', 'G3': '2', 'G2': '0', 'G1': '0', 'I1': '0', > > 'C8': '0', 'I3': '5', 'E5': '0', 'I5': '1', 'C9': '0', 'G9': '0', > > 'G8': '0', 'A1': '0', 'A3': '3', 'A2': '0', 'A5': '2', 'A4': '0', > > 'A7': '6', 'A6': '0', 'C3': '1', 'C2': '0', 'C1': '0', 'E6': '0', > > 'C7': '4', 'C6': '6', 'C5': '0', 'C4': '8', 'I9': '0', 'D8': '0', > > 'I8': '0', 'E4': '0', 'D9': '0', 'H8': '0', 'F6': '8', 'A9': '0', > > 'G4': '6', 'A8': '0', 'E7': '0', 'E3': '0', 'F1': '0', 'F2': '0', > > 'F3': '6', 'F4': '7', 'F5': '0', 'E2': '0', 'F7': '2', 'F8': '0', > > 'D2': '0', 'H1': '8', 'H6': '3', 'H2': '0', 'H4': '2', 'D3': '8', > > 'B4': '3', 'B5': '0', 'B6': '5', 'B7': '0', 'E9': '8', 'B1': '9', > > 'B2': '0', 'B3': '0', 'D6': '2', 'D7': '9', 'D4': '1', 'D5': '0', > > 'B8': '0', 'B9': '1', 'D1': '0'} > > > Now I want to create a dict which would have both the keys and values > > to be of the corresponding values of dict2. > > > Something like this: > > > Eg. The first key in dict1 i.e. B8 as 0 (0 is the value of B8 in > > dict2) mapped as set(['0','0','0',...]). > > > Can anyone help me out with this. > > - > > Anush > > new_dict = {} > for akey, aset in dict1.items(): > new_dict[akey] = sum(int(dict2[k]) for k in aset) > > James So there is no way I can represent all the duplicates right. So is there any solution where I could take the values of dictionary and represent them separately? - Anush From evan at yelp.com Sat Jun 30 18:13:01 2007 From: evan at yelp.com (Evan Klitzke) Date: Sat, 30 Jun 2007 15:13:01 -0700 Subject: Reading image dimensions before it is loaded from a web form using python. In-Reply-To: <46869EE1.4020608@khine.net> References: <46869EE1.4020608@khine.net> Message-ID: On 6/30/07, Norman Khine wrote: > Hello, > I am writing an application using python that allows the user to upload > an image to a folder on the server. > > Is there a way to get the size of the file before it has been uploaded > onto the server and give an error if the size does not comply to the > maximum size. The easiest way to do this is to simply restrict the maximum file upload size. When the client makes the POST request you can see how big it will be. This won't really give you the image dimensions of course, but there's no simple way to find out that information without uploading the entire image. -- Evan Klitzke From bugs at almad.net Tue Jun 5 05:44:57 2007 From: bugs at almad.net (Almad) Date: Tue, 05 Jun 2007 02:44:57 -0700 Subject: Regression testing with Python Message-ID: <1181036697.384740.23610@g4g2000hsf.googlegroups.com> Hi, I'd like to ask how do You resolve "resources" issue when writing regression tests in Python. When doing functional tests, I have some resources that might not be available (like database, HTTP server, Selenium testing proxy) and I'd like then to skip test gracefully (not either failing nor green status). Is there a simple way to do this? Or, how do You build Your Selenium testsuites and integrate them into main suite? Thank You, Almad From fredrik at pythonware.com Mon Jun 11 14:34:30 2007 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 11 Jun 2007 20:34:30 +0200 Subject: with as a reserved word In-Reply-To: <1181574196.682123.291010@a26g2000pre.googlegroups.com> References: <1181574196.682123.291010@a26g2000pre.googlegroups.com> Message-ID: BBands wrote: > I gather that 'with' is on its way to becoming a reserved word. Is > this something that will break? yes. > import Gnuplot > gp = Gnuplot.Gnuplot(debug=1) > data = Gnuplot.Data([1,2,3,4,3,2,3,4,3,2,1], with='linespoints') if you have Python 2.5, you can try it out yourself: >>> dict(with=1) :1: Warning: 'with' will become a reserved keyword in Python 2.6 {'with': 1} >>> from __future__ import with_statement >>> dict(with=1) File "", line 1 dict(with=1) ^ SyntaxError: invalid syntax From john_wilson at telus.net Mon Jun 11 02:10:15 2007 From: john_wilson at telus.net (TtfnJohn) Date: Sun, 10 Jun 2007 23:10:15 -0700 Subject: Why does one regex routine work and not the other one? Message-ID: <1181542215.105744.224040@r19g2000prf.googlegroups.com> I have two small scripts that while on the surface should both work the problem is they don't. Here's the first one: import re testString = 'Thap,fpvi,*!wtyd@*.dip.t-dialin.net:*!ylx@*.dip.t- dialin.net:*!lajaz@*.dip.t-dialin.net::::::' reobj = re.compile(r"(.*),(.*),(.*):::(.*):::(.*)") testString1 = reobj.search(testString) if testString1: match0 = testString1.group(0) match1 = testString1.group(1) This works as expected with any number of seed strings. Now then: This one consistently fails even though it should work, as near as I can tell. import os import re import readline from buzhug import Base # initialize a few things voiceuser = Base('voiceuser') # now to create & open the database. If the database already exists this will # simply open it voiceuser.create(('name',str),('ircname',str),('first',str), ('second',str),('third',str),('fourth',str),('fifth',str), ('sixth',str),('seventh',str),mode="open") #next is to open the file we'll read from and then process it and add the names # to the database # the first step is to compile the regular expression testString = re.compile(r"(.*),(.*),(.*):::(.*):::(.*)") voiceList = open('friendslist','r') while 1: line = voiceList.readline() if not line: break print len(line) line = line[:-2] print line print len(line) regex = testString.search(line) # fails here with regex showing a value of None in the debugger in Komodo if regex: targetUser = regex.group(1) targetFlag = regex.group(2) targetHosts = regex.group(3) targetName = regex.group(4) retVal = targetFlag.find('v') if retVal == -1: continue doneSplit = targetHosts.split(':') counterSplit = len(doneSplit) # initialize or refresh list for database insertion insertRecordList = [] insertRecordList = insertRecordList * 9 insertRecordList[0] = targetUser insertRecordList[1] = targetName for i in range(2,counterSplit,1): Obviously I don't get down to the part where I start to populate a database record and it does look a bit kludgey to this Python n00b. My question is that if it is bringing in strings from the file with the same format as the one in the first listing why would it all fail here? Could the newline character at the end of the line be the villian of the piece? Thanks for any advice in advance John From max at alcyone.com Sun Jun 3 21:22:54 2007 From: max at alcyone.com (Erik Max Francis) Date: Sun, 03 Jun 2007 18:22:54 -0700 Subject: subexpressions (OT: math) In-Reply-To: References: <4662675b$1_5@news.bluewin.ch> <1180890214.317409.85100@w5g2000hsg.googlegroups.com> <4662FDC8.9080407@islandtraining.com> <46634BDC.7090104@freakmail.de> Message-ID: Gary Herron wrote: > No, not end-of-story. Neither of us are being precise enough here. To > quote from your second link: > "Although the radian is a unit of measure, it is a dimensionless > quantity." > > But NOTE: Radians and degrees *are* units of measure., however those > units are dimensionless quantities , i.e., not a length or a time etc. They're both "unit of measure" in some general sense, I suppose, but only one is dimensionless. pi/2 rad = pi/2. 90 deg != 90. Of the plane angles, only radians are dimensionless, and of the solid angles, only steradians are dimensionless. This is because they're defined as the ratio of two quantities with similar dimensions (length for radians and area for steradians). > The arguments to sine and cosine must have an associated unit so you > know whether to interpret sin(1.2) as sine of an angle measured in > degrees or radians (or whatever else). The problem with this reasoning is when angular-dimensioned quantities pop out of trigonometric functions, which happens routinely in the world of calculus. When that happens, you use radians (or steradians) or you're screwed. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM, Y!M erikmaxfrancis There never was a good war or a bad peace. -- Benjamin Franklin From jstroud at mbi.ucla.edu Wed Jun 6 21:01:53 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Wed, 06 Jun 2007 18:01:53 -0700 Subject: Determinant of Large Matrix In-Reply-To: <5coopoF2vt25kU1@mid.individual.net> References: <5coopoF2vt25kU1@mid.individual.net> Message-ID: Hello, Thank you to those who responded for your answers. They were very helpful and I'm confident now that numpy is calculating accurate determinants for these matrices. But I think I need to restate my problem a little as suggested by some becuase I'm still bewildered. First, here is the relevant part of my code: # start of code def main(word, repeats, trials): encodings = encode(word, CODE) random.shuffle(encodings) values = [] pb = PB(tk.Tk()) for i in xrange(trials): if i % 100 == 0: pb.update(float(i)/trials) random.seed() encodings = random.sample(encodings, repeats) distmat = build_distmat(encodings) print print distmat values.append(det(distmat)) values.sort() # print values print set(values) # end of code Here are some notes about the code: 1. PB is a progress bar because this takes a while for a lot of trials. 2. encodings is a complete list equivalent encodings of word. 3. distmat is a representation of the distances between the sample as integers for purposes of calculating the "content" of the hyperspace defined by this pairwise distance matrix (Cayley-Menger determinant). 4. det is numpy.linalg.det I get fairly unintuitive results, because if I run it once for 10 (or 1000 or 100,000) the set of values are all essentially the same: set([-733163520.00005591, -733163520.00004566, -733163519.99998546, -733163520.00002789, -733163519.99999189, -733163519.9999783, -733163519.9999758, -733163520.00002348, -733163519.99996936, -733163520.00004542]) If I run it again on 10 (or 1000) the set is basically homogenous but now of different values (terribly confusing): set([12048175104.00001, 12048175104.000015, 12048175104.000046, 12048175103.999994, 12048175104.000023, 12048175103.999981, 12048175103.999998, 12048175103.99999]) How could this be? This holds for 10 trials or 100000 trials. Below is the output from the above runs. Is this a problem with the rng? All of these matrices look different. I'm certain this can't happen by chance. Thank you again. James euler 70% ./simplex.py [[ 0. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1.] [ 1. 0. 4. 9. 9. 4. 4. 9. 9. 1. 9. 16. 9. 9.] [ 1. 4. 0. 9. 9. 4. 4. 16. 16. 4. 9. 9. 1. 4.] [ 1. 9. 9. 0. 9. 9. 16. 4. 4. 16. 9. 1. 4. 4.] [ 1. 9. 9. 9. 0. 16. 4. 4. 9. 9. 9. 9. 4. 9.] [ 1. 4. 4. 9. 16. 0. 9. 4. 4. 4. 4. 9. 9. 4.] [ 1. 4. 4. 16. 4. 9. 0. 16. 9. 1. 9. 9. 9. 9.] [ 1. 9. 16. 4. 4. 4. 16. 0. 1. 9. 4. 4. 9. 4.] [ 1. 9. 16. 4. 9. 4. 9. 1. 0. 4. 9. 1. 9. 9.] [ 1. 1. 4. 16. 9. 4. 1. 9. 4. 0. 9. 9. 9. 9.] [ 1. 9. 9. 9. 9. 4. 9. 4. 9. 9. 0. 9. 16. 1.] [ 1. 16. 9. 1. 9. 9. 9. 4. 1. 9. 9. 0. 4. 4.] [ 1. 9. 1. 4. 4. 9. 9. 9. 9. 9. 16. 4. 0. 9.] [ 1. 9. 4. 4. 9. 4. 9. 4. 9. 9. 1. 4. 9. 0.]] [[ 0. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1.] [ 1. 0. 4. 16. 4. 9. 16. 4. 4. 9. 9. 1. 9. 9.] [ 1. 4. 0. 9. 9. 1. 9. 9. 9. 16. 9. 4. 4. 9.] [ 1. 16. 9. 0. 4. 4. 1. 9. 9. 9. 4. 9. 9. 1.] [ 1. 4. 9. 4. 0. 16. 9. 9. 1. 9. 4. 1. 9. 9.] [ 1. 9. 1. 4. 16. 0. 4. 4. 16. 9. 4. 9. 9. 4.] [ 1. 16. 9. 1. 9. 4. 0. 9. 16. 9. 9. 9. 4. 4.] [ 1. 4. 9. 9. 9. 4. 9. 0. 4. 1. 4. 4. 9. 9.] [ 1. 4. 9. 9. 1. 16. 16. 4. 0. 4. 4. 4. 4. 9.] [ 1. 9. 16. 9. 9. 9. 9. 1. 4. 0. 4. 9. 9. 9.] [ 1. 9. 9. 4. 4. 4. 9. 4. 4. 4. 0. 9. 16. 4.] [ 1. 1. 4. 9. 1. 9. 9. 4. 4. 9. 9. 0. 9. 16.] [ 1. 9. 4. 9. 9. 9. 4. 9. 4. 9. 16. 9. 0. 9.] [ 1. 9. 9. 1. 9. 4. 4. 9. 9. 9. 4. 16. 9. 0.]] [[ 0. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1.] [ 1. 0. 9. 9. 4. 9. 4. 9. 9. 9. 9. 9. 16. 4.] [ 1. 9. 0. 1. 9. 4. 9. 4. 16. 9. 9. 9. 4. 1.] [ 1. 9. 1. 0. 9. 4. 9. 9. 9. 9. 16. 9. 4. 4.] [ 1. 4. 9. 9. 0. 1. 9. 9. 4. 9. 4. 16. 9. 9.] [ 1. 9. 4. 4. 1. 0. 16. 16. 9. 4. 9. 9. 4. 4.] [ 1. 4. 9. 9. 9. 16. 0. 1. 4. 4. 4. 4. 4. 16.] [ 1. 9. 4. 9. 9. 16. 1. 0. 4. 9. 1. 9. 4. 9.] [ 1. 9. 16. 9. 4. 9. 4. 4. 0. 4. 1. 9. 9. 16.] [ 1. 9. 9. 9. 9. 4. 4. 9. 4. 0. 4. 1. 4. 9.] [ 1. 9. 9. 16. 4. 9. 4. 1. 1. 4. 0. 9. 9. 9.] [ 1. 9. 9. 9. 16. 9. 4. 9. 9. 1. 9. 0. 4. 9.] [ 1. 16. 4. 4. 9. 4. 4. 4. 9. 4. 9. 4. 0. 9.] [ 1. 4. 1. 4. 9. 4. 16. 9. 16. 9. 9. 9. 9. 0.]] [[ 0. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1.] [ 1. 0. 9. 9. 1. 9. 4. 1. 16. 9. 9. 4. 9. 4.] [ 1. 9. 0. 4. 9. 1. 9. 9. 4. 4. 9. 4. 9. 4.] [ 1. 9. 4. 0. 16. 4. 1. 9. 4. 4. 9. 4. 4. 16.] [ 1. 1. 9. 16. 0. 9. 9. 4. 16. 9. 9. 9. 4. 4.] [ 1. 9. 1. 4. 9. 0. 9. 9. 9. 9. 16. 4. 9. 9.] [ 1. 4. 9. 1. 9. 9. 0. 9. 4. 1. 9. 4. 9. 16.] [ 1. 1. 9. 9. 4. 9. 9. 0. 9. 16. 9. 4. 9. 4.] [ 1. 16. 4. 4. 16. 9. 4. 9. 0. 1. 4. 9. 9. 9.] [ 1. 9. 4. 4. 9. 9. 1. 16. 1. 0. 4. 9. 9. 9.] [ 1. 9. 9. 9. 9. 16. 9. 9. 4. 4. 0. 9. 4. 1.] [ 1. 4. 4. 4. 9. 4. 4. 4. 9. 9. 9. 0. 16. 4.] [ 1. 9. 9. 4. 4. 9. 9. 9. 9. 9. 4. 16. 0. 9.] [ 1. 4. 4. 16. 4. 9. 16. 4. 9. 9. 1. 4. 9. 0.]] [[ 0. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1.] [ 1. 0. 16. 4. 9. 4. 9. 4. 16. 4. 1. 4. 9. 9.] [ 1. 16. 0. 4. 4. 16. 4. 9. 1. 9. 9. 4. 4. 4.] [ 1. 4. 4. 0. 1. 9. 4. 9. 9. 9. 9. 4. 9. 4.] [ 1. 9. 4. 1. 0. 9. 9. 9. 9. 9. 16. 4. 9. 9.] [ 1. 4. 16. 9. 9. 0. 9. 1. 9. 4. 9. 9. 4. 16.] [ 1. 9. 4. 4. 9. 9. 0. 9. 1. 16. 4. 9. 9. 1.] [ 1. 4. 9. 9. 9. 1. 9. 0. 4. 1. 9. 4. 9. 16.] [ 1. 16. 1. 9. 9. 9. 1. 4. 0. 9. 9. 4. 9. 4.] [ 1. 4. 9. 9. 9. 4. 16. 1. 9. 0. 9. 4. 9. 9.] [ 1. 1. 9. 9. 16. 9. 4. 9. 9. 9. 0. 9. 4. 4.] [ 1. 4. 4. 4. 4. 9. 9. 4. 4. 4. 9. 0. 16. 9.] [ 1. 9. 4. 9. 9. 4. 9. 9. 9. 9. 4. 16. 0. 9.] [ 1. 9. 4. 4. 9. 16. 1. 16. 4. 9. 4. 9. 9. 0.]] [[ 0. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1.] [ 1. 0. 4. 1. 9. 4. 9. 16. 9. 9. 9. 4. 9. 9.] [ 1. 4. 0. 9. 4. 9. 16. 9. 4. 16. 9. 1. 4. 9.] [ 1. 1. 9. 0. 16. 9. 4. 9. 4. 4. 4. 9. 16. 4.] [ 1. 9. 4. 16. 0. 4. 16. 4. 4. 9. 9. 4. 1. 4.] [ 1. 4. 9. 9. 4. 0. 4. 9. 9. 9. 9. 9. 9. 16.] [ 1. 9. 16. 4. 16. 4. 0. 9. 9. 1. 4. 9. 9. 9.] [ 1. 16. 9. 9. 4. 9. 9. 0. 1. 9. 9. 9. 9. 4.] [ 1. 9. 4. 4. 4. 9. 9. 1. 0. 9. 9. 4. 9. 4.] [ 1. 9. 16. 4. 9. 9. 1. 9. 9. 0. 1. 9. 4. 4.] [ 1. 9. 9. 4. 9. 9. 4. 9. 9. 1. 0. 16. 9. 4.] [ 1. 4. 1. 9. 4. 9. 9. 9. 4. 9. 16. 0. 1. 9.] [ 1. 9. 4. 16. 1. 9. 9. 9. 9. 4. 9. 1. 0. 4.] [ 1. 9. 9. 4. 4. 16. 9. 4. 4. 4. 4. 9. 4. 0.]] [[ 0. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1.] [ 1. 0. 9. 9. 4. 9. 9. 9. 9. 1. 16. 9. 4. 9.] [ 1. 9. 0. 4. 9. 9. 9. 16. 4. 9. 9. 1. 4. 9.] [ 1. 9. 4. 0. 16. 16. 9. 9. 4. 4. 1. 4. 4. 9.] [ 1. 4. 9. 16. 0. 1. 4. 4. 16. 4. 9. 9. 4. 4.] [ 1. 9. 9. 16. 1. 0. 9. 1. 9. 9. 9. 4. 4. 4.] [ 1. 9. 9. 9. 4. 9. 0. 9. 4. 9. 4. 9. 16. 9.] [ 1. 9. 16. 9. 4. 1. 9. 0. 9. 4. 4. 9. 9. 1.] [ 1. 9. 4. 4. 16. 9. 4. 9. 0. 9. 9. 1. 9. 16.] [ 1. 1. 9. 4. 4. 9. 9. 4. 9. 0. 9. 9. 4. 4.] [ 1. 16. 9. 1. 9. 9. 4. 4. 9. 9. 0. 9. 9. 4.] [ 1. 9. 1. 4. 9. 4. 9. 9. 1. 9. 9. 0. 4. 16.] [ 1. 4. 4. 4. 4. 4. 16. 9. 9. 4. 9. 4. 0. 9.] [ 1. 9. 9. 9. 4. 4. 9. 1. 16. 4. 4. 16. 9. 0.]] [[ 0. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1.] [ 1. 0. 4. 9. 9. 4. 9. 4. 9. 4. 4. 16. 4. 4.] [ 1. 4. 0. 9. 9. 9. 4. 9. 16. 9. 1. 9. 4. 9.] [ 1. 9. 9. 0. 4. 16. 9. 9. 4. 9. 9. 4. 1. 9.] [ 1. 9. 9. 4. 0. 9. 16. 4. 1. 4. 16. 9. 9. 4.] [ 1. 4. 9. 16. 9. 0. 9. 1. 9. 4. 9. 9. 9. 9.] [ 1. 9. 4. 9. 16. 9. 0. 9. 9. 16. 1. 4. 4. 9.] [ 1. 4. 9. 9. 4. 1. 9. 0. 4. 4. 9. 9. 4. 9.] [ 1. 9. 16. 4. 1. 9. 9. 4. 0. 4. 9. 9. 9. 1.] [ 1. 4. 9. 9. 4. 4. 16. 4. 4. 0. 9. 4. 16. 1.] [ 1. 4. 1. 9. 16. 9. 1. 9. 9. 9. 0. 9. 4. 4.] [ 1. 16. 9. 4. 9. 9. 4. 9. 9. 4. 9. 0. 9. 9.] [ 1. 4. 4. 1. 9. 9. 4. 4. 9. 16. 4. 9. 0. 16.] [ 1. 4. 9. 9. 4. 9. 9. 9. 1. 1. 4. 9. 16. 0.]] [[ 0. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1.] [ 1. 0. 4. 4. 9. 4. 4. 4. 9. 4. 9. 1. 16. 16.] [ 1. 4. 0. 9. 9. 9. 1. 4. 4. 9. 16. 4. 9. 16.] [ 1. 4. 9. 0. 9. 16. 9. 9. 4. 9. 9. 9. 9. 4.] [ 1. 9. 9. 9. 0. 4. 16. 9. 9. 9. 1. 9. 4. 4.] [ 1. 4. 9. 16. 4. 0. 9. 4. 9. 4. 4. 4. 4. 9.] [ 1. 4. 1. 9. 16. 9. 0. 4. 4. 9. 9. 1. 9. 9.] [ 1. 4. 4. 9. 9. 4. 4. 0. 9. 1. 9. 9. 4. 9.] [ 1. 9. 4. 4. 9. 9. 4. 9. 0. 16. 9. 9. 1. 9.] [ 1. 4. 9. 9. 9. 4. 9. 1. 16. 0. 9. 9. 9. 9.] [ 1. 9. 16. 9. 1. 4. 9. 9. 9. 9. 0. 4. 4. 1.] [ 1. 1. 4. 9. 9. 4. 1. 9. 9. 9. 4. 0. 16. 9.] [ 1. 16. 9. 9. 4. 4. 9. 4. 1. 9. 4. 16. 0. 4.] [ 1. 16. 16. 4. 4. 9. 9. 9. 9. 9. 1. 9. 4. 0.]] [[ 0. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1.] [ 1. 0. 4. 4. 16. 4. 16. 9. 9. 1. 4. 4. 9. 4.] [ 1. 4. 0. 9. 9. 9. 9. 9. 16. 9. 4. 1. 9. 9.] [ 1. 4. 9. 0. 9. 9. 9. 16. 4. 1. 9. 4. 9. 1.] [ 1. 16. 9. 9. 0. 9. 4. 4. 1. 16. 4. 4. 4. 9.] [ 1. 4. 9. 9. 9. 0. 4. 9. 4. 9. 16. 9. 9. 9.] [ 1. 16. 9. 9. 4. 4. 0. 4. 9. 9. 9. 9. 1. 16.] [ 1. 9. 9. 16. 4. 9. 4. 0. 9. 9. 4. 9. 1. 9.] [ 1. 9. 16. 4. 1. 4. 9. 9. 0. 9. 9. 9. 9. 4.] [ 1. 1. 9. 1. 16. 9. 9. 9. 9. 0. 4. 9. 4. 4.] [ 1. 4. 4. 9. 4. 16. 9. 4. 9. 4. 0. 4. 4. 9.] [ 1. 4. 1. 4. 4. 9. 9. 9. 9. 9. 4. 0. 9. 4.] [ 1. 9. 9. 9. 4. 9. 1. 1. 9. 4. 4. 9. 0. 16.] [ 1. 4. 9. 1. 9. 9. 16. 9. 4. 4. 9. 4. 16. 0.]] set([31247376384.000099, 31247376384.000187, 31247376384.000217, 31247376383.99992, 31247376384.000214, 31247376383.999863, 31247376384.000294, 31247376383.999889, 31247376384.000324, 31247376383.999947]) euler 71% ./simplex.py [[ 0. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1.] [ 1. 0. 9. 9. 4. 9. 9. 9. 1. 4. 4. 1. 4. 1.] [ 1. 9. 0. 16. 4. 9. 4. 16. 9. 16. 9. 16. 4. 9.] [ 1. 9. 16. 0. 4. 1. 9. 4. 9. 4. 1. 4. 9. 4.] [ 1. 4. 4. 4. 0. 1. 16. 9. 4. 9. 1. 9. 9. 1.] [ 1. 9. 9. 1. 1. 0. 9. 4. 9. 4. 4. 4. 16. 4.] [ 1. 9. 4. 9. 16. 9. 0. 9. 16. 9. 16. 4. 9. 9.] [ 1. 9. 16. 4. 9. 4. 9. 0. 4. 1. 9. 4. 16. 9.] [ 1. 1. 9. 9. 4. 9. 16. 4. 0. 1. 4. 4. 4. 4.] [ 1. 4. 16. 4. 9. 4. 9. 1. 1. 0. 9. 1. 9. 9.] [ 1. 4. 9. 1. 1. 4. 16. 9. 4. 9. 0. 9. 4. 1.] [ 1. 1. 16. 4. 9. 4. 4. 4. 4. 1. 9. 0. 9. 4.] [ 1. 4. 4. 9. 9. 16. 9. 16. 4. 9. 4. 9. 0. 9.] [ 1. 1. 9. 4. 1. 4. 9. 9. 4. 9. 1. 4. 9. 0.]] [[ 0. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1.] [ 1. 0. 9. 1. 9. 4. 1. 4. 4. 9. 9. 9. 1. 4.] [ 1. 9. 0. 4. 4. 9. 9. 4. 16. 9. 9. 16. 4. 9.] [ 1. 1. 4. 0. 9. 9. 1. 4. 4. 16. 9. 9. 4. 1.] [ 1. 9. 4. 9. 0. 16. 4. 9. 9. 4. 16. 16. 9. 16.] [ 1. 4. 9. 9. 16. 0. 9. 4. 4. 4. 1. 4. 1. 4.] [ 1. 1. 9. 1. 4. 9. 0. 4. 1. 16. 9. 9. 4. 4.] [ 1. 4. 4. 4. 9. 4. 4. 0. 9. 16. 1. 4. 1. 9.] [ 1. 4. 16. 4. 9. 4. 1. 9. 0. 9. 4. 4. 9. 1.] [ 1. 9. 9. 16. 4. 4. 16. 16. 9. 0. 9. 9. 9. 9.] [ 1. 9. 9. 9. 16. 1. 9. 1. 4. 9. 0. 1. 4. 4.] [ 1. 9. 16. 9. 16. 4. 9. 4. 4. 9. 1. 0. 9. 4.] [ 1. 1. 4. 4. 9. 1. 4. 1. 9. 9. 4. 9. 0. 9.] [ 1. 4. 9. 1. 16. 4. 4. 9. 1. 9. 4. 4. 9. 0.]] [[ 0. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1.] [ 1. 0. 9. 9. 9. 16. 9. 16. 4. 9. 4. 9. 9. 16.] [ 1. 9. 0. 4. 16. 9. 4. 1. 9. 1. 4. 4. 9. 4.] [ 1. 9. 4. 0. 9. 4. 9. 1. 9. 4. 4. 9. 1. 1.] [ 1. 9. 16. 9. 0. 4. 16. 9. 4. 9. 9. 9. 4. 4.] [ 1. 16. 9. 4. 4. 0. 4. 4. 9. 9. 4. 1. 1. 4.] [ 1. 9. 4. 9. 16. 4. 0. 9. 16. 4. 4. 1. 9. 9.] [ 1. 16. 1. 1. 9. 4. 9. 0. 4. 4. 9. 9. 4. 1.] [ 1. 4. 9. 9. 4. 9. 16. 4. 0. 16. 16. 16. 9. 9.] [ 1. 9. 1. 4. 9. 9. 4. 4. 16. 0. 4. 4. 9. 1.] [ 1. 4. 4. 4. 9. 4. 4. 9. 16. 4. 0. 1. 1. 9.] [ 1. 9. 4. 9. 9. 1. 1. 9. 16. 4. 1. 0. 4. 9.] [ 1. 9. 9. 1. 4. 1. 9. 4. 9. 9. 1. 4. 0. 4.] [ 1. 16. 4. 1. 4. 4. 9. 1. 9. 1. 9. 9. 4. 0.]] [[ 0. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1.] [ 1. 0. 4. 4. 16. 4. 4. 1. 9. 9. 1. 9. 4. 4.] [ 1. 4. 0. 4. 9. 1. 9. 9. 4. 16. 4. 1. 4. 9.] [ 1. 4. 4. 0. 9. 4. 4. 1. 1. 9. 9. 1. 9. 9.] [ 1. 16. 9. 9. 0. 16. 9. 9. 9. 4. 16. 4. 16. 4.] [ 1. 4. 1. 4. 16. 0. 9. 9. 1. 9. 4. 4. 4. 9.] [ 1. 4. 9. 4. 9. 9. 0. 1. 4. 4. 1. 4. 4. 16.] [ 1. 1. 9. 1. 9. 9. 1. 0. 4. 4. 4. 4. 9. 9.] [ 1. 9. 4. 1. 9. 1. 4. 4. 0. 4. 9. 1. 9. 16.] [ 1. 9. 16. 9. 4. 9. 4. 4. 4. 0. 9. 9. 16. 9.] [ 1. 1. 4. 9. 16. 4. 1. 4. 9. 9. 0. 9. 1. 9.] [ 1. 9. 1. 1. 4. 4. 4. 4. 1. 9. 9. 0. 9. 16.] [ 1. 4. 4. 9. 16. 4. 4. 9. 9. 16. 1. 9. 0. 9.] [ 1. 4. 9. 9. 4. 9. 16. 9. 16. 9. 9. 16. 9. 0.]] [[ 0. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1.] [ 1. 0. 9. 4. 4. 9. 1. 9. 4. 4. 9. 1. 1. 9.] [ 1. 9. 0. 16. 1. 9. 9. 4. 9. 9. 16. 4. 4. 4.] [ 1. 4. 16. 0. 9. 9. 9. 9. 4. 9. 4. 4. 9. 16.] [ 1. 4. 1. 9. 0. 9. 9. 4. 9. 9. 16. 1. 1. 4.] [ 1. 9. 9. 9. 9. 0. 9. 9. 16. 16. 4. 16. 4. 9.] [ 1. 1. 9. 9. 9. 9. 0. 4. 1. 1. 9. 4. 4. 4.] [ 1. 9. 4. 9. 4. 9. 4. 0. 1. 4. 16. 9. 4. 1.] [ 1. 4. 9. 4. 9. 16. 1. 1. 0. 1. 9. 4. 9. 4.] [ 1. 4. 9. 9. 9. 16. 1. 4. 1. 0. 4. 4. 9. 1.] [ 1. 9. 16. 4. 16. 4. 9. 16. 9. 4. 0. 9. 16. 9.] [ 1. 1. 4. 4. 1. 16. 4. 9. 4. 4. 9. 0. 4. 9.] [ 1. 1. 4. 9. 1. 4. 4. 4. 9. 9. 16. 4. 0. 4.] [ 1. 9. 4. 16. 4. 9. 4. 1. 4. 1. 9. 9. 4. 0.]] [[ 0. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1.] [ 1. 0. 4. 4. 1. 9. 9. 4. 16. 1. 9. 1. 9. 4.] [ 1. 4. 0. 9. 1. 9. 4. 9. 9. 1. 4. 4. 4. 16.] [ 1. 4. 9. 0. 9. 4. 4. 1. 16. 4. 1. 4. 4. 9.] [ 1. 1. 1. 9. 0. 16. 4. 9. 9. 4. 4. 4. 4. 9.] [ 1. 9. 9. 4. 16. 0. 9. 4. 9. 4. 9. 9. 16. 4.] [ 1. 9. 4. 4. 4. 9. 0. 1. 4. 9. 1. 4. 4. 16.] [ 1. 4. 9. 1. 9. 4. 1. 0. 9. 4. 4. 1. 9. 9.] [ 1. 16. 9. 16. 9. 9. 4. 9. 0. 16. 9. 9. 9. 4.] [ 1. 1. 1. 4. 4. 4. 9. 4. 16. 0. 9. 1. 9. 9.] [ 1. 9. 4. 1. 4. 9. 1. 4. 9. 9. 0. 9. 1. 16.] [ 1. 1. 4. 4. 4. 9. 4. 1. 9. 1. 9. 0. 9. 9.] [ 1. 9. 4. 4. 4. 16. 4. 9. 9. 9. 1. 9. 0. 16.] [ 1. 4. 16. 9. 9. 4. 16. 9. 4. 9. 16. 9. 16. 0.]] [[ 0. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1.] [ 1. 0. 16. 4. 4. 9. 1. 4. 1. 9. 9. 1. 9. 9.] [ 1. 16. 0. 9. 9. 4. 9. 16. 16. 4. 9. 16. 4. 9.] [ 1. 4. 9. 0. 9. 4. 1. 9. 9. 9. 4. 1. 4. 1.] [ 1. 4. 9. 9. 0. 1. 9. 1. 4. 9. 4. 4. 16. 4.] [ 1. 9. 4. 4. 1. 0. 4. 4. 9. 16. 1. 9. 9. 1.] [ 1. 1. 9. 1. 9. 4. 0. 9. 4. 16. 4. 4. 4. 4.] [ 1. 4. 16. 9. 1. 4. 9. 0. 4. 9. 1. 4. 9. 4.] [ 1. 1. 16. 9. 4. 9. 4. 4. 0. 9. 9. 4. 16. 9.] [ 1. 9. 4. 9. 9. 16. 16. 9. 9. 0. 16. 4. 9. 9.] [ 1. 9. 9. 4. 4. 1. 4. 1. 9. 16. 0. 9. 4. 1.] [ 1. 1. 16. 1. 4. 9. 4. 4. 4. 4. 9. 0. 9. 4.] [ 1. 9. 4. 4. 16. 9. 4. 9. 16. 9. 4. 9. 0. 9.] [ 1. 9. 9. 1. 4. 1. 4. 4. 9. 9. 1. 4. 9. 0.]] [[ 0. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1.] [ 1. 0. 1. 9. 9. 1. 9. 4. 1. 4. 9. 9. 4. 4.] [ 1. 1. 0. 9. 9. 4. 4. 4. 4. 4. 9. 16. 4. 1.] [ 1. 9. 9. 0. 1. 4. 4. 4. 4. 16. 9. 9. 1. 4.] [ 1. 9. 9. 1. 0. 4. 4. 1. 4. 9. 16. 9. 4. 4.] [ 1. 1. 4. 4. 4. 0. 9. 1. 4. 9. 9. 9. 1. 9.] [ 1. 9. 4. 4. 4. 9. 0. 9. 4. 16. 16. 9. 9. 1.] [ 1. 4. 4. 4. 1. 1. 9. 0. 9. 4. 9. 16. 1. 9.] [ 1. 1. 4. 4. 4. 4. 4. 9. 0. 9. 16. 4. 9. 1.] [ 1. 4. 4. 16. 9. 9. 16. 4. 9. 0. 4. 9. 9. 9.] [ 1. 9. 9. 9. 16. 9. 16. 9. 16. 4. 0. 4. 4. 16.] [ 1. 9. 16. 9. 9. 9. 9. 16. 4. 9. 4. 0. 16. 9.] [ 1. 4. 4. 1. 4. 1. 9. 1. 9. 9. 4. 16. 0. 9.] [ 1. 4. 1. 4. 4. 9. 1. 9. 1. 9. 16. 9. 9. 0.]] [[ 0. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1.] [ 1. 0. 16. 1. 4. 4. 9. 4. 9. 4. 9. 4. 1. 4.] [ 1. 16. 0. 16. 9. 4. 9. 16. 4. 9. 4. 16. 9. 9.] [ 1. 1. 16. 0. 1. 9. 9. 1. 9. 9. 9. 4. 4. 4.] [ 1. 4. 9. 1. 0. 16. 4. 4. 4. 4. 4. 9. 1. 9.] [ 1. 4. 4. 9. 16. 0. 16. 9. 9. 9. 16. 9. 9. 9.] [ 1. 9. 9. 9. 4. 16. 0. 9. 4. 1. 1. 1. 4. 4.] [ 1. 4. 16. 1. 4. 9. 9. 0. 16. 9. 9. 4. 9. 4.] [ 1. 9. 4. 9. 4. 9. 4. 16. 0. 9. 9. 9. 4. 16.] [ 1. 4. 9. 9. 4. 9. 1. 9. 9. 0. 1. 4. 1. 4.] [ 1. 9. 4. 9. 4. 16. 1. 9. 9. 1. 0. 4. 4. 1.] [ 1. 4. 16. 4. 9. 9. 1. 4. 9. 4. 4. 0. 9. 1.] [ 1. 1. 9. 4. 1. 9. 4. 9. 4. 1. 4. 9. 0. 9.] [ 1. 4. 9. 4. 9. 9. 4. 4. 16. 4. 1. 1. 9. 0.]] [[ 0. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1.] [ 1. 0. 16. 4. 9. 9. 1. 4. 4. 9. 4. 4. 1. 9.] [ 1. 16. 0. 16. 9. 4. 9. 16. 9. 4. 4. 16. 9. 9.] [ 1. 4. 16. 0. 4. 16. 4. 4. 9. 9. 9. 1. 9. 9.] [ 1. 9. 9. 4. 0. 4. 9. 4. 4. 16. 4. 1. 4. 1.] [ 1. 9. 4. 16. 4. 0. 16. 9. 9. 9. 9. 9. 4. 4.] [ 1. 1. 9. 4. 9. 16. 0. 4. 4. 9. 1. 4. 4. 9.] [ 1. 4. 16. 4. 4. 9. 4. 0. 4. 4. 9. 1. 9. 1.] [ 1. 4. 9. 9. 4. 9. 4. 4. 0. 9. 1. 9. 1. 1.] [ 1. 9. 4. 9. 16. 9. 9. 4. 9. 0. 16. 9. 16. 9.] [ 1. 4. 4. 9. 4. 9. 1. 9. 1. 16. 0. 9. 1. 4.] [ 1. 4. 16. 1. 1. 9. 4. 1. 9. 9. 9. 0. 9. 4.] [ 1. 1. 9. 9. 4. 4. 4. 9. 1. 16. 1. 9. 0. 4.] [ 1. 9. 9. 9. 1. 4. 9. 1. 1. 9. 4. 4. 4. 0.]] set([-167037108224.00009, -167037108224.00006, -167037108223.99988, -167037108223.99979, -167037108223.99997, -167037108224.00003]) From apatheticagnostic at gmail.com Tue Jun 26 02:52:10 2007 From: apatheticagnostic at gmail.com (kaens) Date: Tue, 26 Jun 2007 02:52:10 -0400 Subject: can't start Apache on Mac OS X--no listening sockets available? In-Reply-To: <1182840123.203387.173210@q75g2000hsh.googlegroups.com> References: <1182824632.015853.317970@g4g2000hsf.googlegroups.com> <1182826067.067254.247940@j4g2000prf.googlegroups.com> <1182838193.195172.206160@u2g2000hsc.googlegroups.com> <1182840123.203387.173210@q75g2000hsh.googlegroups.com> Message-ID: <163f0ce20706252352q51cc0793h71251009fc1a5ac3@mail.gmail.com> On 6/26/07, 7stud wrote: > Ok. If I try to start Personal Web Sharing while Apache is running, > it says "Web Sharing starting up...", but it never does. Then if I > close the window and restart my imac, my imac boots up with Personal > Web Sharing turned on. > > I still can't figure out where the page that says "It works!" is > located. It must be in the pre installed apache directory, but I have > no idea where it is on my imac. And, I don't understand why the page > isn't being served up by my new installation since I started the new > Apache using the command: > > $sudo /Library/Apache2/bin/apachectl start > > I didn't start the pre-installed Apache. > > Also, when I look at the Activity monitor, there is an httpd root > process with pid 285, and then there are 6 daemon http processes with > pids 286, 287, 288, 289, 290, 291. What is that all about? > > -- > http://mail.python.org/mailman/listinfo/python-list > If apache2 works on macs how it does on linux (it should, right?) there should be Apache2/sites-enabled and Apache2/sites-available directories - the "default" files in these will tell you what pages are being served, I believe. Maybe apachectl restart? Also, I think the processes are normal, but I'm not sure. Apache is a pretty heavyweight server. From steven.bethard at gmail.com Fri Jun 1 01:20:27 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Thu, 31 May 2007 23:20:27 -0600 Subject: strange PyLint configuration In-Reply-To: <5c8q4eF2vg743U1@mid.individual.net> References: <1180613790.317480.314600@p47g2000hsd.googlegroups.com> <5c8glhF2tra7sU1@mid.individual.net> <5c8q4eF2vg743U1@mid.individual.net> Message-ID: <67GdnffsDOACMcLbnZ2dnUVZ_qarnZ2d@comcast.com> Bjoern Schliessmann wrote: > Eduardo "EdCrypt" O. Padoan wrote: > >> No. Quoting PEP 8: >> Functions: >> """ >> mixedCase is allowed only in contexts where that's already the >> prevailing style (e.g. threading.py), to retain backwards >> compatibility. >> """ >> Methods and instances: >> """ >> Use the function naming rules: lowercase with words separated by >> underscores as necessary to improve readability. >> """ > > Has this been updated recently? I could've sworn I had read that > stuff like has_key was "old". You can check the revision history here: http://svn.python.org/view/peps/trunk/pep-0008.txt?rev=55405&view=log Looks to me like camelCase became unacceptable in Revision 1781, back in March 2004. STeVe From bj_666 at gmx.net Sat Jun 23 03:26:30 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Sat, 23 Jun 2007 09:26:30 +0200 Subject: SIMD powered Python References: <1182554657.444684.268050@i13g2000prf.googlegroups.com> Message-ID: In <1182554657.444684.268050 at i13g2000prf.googlegroups.com>, Bytter wrote: > Is there any I&D ongoing about using SIMD [1] instructions, like SSE > [2], to speed up Python, especially regarding functional features, > like list comprehension, map and reduce, etc.. ? SIMD instruction sets know about "low level" data types, Python is about objects. `map()`, `reduce()`, list comprehension work on arbitrary iterables so how do you expect SIMD instructions handle this? Even simple lists contain objects and those don't have to be of the same type. Ciao, Marc 'BlackJack' Rintsch From sk8in_zombi at yahoo.com.au Fri Jun 8 12:53:37 2007 From: sk8in_zombi at yahoo.com.au (Mr SZ) Date: Sat, 9 Jun 2007 02:53:37 +1000 (EST) Subject: Working with dictionary like strings Message-ID: <590423.84875.qm@web54502.mail.re2.yahoo.com> hello all, I'm using the urllib module to fetch pages from the web.The returned response is in the structure of a dictionary .For eg: {"":"","label": [ ] ,"torrents": [ ["F0666BDCCBFD01A52535759C044485E2E1CCE3C3",136,"AAA",1250164864,651,646185088,606208,0,0,0,-1,"",0,0,0,0,33564,7,342884352], ["46683EA1C950CB020DD6DD3007120EAB9966FA79",201,"tpg",4153995264,305,841170944,758087680,901,0,0,103109046,"",4,23,0,0,64080,2,2887053312]] ,"torrentc": "2001899868"} This response as we can see is not just like a dictionary but it's values are in the form of lists.Now,is there a way I can deal with this string as a dictionary .I'm only interested in the value field of torrents key which again is a list of lists. " life isn't heavy enough,it flies away and floats far above action" --------------------------------- How would you spend $50,000 to create a more sustainable environment in Australia? Go to Yahoo!7 Answers and share your idea. -------------- next part -------------- An HTML attachment was scrubbed... URL: From hzqij1978 at gmail.com Tue Jun 12 11:46:22 2007 From: hzqij1978 at gmail.com (hzqij) Date: Tue, 12 Jun 2007 15:46:22 -0000 Subject: a question about unicode in python Message-ID: <1181663182.251071.10540@i13g2000prf.googlegroups.com> i have a python source code test.py # -*- coding: UTF-8 -*- # s is a unicode string, include chinese s = u'??' then i run $ python test.py UnicodeDecodeError: 'utf8' codec can't decode bytes in position 0-1: invalid data by in python interactive, it is right >>> s = u'??' why? From devicerandom at gmail.com Thu Jun 28 12:45:46 2007 From: devicerandom at gmail.com (massimo s.) Date: Thu, 28 Jun 2007 09:45:46 -0700 Subject: problem with hack using multiple inheritance for plugins In-Reply-To: <4683d4a6$0$26080$426a74cc@news.free.fr> References: <1183026288.857294.91620@q69g2000hsb.googlegroups.com> <1183028051.940679.145680@q69g2000hsb.googlegroups.com> <46839f4c$0$22380$426a74cc@news.free.fr> <1183034478.587345.214570@w5g2000hsg.googlegroups.com> <1183036068.348031.240690@n60g2000hse.googlegroups.com> <4683d4a6$0$26080$426a74cc@news.free.fr> Message-ID: <1183049146.983151.258760@m36g2000hse.googlegroups.com> Uh, oh. I think I found the bug, and it was a *really stupid bug*. The list of GUI_PLUGINS was empty... so there was no plugin class that was inherited. I'm embarrassed to have wasted your time that way. However I learned a lot about new-style classes and so on, so for me it was a learning experience nonetheless. Really sorry for wasting your time. I should use a debugger, I know. : ( Thanks a lot for your patience, M. From paddy3118 at googlemail.com Wed Jun 20 15:44:42 2007 From: paddy3118 at googlemail.com (Paddy) Date: Wed, 20 Jun 2007 19:44:42 -0000 Subject: Packing a simple dictionary into a string - extending struct? In-Reply-To: References: Message-ID: <1182368682.823417.30880@q75g2000hsh.googlegroups.com> On Jun 20, 12:19 pm, "Jonathan Fine" wrote: > Hello > > I want to serialise a dictionary, whose keys and values are ordinary strings > (i.e. a sequence of bytes). > > I can of course use pickle, but it has two big faults for me. > 1. It should not be used with untrusted data. > 2. I want non-Python programs to be able to read and write these > dictionaries. > > I don't want to use XML because: > 1. It is verbose. > 2. It forces other applications to load an XML parser. > > I've written, in about 80 lines, Python code that will pack and unpack (to > use the language of the struct module) such a dictionary. And then I > thought I might be reinventing the wheel. But so far I've not found > anything much like this out there. (The closest is work related to 'binary > XML' -http://en.wikipedia.org/wiki/Binary_XML.) > > So, what I'm looking for is something like and extension of struct that > allows dictionaries to be stored. Does anyone know of any related work? > > -- > Jonathan Fine You could use YAML or KSON then compress the output if size is an issue. - Paddy. From pydecker at gmail.com Wed Jun 27 14:31:56 2007 From: pydecker at gmail.com (Peter Decker) Date: Wed, 27 Jun 2007 14:31:56 -0400 Subject: Tabbed windows Support in Python In-Reply-To: <1ef9860e0706271102m466cf4a7k1f55f76517d456b3@mail.gmail.com> References: <1ef9860e0706271102m466cf4a7k1f55f76517d456b3@mail.gmail.com> Message-ID: On 6/27/07, senthil arasu wrote: > Hi, > Currently iam implementing GUI Framework for supporting Tabbed windows to > render different HTML Pages. > A row of tabs facilitated for navigation of pages. > > Iam expecting some classes like "QTabWidget" whick provided by Qt Libarary. > After starting my implementation i came to know Tkinter not supports tabbed > windows > > is there anybody to help me how to proceed further. Do yourself a favor and start off right: use the Dabo framework for your UI. You can get information about it at http://dabodev.com. You can use their Class Designer to create your tabbed windows visually instead of having to write code. -- # p.d. From newsgroups at debain.org Fri Jun 29 16:59:03 2007 From: newsgroups at debain.org (Samuel) Date: Fri, 29 Jun 2007 20:59:03 +0000 (UTC) Subject: ANNOUNCE: Exscript 0.9 (Initial Release) Message-ID: Introduction ------------- Exscript is a scripting language for automating Telnet or SSH sessions. It supports a wide range of features, such as parallelization, AAA authentication methods, TACACS, and a very simple template language. Exscript itself is written in Python, and it should run on any platform where Python supports OS threads. This is the initial public release. Dependencies ------------- Python 2.2 or better Python Crypto module Download Exscript ------------------ Release: http://exscript.googlecode.com/files/exscript-0.9.tgz SVN instructions: http://code.google.com/p/exscript/source Links ------ Exscript project page: http://code.google.com/p/exscript/ Mailing list: http://groups.google.com/group/exscript Bug tracker: http://code.google.com/p/exscript/issues/list Browse the source: http://exscript.googlecode.com/svn/trunk/ From bruno.42.desthuilliers at wtf.websiteburo.oops.com Thu Jun 28 03:17:46 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Thu, 28 Jun 2007 09:17:46 +0200 Subject: listing the type of an object In-Reply-To: <71af3$4682d18c$d443bb3a$9028@news.speedlinq.nl> References: <71af3$4682d18c$d443bb3a$9028@news.speedlinq.nl> Message-ID: <46836088$0$29024$426a74cc@news.free.fr> Stef Mientki a ?crit : > How can I list a type of an object instance ? > > I tried: > > class tLED (tDevice): Do yourself (and the world) a favour and give up hungarian notation... This should be: class Led(Device): #... > def some_proc(self): > print 'type(self)', type(self) > > But i gives me: > type(self) looks like Device is an old style class. > Moreover, I want even the type to be listed by it's ancestor, like this > > class tDevice: > def some_other_proc: > print 'type(self)', type(self) Try this: class Device(object): def some_other_proc(self): print self, type(self) class Led(Device): pass led = Led() led.some_other_proc() From jjl at pobox.com Mon Jun 25 15:50:27 2007 From: jjl at pobox.com (John J. Lee) Date: Mon, 25 Jun 2007 19:50:27 GMT Subject: eggs considered harmful References: <87fy4knb1u.fsf@pobox.com> Message-ID: <87wsxru83g.fsf@pobox.com> Harry George writes: > jjl at pobox.com (John J. Lee) writes: [...] >> 2. You can run your own private egg repository. IIRC, it's as simple >> as a directory of eggs and a plain old web server with directory >> listings turned on. You then run easy_install -f URL package_name >> instead of easy_install package_name . The distutils-sig archives >> will have more on this. > > Again, not speaking for anyone else: With 500 OSS packages, all of > which play by the same tarball rules, we don't have resources to > handle eggs differently. You said earlier: > The rules are that a) a very few authorized downloaders obtain > tarballs and put them in a depot and b) other users get tarballs from > the depot and build from source. Not sure how this differs significantly "from running a repository", in the sense I use it above. John From p.lavarre at ieee.org Mon Jun 4 11:53:03 2007 From: p.lavarre at ieee.org (p.lavarre at ieee.org) Date: Mon, 04 Jun 2007 08:53:03 -0700 Subject: FAQ: how to vary the byte offset of a field of a ctypes.Structure In-Reply-To: <1180746230.156083.112110@g37g2000prf.googlegroups.com> References: <1180634138.944362.88590@d30g2000prg.googlegroups.com> <1180746230.156083.112110@g37g2000prf.googlegroups.com> Message-ID: <1180972383.611712.242370@j4g2000prf.googlegroups.com> > > http://docs.python.org/lib/module-pickle.html > > ... concise Python ways of pickling and unpickling > > the (0xFF ** N) possible ways of > > packing N strings of byte lengths of 0..xFE together ... Aye, looks like an exercise left open for the student to complete: >>> pickle.dumps("") "S''\np0\n." >>> >>> pickle.dumps("abc") "S'abc'\np0\n." >>> >>> pickle.loads(pickle.dumps("abc")) 'abc' >>> >>> pickle.dumps(ctypes.c_ubyte(0)) ... TypeError: abstract class >>> From Sabri.Pllana at gmail.com Tue Jun 5 04:56:12 2007 From: Sabri.Pllana at gmail.com (Sabri.Pllana at gmail.com) Date: Tue, 05 Jun 2007 01:56:12 -0700 Subject: CFP: 2008 International Workshop on Multi-Core Computing Systems Message-ID: <1181033772.861657.272670@g4g2000hsf.googlegroups.com> We apologize if you receive multiple copies of this call for papers. *********************************************************************** 2008 International Workshop on Multi-Core Computing Systems (MuCoCoS'08) Barcelona, Spain, March 4 - 7, 2008; in conjunction with CISIS'08. *********************************************************************** Context ------- - The improvement of the processor performance by increasing the clock rate has reached its technological limits. Increasing the number of processor cores rather than clock rate can give better performance and reduce problems like energy consumption, heat dissipation and design complexity. We are witnessing the emergence of multi-core processors in all markets from laptops and game consoles to servers and supercomputers. Topics of Interest ------------------ - The topics of the workshop include but are not limited to: - multi-core architectures - interconnection networks - multi-core embedded systems - programming languages and models - algorithms for multi-core computing systems - applications for multi-core systems - performance modeling and evaluation of multi-core systems - design space exploration - resource usage optimization - tool-support for multi-core systems - compilers, runtime and operating systems Submission Guidelines --------------------- - The papers should be prepared using the IEEE CS format (instructions for LaTex users are available at ), and no longer than 6 pages. Submitted papers will be carefully evaluated based on originality, significance to workshop topics, technical soundness, and presentation quality. - Submission of the paper implies that should the paper be accepted, at least one of the authors will register and present the paper at the workshop. Proceedings of the workshop will be published by IEEE Computer Society Press. The best papers presented at the workshop will be selected for publication in an international journal. - The papers should be submitted electronically via CISIS'08 website Important Dates --------------- - Paper submission deadline: October 10, 2007 - Notification: November 25, 2007 - Registration: December 15, 2007 - Final version of the paper: January 15, 2008 - Workshop: March 4 - 7, 2008 Keynote Speaker --------------- - David A. Bader Head of the Sony-Toshiba-IBM center of competence for the Cell BE processor. Workshop Co-chairs ------------------ - Leonard Barolli , Fukuoka Institute of Technology, Japan - Sabri Pllana , University of Vienna, Austria - Fatos Xhafa , Polytechnic University of Catalonia, Spain Program Committee ----------------- - David A. Bader, Georgia Institute of Technology, USA - Leonard Barolli, Fukuoka Institute of Technology, Japan - Siegfried Benkner, University of Vienna, Austria - Luca Benini, University of Bologna, Italy - Rajkumar Buyya, University of Melbourne, Australia - Michael McCool, University of Waterloo, and RapidMind Inc., Canada - Lasse Natvig, Norwegian University of Science and Technology, Norway - Sabri Pllana, University of Vienna, Austria - Vivek Sarkar, IBM Research, T.J. Watson Research Center, USA - Thomas Sterling, Caltech and Louisiana State University, USA - Jesper Larsson Tr?ff, C&C Research labs, NEC Europe Ltd, Germany - Manolis Vavalis, CERETETH, Greece - Brian Vinter, University of Copenhagen, Denmark - Fatos Xhafa, Polytechnic University of Catalonia, Spain - Hans Zima, University of Vienna, Austria, and JPL/Caltech, USA From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Sat Jun 9 06:53:54 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Sat, 09 Jun 2007 12:53:54 +0200 Subject: Python's "only one way to do it" philosophy isn't good? References: <1181368143.874341.273140@r19g2000prf.googlegroups.com> Message-ID: <5cvf62F32relhU1@mid.individual.net> Gabriel Genellina wrote: > For what I can > remember of my first love (Physics): if you have a small ball > moving inside a spherical cup, it would be almost crazy to use > cartesian orthogonal coordinates and Newton's laws to solve it - > the "obvious" way would be to use spherical coordinates and the > Lagrangian formulation (or at least I hope so Yep, that's right. > - surely knowledgeable people will find more "obviously" which is > the right way). No, this case is IMHO almost classical. Movement with planar constraints can be solved quite easy using Lagrange. > All classical mechanics formulations may be equivalent, but > in certain cases one is much more suited that the others. Or: Lagrange is the only obvious way to describe movement with constraints. Regards, Bj?rn -- BOFH excuse #80: That's a great computer you have there; have you considered how it would work as a BSD machine? From gagsl-py2 at yahoo.com.ar Tue Jun 12 07:59:26 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 12 Jun 2007 08:59:26 -0300 Subject: Postpone creation of attributes until needed References: <1181553891.447344.109390@g4g2000hsf.googlegroups.com> <1181559496.911368.219210@p77g2000hsh.googlegroups.com> <1181564855.890242.116840@m36g2000hse.googlegroups.com> <1181626546.323759.80500@i13g2000prf.googlegroups.com> Message-ID: En Tue, 12 Jun 2007 08:18:40 -0300, Steven D'Aprano escribi?: > On Mon, 11 Jun 2007 22:35:46 -0700, Frank Millman wrote: > >> Because, as I have tried to explain elsewhere (probably not very >> clearly), not all the information required to perform compute() is >> available at __init__ time. > > I'm sorry, but this explanation doesn't make sense to me. > > Currently, something like this happens: > > (1) the caller initializes an instance > => instance.x = some known value > => instance.y is undefined > (2) the caller tries to retrieve instance.y > (3) which calls instance.__getattr__('y') > (4) which calls instance.compute() > => which forces the necessary information to be available > => instance.__dict__['y'] = some value > (5) finally returns a value for instance.y > > Since, as far as I can tell, there is no minimum time between creating > the > instance at (1) and trying to access instance.y at (2), there is no > minimum time between (1) and calling compute() at (4), except for the > execution time of the steps between them. So why not just make compute() > the very last thing that __init__ does? As far as I understand what the OP said, (2) may never happen. And since (4) is expensive, it is avoided until it is actually required. -- Gabriel Genellina From pinkfloydhomer at gmail.com Thu Jun 7 08:33:48 2007 From: pinkfloydhomer at gmail.com (pinkfloydhomer at gmail.com) Date: Thu, 07 Jun 2007 12:33:48 -0000 Subject: Bragging about Python Message-ID: <1181219628.841553.283510@p77g2000hsh.googlegroups.com> Is there a resource somewhere on the net that can be used to quickly and effectively show Python's strengths to non-Python programmers? Small examples that will make them go "Wow, that _is_ neat"? From bugmagnet at gmail.com Fri Jun 22 05:49:22 2007 From: bugmagnet at gmail.com (bugmagnet at gmail.com) Date: Fri, 22 Jun 2007 09:49:22 -0000 Subject: Internationalised email subjects In-Reply-To: <1182496538.387301.122670@i38g2000prf.googlegroups.com> References: <1182337500.638044.63470@e9g2000prf.googlegroups.com> <46791592$0$5719$edfadb0f@dread14.news.tele.dk> <1182346499.123234.279880@e9g2000prf.googlegroups.com> <1182417604.446766.47660@e9g2000prf.googlegroups.com> <1182417823.793678.323530@a26g2000pre.googlegroups.com> <467B5D56.7060208@v.loewis.de> <1182496538.387301.122670@i38g2000prf.googlegroups.com> Message-ID: <1182505762.845544.314940@e9g2000prf.googlegroups.com> Thanks Richie, I've tried removing the encode('GB2312') line, so the code looks like this: h = Header(subject, 'GB2312') However, this line still causes the following error message: Traceback (most recent call last): File "/home/web88/html/app/sendmail.py", line 314, in h = Header(subject, 'GB2312') File "/usr/lib/python2.2/email/Header.py", line 188, in __init__ self.append(s, charset, errors) File "/usr/lib/python2.2/email/Header.py", line 272, in append ustr = unicode(s, incodec, errors) LookupError: unknown encoding: gb2312 ) Any ideas? From conor.robinson at gmail.com Mon Jun 18 20:23:35 2007 From: conor.robinson at gmail.com (py_genetic) Date: Tue, 19 Jun 2007 00:23:35 -0000 Subject: Efficient way of generating original alphabetic strings like unix file "split" In-Reply-To: <1181858555.994606.56650@i13g2000prf.googlegroups.com> References: <1181846461.238047.84140@j4g2000prf.googlegroups.com> <87d4zyqoy5.fsf@merkury.smsnet.pl> <1181857180.456039.252940@q19g2000prn.googlegroups.com> <1181858555.994606.56650@i13g2000prf.googlegroups.com> Message-ID: <1182212615.105549.301080@n15g2000prd.googlegroups.com> On Jun 14, 3:02 pm, "mensana... at aol.com" wrote: > On Jun 14, 4:39 pm, py_genetic wrote: > > > > You didn't try hard enough. :) > > > >http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/190465 > > > > -- > > > HTH, > > > Rob > > > Thanks Rob, "permutation" was the keyword I shcould have used! > > See my other post to see if that is indeed what you mean. Thanks, mensanator I see what you are saying, I appreciate you clarification. I modified the unique version to fit my needs, sometimes you just want the first x unique combinations and of the right "width" (A or AA or AAA...) string, so I reworked it a bit to be more efficient. Isn't this a case of base^n-1 for # unique combinations, using the alphabet: 26^strlen - 1 or to figure out strlen from #of combinations needed: ln(26 * #ofcobinations needed)/ ln(26) obviously a float but a pritty good idea of strlen needed when rounded? From a.kaur11 at gmail.com Tue Jun 12 05:15:39 2007 From: a.kaur11 at gmail.com (a.kaur11 at gmail.com) Date: Tue, 12 Jun 2007 02:15:39 -0700 Subject: Fight Stopping AIDS, Let's Do it... Message-ID: <1181639739.110641.109580@q19g2000prn.googlegroups.com> Hi Friends, Let's Stop AIDS, it's increasing like a forest fire... See the page below and learn more about it. www.chulbul.com/aids.htm Let's Know more about stopping AIDS today !! ________________________--- Join the Revolution !! http://www.orkut.com/Community.aspx?cmm=27495757 From nick at craig-wood.com Mon Jun 25 05:30:06 2007 From: nick at craig-wood.com (Nick Craig-Wood) Date: Mon, 25 Jun 2007 04:30:06 -0500 Subject: Chroot Jail Not Secure for Sandboxing Python? References: <1182748892.916068.146780@p77g2000hsh.googlegroups.com> <467f55f7$0$20850$9b622d9e@news.freenet.de> <1182752545.475065.30310@k79g2000hse.googlegroups.com> Message-ID: gregpinero at gmail.com wrote: > On Jun 25, 1:43 am, "Martin v. L?wis" wrote: > > You have to define your threat model. If the threat to prevent is > > a malicious user getting at your data, or spreading a virus > > through your files, then chroot is perfectly adequate. > > Yeah, sounds like my threat model. Maybe prevent someone sending > spam, or DOS from my server too. It all depends on how much stuff you put in your chroot! If you don't put bin/sh in the chroot then you'll stop a lot of exploits from working. If you don't allow the chrooted user write permission to the chroot then you will anyone uploading a shell or any other binaries, just leaving you with the binaries in the chroot to worry about. Nothing stops someone running os.fork() from python and spawning processes to do bad stuff. However in order to do that they would have to have compromised your .py and sent some code to exec(), or found a buffer overflow within python. It is getting increasingly unlikely but not impossible. Note that root can break out of a chroot, so your users must not be root in the chroot. Chroots provide a reasonable level of security. If you are truly paranoid about security then you want to check out selinux (as made originally by the NSA). >From the selinux FAQ :- The Security-enhanced Linux kernel enforces mandatory access control policies that confine user programs and system servers to the minimum amount of privilege they require to do their jobs. When confined in this way, the ability of these user programs and system daemons to cause harm when compromised (via buffer overflows or misconfigurations, for example) is reduced or eliminated. -- Nick Craig-Wood -- http://www.craig-wood.com/nick From ahlongxp at gmail.com Mon Jun 11 20:38:07 2007 From: ahlongxp at gmail.com (ahlongxp) Date: Tue, 12 Jun 2007 00:38:07 -0000 Subject: skip next item in list In-Reply-To: References: <1181573389.186279.108590@g37g2000prf.googlegroups.com> Message-ID: <1181608687.756925.179220@r19g2000prf.googlegroups.com> Thanks to all of you. I think the next() trick is the one I'm looking for. -- ahlongxp Software College,Northeastern University,China ahlongxp at gmail.com http://www.herofit.cn From apatheticagnostic at gmail.com Thu Jun 7 12:42:03 2007 From: apatheticagnostic at gmail.com (kaens) Date: Thu, 7 Jun 2007 12:42:03 -0400 Subject: MySQL InterfaceError In-Reply-To: <01d301c7a915$ccc10e40$0f01a8c0@desktop9> References: <001e01c7a6f3$e687ed40$0f01a8c0@desktop9> <002901c7a6f4$f55e56a0$0f01a8c0@desktop9> <008e01c7a7a5$ddaf8ae0$0f01a8c0@desktop9> <163f0ce20706061650k5708926ck449c53bf0bb39a81@mail.gmail.com> <016a01c7a897$2fbd4650$0f01a8c0@desktop9> <163f0ce20706062024o556038f5te71ddacfc64c473e@mail.gmail.com> <01d301c7a915$ccc10e40$0f01a8c0@desktop9> Message-ID: <163f0ce20706070942y4c7c059fwccb368f69eaf2a71@mail.gmail.com> On 6/7/07, Joe wrote: > > Huh the only thing I can find on InterfaceError is "Errors related to > > the database interface and not the database itself." You might be able > > to get some info from connection.info() . . . > > Yeah, I wish there was more documentation about this type of error. The > only thing info() tells me is that the connection is open through id ######. > > > Are you using utf8? MySQLdb seems to have some problems with that. > > Also, I assume you've tried catching the error and printing the error > > message, right? > > Yes, we are using utf8. What kind of problems can be seen with it? This is > all I have run across so far. What type of encoding would you suggest? I > am still new at some of this stuff, so if you could possibly explain > (off-topic, so a link is fine) the differences between database encodings I > would be grateful. > > And, yes, printing the error message returns absolutely nothing. The tuple > following InterfaceError is both the error code and message. Unfortunately, > it will only give me (0, '') which isn't much help. > > Thanks again! > > Jough > > I really don't know what kinds of errors have cropped up with utf8, or what encoding you should use. The one utf8 error I saw online was related to the character_set_name() call - you could try commenting that out, and all the references to the variable set, and see if your queries work then. I don't know if that's your problem or not. I guess you should go to the MySQLdb site and open a bug report there or something. Wish I knew enough about it to help you out more, but really, I just use it, and I've yet to have a problem with it. From gagsl-py2 at yahoo.com.ar Sat Jun 9 02:35:48 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 09 Jun 2007 03:35:48 -0300 Subject: Python's "only one way to do it" philosophy isn't good? References: <1181368143.874341.273140@r19g2000prf.googlegroups.com> Message-ID: En Sat, 09 Jun 2007 02:49:03 -0300, WaterWalk escribi?: > I've just read an article "Building Robust System" by Gerald Jay > Sussman. The article is here: > http://swiss.csail.mit.edu/classes/symbolic/spring07/readings/robust-systems.pdf > > In it there is a footprint which says: > "Indeed, one often hears arguments against building exibility into an > engineered sys- > tem. For example, in the philosophy of the computer language Python it > is claimed: > \There should be one|and preferably only one|obvious way to do > it."[25] Science does > not usually proceed this way: In classical mechanics, for example, one > can construct equa- > tions of motion using Newtonian vectoral mechanics, or using a > Lagrangian or Hamiltonian > variational formulation.[30] In the cases where all three approaches > are applicable they are > equivalent, but each has its advantages in particular contexts." > > I'm not sure how reasonable this statement is and personally I like > Python's simplicity, power and elegance. So I put it here and hope to > see some inspiring comments. I think the key is the word you ommited in the subject: "obvious". There should be one "obvious" way to do it. For what I can remember of my first love (Physics): if you have a small ball moving inside a spherical cup, it would be almost crazy to use cartesian orthogonal coordinates and Newton's laws to solve it - the "obvious" way would be to use spherical coordinates and the Lagrangian formulation (or at least I hope so - surely knowledgeable people will find more "obviously" which is the right way). All classical mechanics formulations may be equivalent, but in certain cases one is much more suited that the others. -- Gabriel Genellina From MI5Victim at mi5.gov.uk Fri Jun 8 09:24:39 2007 From: MI5Victim at mi5.gov.uk (MI5Victim at mi5.gov.uk) Date: 8 Jun 2007 13:24:39 GMT Subject: MI5 Persecution: Watch Out, Forger About 27/9/95 (3590) Message-ID: From: ray at ultimate-tech.com (Ray Dunn) Newsgroups: uk.misc,soc.culture.british Subject: Re: An apology from Mike Corley Date: Wed Sep 27 14:20:36 1995 In referenced article, David Wooding says... >Well, Mike Corley might or might not have written the apologies, but I >think not. I thought the following line both witty and imaginative. > >>>It was the razor blades stuffed down between the keys that told me. Corley himself denies posting this "apology", but I'm impressed if it is a forgery. Here's the header of my received email. It looks very genuine except for the fact that postings to newsgroups are directed through demon's mail to news gateway, which is strange. Also the message id is which seems to be in a different format from previous Corley postings, e.g. Received: from SpoolDir by ULTIMATE (Mercury 1.20); 26 Sep 95 12:00:14 +0500 >Return-path: >Received: from mail.torfree.net by smtp.ultimate-tech.com (Mercury 1.20); > 26 Sep 95 12:00:04 +0500 >Received: from bloor.torfree.net ([199.71.188.18]) by mail.torfree.net > (/\==/\ Smail3.1.28.1 #28.6; 16-jun-94) > via sendmail with smtp id > for ; Tue, 26 Sep 95 11:31 EDT >Received: from torfree.net by bloor.torfree.net with smtp > (Smail3.1.28.1 #6) id m0sxbx2-000JEeC; Tue, 26 Sep 95 11:29 EDT >Message-Id: >Apparently-To: bu765 at torfree.net, snail at objmedia.demon.co.uk, > ray at ultimate-tech.com, Frank at acclaim.demon.co.uk, > p.marshall at axion.bt.co.uk, me93jrb at brunel.ac.uk, > mikeh at mordor.com, > michael at everyman.demon.co.uk, tim at xara.co.uk, > Alan.Holmes at brunel.ac.uk, uk.misc at news.demon.co.uk, > uk-misc at news.demon.co.uk, uk-media at news.demon.co.uk, > uk.media at news.demon.co.uk, uk.legal at news.demon.co.uk, > uk-legal at news.demon.co.uk, alt-conspiracy at news.demon.co.uk, > alt.conspiracy at news.demon.co.uk, > soc.culture.british at news.demon.co.uk, > soc-culture-british at news.demon.co.uk, > soc-culture-canada at news.demon.co.uk, > soc.culture.canada at news.demon.co.uk >Newsgroups: uk.misc, uk.media, soc.culture.british, soc.culture.canada, uk.legal, alt.conspiracy >From: bu765 at torfree.net (Mike Corley) >Subject: Oops! Sorry! >Organization: Toronto Free-Net >X-Newsreader: TIN [version 1.2 PL2] >Date: Thu, 26 Sep 1995 01:23:45 GMT >Lines: 27 >X-PMFLAGS: 33554560 -- Ray Dunn (opinions are my own) | Phone: (514) 938 9050 Montreal | Phax : (514) 938 5225 ray at ultimate-tech.com | Home : (514) 630 3749 3590 From raims at dot.com Wed Jun 27 18:35:03 2007 From: raims at dot.com (Lawrence Oluyede) Date: Thu, 28 Jun 2007 00:35:03 +0200 Subject: glob.glob standardization References: <1182982000.940609.201250@k79g2000hse.googlegroups.com> Message-ID: <1i0e6u4.clqnam14vyiu0N%raims@dot.com> billiejoex wrote: > Don't you think it would be more convenient for glob.glob to return > file names only in any case, like os.listdir do? AFAIK it's a wanted behavior. The doc says: """ Notice how any leading components of the path are preserved. """ -- Lawrence, oluyede.org - neropercaso.it "It is difficult to get a man to understand something when his salary depends on not understanding it" - Upton Sinclair From jitudon at hotmail.com Tue Jun 12 04:45:26 2007 From: jitudon at hotmail.com (jitudon at hotmail.com) Date: Tue, 12 Jun 2007 01:45:26 -0700 Subject: Autocompletion in interactive mode doesn't work in 2.5.1 In-Reply-To: References: Message-ID: <1181637926.874587.150270@a26g2000pre.googlegroups.com> On Jun 12, 9:36 am, "Papalagi Pakeha" wrote: > Hi all, > > How can I turn on autocompletion when I push in python 2.5.1 > interactive mode? E.g. to give me a list of all methods and attributes > of a given object. > > It works great on my Linux / Ubuntu 7.04 installation but doesn't work > on Solaris 10 (x86). I have libreadline.so and libncurses.so installed > and "import readline" is executed during startup, but still > doesn't work. ArrowUp and ArrowDown however work and I can browse the > history of commands so I believe readline is installed and loaded > correctly. > > Any hints? > > Thanks > > PaPa http://docs.python.org/lib/module-rlcompleter.html From tinaweb at bestemselv.com Sun Jun 17 03:18:05 2007 From: tinaweb at bestemselv.com (Tina I) Date: Sun, 17 Jun 2007 09:18:05 +0200 Subject: Goto In-Reply-To: References: <1181762459.749538.151730@z28g2000prd.googlegroups.com> Message-ID: Daniel Nogradi wrote: >> How does one effect a goto in python? I only want to use it for debug. >> I dasn't slap an "if" clause around the portion to dummy out, the >> indentation police will nab me. > > > http://entrian.com/goto/ LOL!! * major flashback to horrible BASIC programs from the eighties * Back then I took a course in structured BASIC programming (now there is a contradiction in terms) and the instructor warned about goto time and time again. But his biggest mistake was to tell us that if we had to use goto at least we should explain it in a comment. So we would turn in programs with sections like: 100 IF S$="YES" THEN GOTO 150 110 REM Go to line 150 if S$ is Yes Tina From dak at gnu.org Wed Jun 20 17:21:24 2007 From: dak at gnu.org (David Kastrup) Date: Wed, 20 Jun 2007 23:21:24 +0200 Subject: The Modernization of Emacs: terminology buffer and keybinding References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182272495.990807.99110@a26g2000pre.googlegroups.com> <87tzt3ihev.fsf@kobe.laptop> <1182370216.961241.6960@n60g2000hse.googlegroups.com> <85zm2ufjpb.fsf@lola.goethe.zz> <1182372592.803332.288260@u2g2000hsc.googlegroups.com> <1182373919.262388.100740@c77g2000hse.googlegroups.com> Message-ID: <85r6o6fhkb.fsf@lola.goethe.zz> Twisted writes: > On Jun 20, 4:49 pm, Twisted wrote: >> On Jun 20, 4:35 pm, David Kastrup wrote: >> > Twisted writes: >> > > I continue to suspect that there's an ulterior motive for making and >> > > keeping certain software actively beginner-hostile; a certain macho >> > > elitism also seen with light aircraft pilots and commented on at >> > >www.asktog.com(exactURL escapes me; sorry). >> >> > You are babbling. >> >> No, I am not. You, however, are being gratuitously insulting. > > I have that exact URL now -- > http://www.asktog.com/columns/027InterfacesThatKill.html Utterly unrelated to Emacs. -- David Kastrup, Kriemhildstr. 15, 44793 Bochum From steve at holdenweb.com Sat Jun 2 13:11:05 2007 From: steve at holdenweb.com (Steve Holden) Date: Sat, 02 Jun 2007 13:11:05 -0400 Subject: Python 2.3 ODBC Datetime limitations In-Reply-To: <33cd6d8d0706011112w554ee6darea56f0977e9e3216@mail.gmail.com> References: <33cd6d8d0706011112w554ee6darea56f0977e9e3216@mail.gmail.com> Message-ID: <4661A4A9.60805@holdenweb.com> YuePing Lu wrote: > Hello, > > Has any of you ever used Python odbc to retrieve data from a relational DB? > > I encountered a problem where it can't handle datetime _earlier than > _*1969*, and _later than _*2040*. It just returned some garbage strings > when I call str(my_date_object). > > When I call strptime to convert the value I got ValueError exception: > > # Table records > for record in self._records: > columns = [] > for i in range(len(self._description)): > if self._description[i][1]=='DATE': > strDate=str(record[i]) > try: > #convert the date format to be mm/dd/yyyy: > oDate=time.strptime(strDate) #convert to struct_time object > strfDate=time.strftime("%m/%d/%Y", oDate) > > columns.append(strfDate) > except ValueError, msg: > raise "Date converstion error", msg > > ... > Any other solutions that you've heard? > > Thanks very much in advance, > Reading the documentation for the time module, you will see: The epoch is the point where the time starts. On January 1st of that year, at 0 hours, the ``time since the epoch'' is zero. For Unix, the epoch is 1970. To find out what the epoch is, look at gmtime(0). The functions in this module do not handle dates and times before the epoch or far in the future. The cut-off point in the future is determined by the C library; for Unix, it is typically in 2038. So this may not be a problem with the odbc module, which isn't the most up-to-date piece of software on the block but is mostly reliable for simple purposes. I'd try something from the datetime module. When I retrieve a date column from a postgreSQL database using ODBC is see: >>> curs.execute("SELECT orginvdt FROM organization WHERE orginvdt IS NOT NULL") 0 >>> row = curs.fetchone() >>> row (,) >>> dbidate = row[0] >>> dir(dbidate) [] So it isn't easy to know just by looking what you can do with a dbitdate. But if you can hack around with the time module you can probably hack around with datetime too, and that's a more capable module. However it's possible that the epoch-to-2038 restriction is actually imposed byt he odbc drivers, in which case you will need to look for another Python driver module for your database. It would have been helpful if you hadn't trapped the exception so that we could have seen the exact traceback - this would have given man more clues as to what was going on. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden ------------------ Asciimercial --------------------- Get on the web: Blog, lens and tag your way to fame!! holdenweb.blogspot.com squidoo.com/pythonology tagged items: del.icio.us/steve.holden/python All these services currently offer free registration! -------------- Thank You for Reading ---------------- From jackt123 at gmail.com Mon Jun 25 20:26:25 2007 From: jackt123 at gmail.com (JackT) Date: Tue, 26 Jun 2007 00:26:25 -0000 Subject: The Modernization of Emacs: terminology buffer and keybinding In-Reply-To: <1182817388.736770.59590@c77g2000hse.googlegroups.com> References: <87tzt3ihev.fsf@kobe.laptop> <1182370216.961241.6960@n60g2000hse.googlegroups.com> <85zm2ufjpb.fsf@lola.goethe.zz> <1182372592.803332.288260@u2g2000hsc.googlegroups.com> <1182373919.262388.100740@c77g2000hse.googlegroups.com> <85r6o6fhkb.fsf@lola.goethe.zz> <1182375045.626510.188170@m36g2000hse.googlegroups.com> <85myyufgwj.fsf@lola.goethe.zz> <1182375528.985142.293900@q69g2000hsb.googlegroups.com> <1182545268.055596.228700@i38g2000prf.googlegroups.com> <1182547318.325617.16370@o11g2000prd.googlegroups.com> <1182657564.912472.55570@g4g2000hsf.googlegroups.com> <1182713541.449966.195970@o61g2000hsh.googlegroups.com> <1182808864.211161.155920@u2g2000hsc.googlegroups.com> <1182817388.736770.59590@c77g2000hse.googlegroups.com> Message-ID: <1182817585.132850.43310@p77g2000hsh.googlegroups.com> On Jun 26, 12:23 am, JackT wrote: > the ONE TRUE EMACS has had GUI capability > since early 1980s. Sorry, I meant early 1990s. I believe it was 1993 or so (it is in the web page). - JackT From nick at craig-wood.com Wed Jun 27 13:30:07 2007 From: nick at craig-wood.com (Nick Craig-Wood) Date: Wed, 27 Jun 2007 12:30:07 -0500 Subject: 16bit hash References: Message-ID: Robin Becker wrote: > Is the any way to get an efficient 16bit hash in python? Here is a 32 bit crc of which you could use the bottom 16 bits as a 16 bit hash... >>> import binascii >>> binascii.crc32("hello world") 222957957 >>> crc = binascii.crc32("hello") >>> crc = binascii.crc32(" world", crc) >>> crc 222957957 >>> And in case you are wondering how fast it is... $ python -m timeit -s 's="."*1024*1024; from binascii import crc32' 'crc32(s)' 100 loops, best of 3: 4.25 msec per loop Which is 235 MB/s Ignore the bit in the binascii docs which says "Since the algorithm is designed for use as a checksum algorithm, it is not suitable for use as a general hash algorithm". Actually CRCs make pretty good hash algorithms if you want something for making a hash table. They make very bad cryptographic hash generators since they are linear and thus easily forgeable. That said you aren't going to be doing any serious crypto with only 16 bits. -- Nick Craig-Wood -- http://www.craig-wood.com/nick From survivedsushi at yahoo.com Wed Jun 27 16:44:57 2007 From: survivedsushi at yahoo.com (Matthew Peter) Date: Wed, 27 Jun 2007 13:44:57 -0700 (PDT) Subject: Return name of caller function? In-Reply-To: <46814B74.9010400@jayloden.com> Message-ID: <354874.53864.qm@web35203.mail.mud.yahoo.com> --- Jay Loden wrote: > > Matthew Peter wrote: > > For example, how do I get this to work? > > > > def func(): > > print "This is", __?__ > > return __caller__ > > > > def echo(): > > print "This is ", __?__ > > return func() > > > > > >>>> print echo() > > This is echo > > This is func > > echo > > This may not be what you're looking for but here's the solution I ended up with > after some help from the list. It's designed for getting the name of an instance > method, but in case it applies to your particular situation: > > #!/usr/bin/python > > import functools > > class TestClass: > def __init__(self): > pass > > def __getattr__(self, name): > try: > return getattr(self.__class__, name) > except AttributeError: > return functools.partial(self.foo, name) > > def foo(self, name, **args): > print "This is", name > > test = TestClass() > test.someMethod() > test.anotherMethod() > > Otherwise the inspect module may be the way to go, as Stephen already pointed out > (though I must admit it seems a very inelegant route, especially compared to > Python's usually clean and clear style). > > -Jay > Thanks for the reply. The goal is to get it working outside of a class. Overloading the method with getattr semi-works but it doesn't work in the larger context of what I am trying to accomplish. You could avoid the exception block in your example: > def __getattr__(self, name): > try: > return getattr(self.__class__, name) > except AttributeError: > return functools.partial(self.foo, name) to: def __getattr__(self, name, *args, **kw): return getattr(self.__class__, name, functools.partial(self.foo, name, *args, **kw)) def foo(self, name, *args, **kw): print "This is", name, args, kw print test.squeaky("I need oil") ____________________________________________________________________________________ Looking for a deal? Find great prices on flights and hotels with Yahoo! FareChase. http://farechase.yahoo.com/ From grue at mail.ru Sun Jun 24 04:15:38 2007 From: grue at mail.ru (Timofei Shatrov) Date: Sun, 24 Jun 2007 08:15:38 GMT Subject: The Modernization of Emacs: terminology buffer and keybinding References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182272495.990807.99110@a26g2000pre.googlegroups.com> <87tzt3ihev.fsf@kobe.laptop> <1182370216.961241.6960@n60g2000hse.googlegroups.com> <85zm2ufjpb.fsf@lola.goethe.zz> <1182372592.803332.288260@u2g2000hsc.googlegroups.com> <1182373919.262388.100740@c77g2000hse.googlegroups.com> <85r6o6fhkb.fsf@lola.goethe.zz> <1182375045.626510.188170@m36g2000hse.googlegroups.com> <85myyufgwj.fsf@lola.goethe.zz> <1182375528.985142.293900@q69g2000hsb.googlegroups.com> <1182545268.055596.228700@i38g2000prf.googlegroups.com> <1182661040.286559.150880@q75g2000hsh.googlegroups.com> Message-ID: <467e27f1.6428764@news.readfreenews.net> On Sun, 24 Jun 2007 04:57:20 -0000, Twisted tried to confuse everyone with this message: >On Jun 23, 2:04 am, Robert Uhl wrote: >> Of course, emacs doesn't take years of mastery. It takes 30, 40 >> minutes. > >I gave it twice that, and it failed to grow on me in that amount of >time. > >> > Besides, ANY interface that involves fumbling around in the dark >> > trying to find a light switch is clunky. >> >> That sounds like vi, not emacs. > >That sounds like any application where you need to read the help, but >"f1" does not bring up a separate help window, switchable with the >main one using alt-tab or the mouse, and navigable using arrows, >pageup, pagedn, and the mouse. The result of that is invariably that >when the document has the focus, the help is open to "help on >switching windows" rather than whatever you need it to be on once the >document has the focus. You can read the help on doing what you want >to do with the document, but to apply it you need to transfer focus >back to the document. If doing that isn't second-nature, you have to >navigate the help away from where you need it to get the focus back to >the document. Now the focus is on the document, but the help you need >isn't displayed next to it anymore. Frustrating? You can't begin to >imagine, I suspect. Apparently, some people are born somehow able to >avoid this problem without having to memorize one or the other piece >of help. You're clearly one of those. I am equally clearly NOT one of >those. Of course, if emacs let you keep THREE windows open and visible >at the same time, instead of being limited to one or a horizontally >split two ... and a cramped 80x10 or so each, at that ... What an idiot. At least get yourt facts straight before posting such bullshit. -- |Don't believe this - you're not worthless ,gr---------.ru |It's us against millions and we can't take them all... | ue il | |But we can take them on! | @ma | | (A Wilhelm Scream - The Rip) |______________| From needpassion at gmail.com Fri Jun 8 18:36:30 2007 From: needpassion at gmail.com (mike) Date: Fri, 08 Jun 2007 15:36:30 -0700 Subject: Could someone show me a sample how to flush the socket sending buffer? Thanks a lot. Message-ID: <1181342190.374220.21800@z28g2000prd.googlegroups.com> I have called the setsockopt() to set no delay after connecting like this way: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect(('192.168.10.1', 21980)) s.setsockopt(socket.SOL_TCP, socket.TCP_NODELAY, 0) s.send("abc at abc.com\n") s.send("123 at hbc.com\n") ...... but still, the server can only receive the first line, and keep waiting for the second line. So, in my mind the second line is still in the sending buffer, and not reach the server side. Any hints would be appreciated. Mike From jackt123 at gmail.com Sun Jun 24 20:48:47 2007 From: jackt123 at gmail.com (JackT) Date: Mon, 25 Jun 2007 00:48:47 -0000 Subject: The Modernization of Emacs: terminology buffer and keybinding In-Reply-To: <1182731526.329068.101540@c77g2000hse.googlegroups.com> References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182272495.990807.99110@a26g2000pre.googlegroups.com> <87tzt3ihev.fsf@kobe.laptop> <1182370216.961241.6960@n60g2000hse.googlegroups.com> <85zm2ufjpb.fsf@lola.goethe.zz> <1182372592.803332.288260@u2g2000hsc.googlegroups.com> <1182373919.262388.100740@c77g2000hse.googlegroups.com> <85r6o6fhkb.fsf@lola.goethe.zz> <1182375045.626510.188170@m36g2000hse.googlegroups.com> <85myyufgwj.fsf@lola.goethe.zz> <1182375528.985142.293900@q69g2000hsb.googlegroups.com> <1182545268.055596.228700@i38g2000prf.googlegroups.com> <1182661040.286559.150880@q75g2000hsh.googlegroups.com> <1182731526.329068.101540@c77g2000hse.googlegroups.com> Message-ID: <1182732527.577903.63600@q75g2000hsh.googlegroups.com> On Jun 25, 12:32 am, Twisted wrote: > > It looks like there are > several utterly different pieces of software that have one thing in > common - the name "emacs"... > > > When you start emacs in a text console, you see this: > > > > Welcome to GNUEmacs, one component of the GNU/Linux operating system. > > Get help C-h (Hold down CTRL and press h) > > Emacsmanual C-h r > > Emacstutorial C-h t Undo changes C-x u > > Really? That is not what I recall seeing. Are you talking aboutemacs- > the-text-mode-editor, oremacs-the-hybrid-somethingorother-when-you- > happen-to-run-it-from-the-command-prompt-on-unix? Because I've been > discussing the former. Everyone now uses http://www.gnu.org/software/emacs/ or a minor derivative of it. Its official distribution FTP location is http://ftp.gnu.org/pub/gnu/emacs/ And for the Windows port, the official FTP is here http://ftp.gnu.org/pub/gnu/emacs/windows/ We don't care about the 1970 version of Emacs, because of course back then there WAS NO GUI. - JackT From showell30 at yahoo.com Wed Jun 20 12:03:17 2007 From: showell30 at yahoo.com (Steve Howell) Date: Wed, 20 Jun 2007 09:03:17 -0700 (PDT) Subject: SimplePrograms challenge In-Reply-To: Message-ID: <526869.48288.qm@web33514.mail.mud.yahoo.com> --- Pete Forman wrote: > Steve Howell writes: > > > Feel free to change the page as you see fit, > although thanks for > > discussing it here first. > > Done. I've moved classes up as unittest depends on > it. > > The changes that I made to classes were: > > 1) Use new style class. > 2) Demonstrate Pythonic use of attribute (no > get/set). > 3) Pare some lines. > -- Thanks! Here's the link, if anybody wants to kibitz: http://wiki.python.org/moin/SimplePrograms My comments: 1) I'm not crazy about having to inherit from object for such a simple class, but I understand that it's best practice. 2) I'm glad you moved the class example up. 3) The median example raises the question of what would happen with an empty list. I don't think it's important to cover that case in the simple example (it's really the responsibility of the caller IMO not to call median with nonsense arguments), but perhaps there is a simple way to fix this? 4) Agreed on Pythonic use of the "balance" attribute. ____________________________________________________________________________________ Shape Yahoo! in your own image. Join our Network Research Panel today! http://surveylink.yahoo.com/gmrs/yahoo_panel_invite.asp?a=7 From robert.kern at gmail.com Thu Jun 21 19:36:55 2007 From: robert.kern at gmail.com (Robert Kern) Date: Thu, 21 Jun 2007 18:36:55 -0500 Subject: eggs considered harmful In-Reply-To: References: Message-ID: Harry George wrote: > ...at least around here. > > I run a corporate Open Source Software Toolkit, which makes hundreds > of libraries and apps available to thousands of technical employees. > The rules are that a) a very few authorized downloaders obtain > tarballs and put them in a depot and b) other users get tarballs from > the depot and build from source. > > Historically, python packages played well in this context. Install > was a simple download, untar, setup.py build/install. > > Eggs and with other setuptools-inspired install processes break this > paradigm. The tarballs are incomplete in the first place. The builds > sometimes wander off to the internet looking for more downloads. The > installs sometimes wander off to the internet looking for > compatibility conditions. (Or rather they try to do so and fail > because I don't let themn through the firewall.) Have you considered establishing a policy that these setuptools-using packages should be installed using the --single-version-externally-managed option to the install command? This does not check for dependencies. Alternately, you can provide a company repository of the tarballs and their depedencies tarballs. Your users can use the easy_install option --find-links to point to that URL such that they do not have to go outside of the firewall to install everything. > These are unacceptable behaviors. I am therefore dropping ZODB3, and > am considering dropping TurboGears and ZSI. If the egg paradigm > spreads, yet more packages will be dropped (or will never get a chance > to compete for addition). I'm sorry to hear that. > I've asked before, and I'll ask again: If you are doing a Python > project, please make a self-sufficient tarball available as well. You > can have dependencies, as long as they are documented and can be > obtained by separate manual download. Given the options I outlined above, you can easily satisfy these requirements for the vast majority of setuptools-using packages that are out there. There are a handful of packages that only distribute the eggs and not the source tarballs, but those are rare. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From steve at holdenweb.com Sat Jun 2 16:15:43 2007 From: steve at holdenweb.com (Steve Holden) Date: Sat, 02 Jun 2007 16:15:43 -0400 Subject: Using PIL to find separator pages In-Reply-To: References: <4660406F.7070506@websafe.com> Message-ID: Steve Holden wrote: > Larry Bates wrote: [...] >> I think I've come up with something that will work. I use PIL >> Image.getcolors() to get colors and take the top 10 colors of my >> background page. I then calculate the average of the R, G, B >> components. That becomes my reference. Then I read a page and >> make the same calculation. I then calculate the absolute value >> of the difference of R, G, B of the two values. Sum those >> together gives something like the average difference between >> the two average colors (at least that is what I think it does). >> This seems to give me small numbers when the pages are the same >> and large numbers when they are different. It isn't super fast >> but it is working. >> >> Thanks for pushing me in the right direction. >> >> -Larry > > Well done! Thanks for letting me know that the basic approach was correct. > > regards > Steve Oh, by the way: instead of averaging over the *whole page*, now average over (say) eight samples each of 10 x 10 pixels or thereabouts. They should all be roughly the same, and they should all be close to the color of the separator color. Seems to me (again, without bothering to actually write the code, which you are far more motivated to do than I anyway) that the much smaller amount of arithmetic will compensate for any loss in accuracy (which I surmise will anyway be trivial if the separator is something like DayGlo green or yellow). Or maybe it's already running "fast enough", and you are already on to the next job? regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden ------------------ Asciimercial --------------------- Get on the web: Blog, lens and tag your way to fame!! holdenweb.blogspot.com squidoo.com/pythonology tagged items: del.icio.us/steve.holden/python All these services currently offer free registration! -------------- Thank You for Reading ---------------- From benc.nospam at gmail.com Fri Jun 15 09:39:17 2007 From: benc.nospam at gmail.com (benc) Date: Fri, 15 Jun 2007 06:39:17 -0700 Subject: unsupported operand type(s) for ^: 'float' and 'float' In-Reply-To: References: Message-ID: <1181914757.149030.3110@p77g2000hsh.googlegroups.com> On Jun 15, 9:21 am, Florian Lindner wrote: > >>> 5.3^4.3 > > Traceback (most recent call last): > File "", line 1, in ? > TypeError: unsupported operand type(s) for ^: 'float' and 'float' That operator... I do not think it means what you think it means. >>> hex(0x1010^0x0110) '0x1100' ^ is the bitwise XOR operator. For exponentiation, use **. >>> 5.3**4.3 1301.326396639844 Hope that helps, --Ben From dmcgarigle at socal.rr.com Sun Jun 24 03:43:02 2007 From: dmcgarigle at socal.rr.com (Dan McGarigle) Date: Sun, 24 Jun 2007 00:43:02 -0700 Subject: convert hex to decimal - ala IBM Maniframe Assembly Language Message-ID: <000001c7b633$4c33d0c0$0200a8c0@danxp> In re: http://mail.python.org/pipermail/python-list/2006-March/371757.html Dear Peter Maas The Intel 80xxx architecture is horrible when compared to an IBM S/360, or S/370, or S/390 or Z machines. IBM mainframes performance is measured in Millions Of Instructions executed per second, and not on some clock speed, But rather, how many millions of completed instructions are executed in 1-second. Numbers like 428 are common MIPS rates. That's 428,000,000 instructions completed by the CPU per second. I can't relate to how many instructions get executed per second on a 2.8Ghz CPU because I can't find out how many cycles each Intel instruction takes.. I really don't care how fast a clock goes. I care about how many instructions are executed per second. As for converting a number from Hex to Decimal we do it this way, with one (1) CVD instruction, on IBM mainframes. START 0 Tell the assembler to start this program at relative location zero ( 0 ). HEX2DEC BALR 6,0 Start the program USING *,6 Tell the assembler to use Register 6 as the base of this program B Step01 Branch to Step01 to get started Hexword DS F Define a storage area of a 4-byte word. Outarea DS PL8 Define a storage area for an 8-byte packed decimal number, max = 999,999,999,999,999 * This is a comment i.e. 999 trillion, 999 billion, 999 million, 999 thousand, 999 ones. Visible DS CL15 Define a storage area for a 15-byte displayable characters area. Step01 EQU * L R5,Hexword Put the 4-byte hexadecimal number into General Purpose Register 5. CVD R5, Outarea Tell the CPU to convert the 4-byte number into a 15 digit signed number in displayable characters UNPK Visible(15),Outarea(8) Make the 15-digit number displayable OI Visible+14,X'F0" Correct the sign of the last digit. BR R14 Return to the operating system END Define the end of the program to the assembler Of course you didn't need to know any of this, except that I am sick of hearing how "great" the Intel architecture is. Phooey ! IBM had INTEL beat into the ground in 1967, (way before the 8088 existed) and has not looked back since. Thanks for accepting a rant from a stranger. Dan McGarigle ( 36 years an IBM mainframe programmer and proud of it, thank you ! ) El Segundo, CA -------------- next part -------------- An HTML attachment was scrubbed... URL: From mccredie at gmail.com Thu Jun 28 14:21:57 2007 From: mccredie at gmail.com (Matimus) Date: Thu, 28 Jun 2007 18:21:57 -0000 Subject: noob question How do I run a Python script. In-Reply-To: <1183051059.795931.299900@q75g2000hsh.googlegroups.com> References: <1183051059.795931.299900@q75g2000hsh.googlegroups.com> Message-ID: <1183054917.256330.102100@a26g2000pre.googlegroups.com> > I installed python, run the interpreter and the script... Are you trying to run the script from the interpreter? You _can_ run scripts from the interpreter, but it isn't as simple as typing the name of the script. To me, that is what it sounds like you are trying to do. I don't know what environment you are using, but at the command line (terminal) you should just type the following to run the script: python cleanmbox.py Actually, if you are using *nix use chmod +x chanmbox.py to tell the os it is executable, and then just run "cleanbox.py". If you are using windows, then you don't even have to do that, just double click on it. -Matt From paddy3118 at googlemail.com Wed Jun 20 15:38:26 2007 From: paddy3118 at googlemail.com (Paddy) Date: Wed, 20 Jun 2007 19:38:26 -0000 Subject: PEP 3107 and stronger typing (note: probably a newbie question) In-Reply-To: References: Message-ID: <1182368306.735573.18770@q75g2000hsh.googlegroups.com> On Jun 20, 7:53 pm, Stephen R Laniel wrote: > Before I ask anything, let me note that this is surely an > old question that has inspired its share of flame wars; I'm > new to Python, but not new to how Internet discussions work. > So if there's a canonical thread or web page that documents > the whole battle, feel free to point me to it. > > Reading [1], I wonder: why isn't the compiler making better > use of (purely optional) type labeling? Why not make a compiler > directive so that > > a) it will check the types of all my arguments and return > values, and maybe even > b) do some type inference up the call stack? > > E.g., > > def( Class1 arg1, Class2 arg2, ..., ClassN argN ): > someStuff() > > would check the types of the arguments, whereas > > def( arg1, arg2, ..., argN): > someStuff() > > would not? I.e., if I *want* strong static > type-checking, why shouldn't I be able to get it? Is it that > allowing this as a compile-time option would mess up too > many knobs to make it optional? > > Again, probably an old debate. I'd like to know why Guido's > decided that not only is strong static typing > productivity-reducing [2], but that it should be *forbidden*. > > [1] -http://www.python.org/dev/peps/pep-3107/ > [2] -http://www.artima.com/intv/strongweakP.html > > -- > Stephen R. Laniel > s... at laniels.org > Cell: +(617) 308-5571http://laniels.org/ > PGP key:http://laniels.org/slaniel.key You have already raised hackles with the title of your post. Python has very strog type checking already. It does not have static type checking which may be what you meant. It seems that if we want to have Python compile down to machine code then we may have to confine names to only refer to objects of one type. (as well as None). I would prefer it if we weren't also required to explicitly state the types of variable names. The reasons are that I am not new to Python and prefer the dynamism of names and the reliance on tests and coverage over static type checking. As you state that you are new to Python, why not try the Python way; gain proficiency; then think again about the issue. If you are still of like mind then your proficiency should enable you to give more convincing reasons to the ccommunity. - Paddy. It would need support. Are you volunteering effort? From showell30 at yahoo.com Sun Jun 3 17:19:53 2007 From: showell30 at yahoo.com (Steve Howell) Date: Sun, 3 Jun 2007 14:19:53 -0700 (PDT) Subject: subexpressions (OT: math) In-Reply-To: <7llbj4-i9c.ln1@lairds.us> Message-ID: <727805.51471.qm@web33506.mail.mud.yahoo.com> What's the square root of -1 radians? :) ____________________________________________________________________________________ Park yourself in front of a world of choices in alternative vehicles. Visit the Yahoo! Auto Green Center. http://autos.yahoo.com/green_center/ From asincero at gmail.com Tue Jun 19 15:40:08 2007 From: asincero at gmail.com (asincero) Date: Tue, 19 Jun 2007 12:40:08 -0700 Subject: Using a switch-like if/else construct versus a dictionary? Message-ID: <1182282008.522677.269730@g4g2000hsf.googlegroups.com> Which is better: using an if/else construct to simulate a C switch or use a dictionary? Example: def foo(): if c == 1: doCase1() elif c == 2: doCase2() elif c == 3: doCase3() elif c == 4: doCase4() elif c == 5: doCase5() else: raise "shouldn't get here" or: def foo(): def doCase1(): pass def doCase2(): pass def doCase3(): pass def doCase4(): pass def doCase5(): pass handle_case = {} handle_case[1] = doCase1() handle_case[2] = doCase2() handle_case[3] = doCase3() handle_case[4] = doCase4() handle_case[5] = doCase5() handle_case[c]() Note that in this situation using OO polymorphism instead of a switch- like construct wouldn't be applicable, or at least I can't see how it could be. Thanks in advance for any tips! -- Arcadio From josiah.carlson at sbcglobal.net Thu Jun 14 15:12:11 2007 From: josiah.carlson at sbcglobal.net (Josiah Carlson) Date: Thu, 14 Jun 2007 12:12:11 -0700 Subject: dynamically generated runtime methods & reflection In-Reply-To: References: Message-ID: Jay Loden wrote: > Josiah Carlson wrote: >> Ahh, so you want to pass the method name to the method that you are >> returning to be called. No problem. >> >> >>> import functools >> >>> >> >>> class foo: >> ... def __getattr__(self, name): >> ... return functools.partial(self.ActualMethod, name) >> ... >> ... def ActualMethod(self, name, *args, **kwargs): >> ... #handle *args and **kwargs based on name! >> ... print name, args, kwargs >> ... >> >>> foo().bar('hello', world=1) >> bar ('hello',) {'world': 1} >> >>> > > Thanks, this is exactly what I was looking for! For some reason functools didn't even show up at all during Google searches...must have just had the wrong search terms. Well, the particular operation is typically called 'currying a function', and unless you know what to look for, it isn't very easy to make happen. On the other hand, it is also relatively easy to implement by hand if necessary. - Josiah From http Fri Jun 22 19:54:16 2007 From: http (Paul Rubin) Date: 22 Jun 2007 16:54:16 -0700 Subject: contextlib.closing annoyance Message-ID: <7xd4zneeaf.fsf_-_@ruckus.brouhaha.com> it looks like contextlib.closing fails to be idempotent, i.e. wrapping closing() around another closing() doesn't work. This is annoying because the idea of closing() is to let you use legacy file-like objects as targets of the "with" statement, e.g. with closing(gzip.open(filename)) as zf: ... but what happens if the gzip library gets updated the dumb way to support the enter and exit methods so you don't need the explicit closing call any more? The dumb way of course is to just call closing() inside the library. It seems to me that closing(closing(f)) ought to do the same thing as closing(f). Let me know if I'm overlooking something. I'm thinking of submitting an RFE. From kerny404 at gmail.com Thu Jun 7 11:42:02 2007 From: kerny404 at gmail.com (andrea) Date: Thu, 07 Jun 2007 08:42:02 -0700 Subject: Designing a graph study program In-Reply-To: References: <1178619753.077639.112510@q75g2000hsh.googlegroups.com> <1178801172.772583.287050@q75g2000hsh.googlegroups.com> Message-ID: <1181230922.397856.202910@q75g2000hsh.googlegroups.com> On 10 Mag, 16:52, Alexander Schliep wrote: > andrea writes: > > On 9 Mag, 09:10, Alexander Schliep wrote: > >> Check outhttp://gato.sf.net(LGPLlicense). It does exactly what you > >> want to do and there is a binary for MacOS X. Algorithms are implemented > >> using Gato's graph class and rudimentary visualizations you get for free > >> by replacing standard data structures (e.g., a vertex queue) by > >> animated ones (AnimatedVertexQueue). > > > Very very nice well done! > > Thanks. > > > I'd like to do something similar, just to learn something new... > > Gato is open source and I'd be happy to collaborate. There are quite a > few areas (e.g. SVG export, displays for data structure contents, more > complete 3D support, polygon edges, running backwards?) which need > work. > > > Could you explain me how you designed it?? How is the step mechanism > > done?? > > The algorithm is executed by a subclass of the Python debugger (see > Gato.py). A Tk event mechanism is used to step to the next line if > you are in running mode. Otherwise the user steps manually. The > visualizations are done with animated data structures, which animate > changes to their internal state with respect to the graph: e.g., when > you add or remove v to/from an AnimatedVertexQueue it changes v's > color. > > Tk has a canvas which does object-oriented drawing. A line is not > just a bunch of pixels but rather an object which you can move, > scale, has callbacks. I dislike Tcl, but Tk is amazing, even it > it looks 1980s. > > There is a paperhttp://algorithmics.molgen.mpg.de/preprints/2000-CATBox-MTCM.pdf > describing the ideas. > > Best, > Alexander Ok thanks a lot for the explanation Alexander... Well I changed my implementation of edges and nodes to this: class node: """nodi di un grafo""" def __init__(self, label, color=None, parent=None, distance=None): self.label = label self.color = color self.parent = parent self.distance = distance def __eq__(self,y): """uguaglianza fra nodi""" return self.label == y.label def __repr__(self): """docstring for __repr__""" return str(self.label) class edge: # CHANGED tutta la gestione di nodi e lati """lato di un grafo""" def __init__(self, u, v, directed=False, w=1): "due lati ed eventualmente il peso associato" self.u = u self.v = v self.w = w self.directed = directed def __repr__(self): """docstring for __repr__""" if self.directed: sym = " --> " else: sym = " --- " return str(self.u) + sym + str(self.v) def __eq__(self,y): if self.directed != y.directed: return False r = (self.u == y.u and self.v == y.v) l = (self.v == y.u and self.u == y.v) if self.directed: # gia controllato che non siano diversi return r else: return r or l Does it make sense?? But now I have some troubles with all the rest ;) For example this code def make_adj_list(self,nodes,edges): """crea la lista di adiacenza""" adj_list = {} for v in nodes: adj_list[v] = [] ... builds an adjacency list of the graph, but now the object Node is not hashable of course! How do I manage this? I think I can use the label adj_list[v.label] = [u.label, etc etc] but then I need another dictionary to go from labels to objects, it's not difficult but look ugly to me, other solutions?? Thanks a lot From grahn+nntp at snipabacken.dyndns.org Tue Jun 19 15:37:32 2007 From: grahn+nntp at snipabacken.dyndns.org (Jorgen Grahn) Date: 19 Jun 2007 19:37:32 GMT Subject: File processing - is Python suitable? References: <1182255317.327241.196330@n2g2000hse.googlegroups.com> Message-ID: On Tue, 19 Jun 2007 05:15:17 -0700, ferrad wrote: > I have not used Python before, but believe it may be what I need. > > I have large text files containing text, numbers, and junk. I want to > delete large chunks process other bits, etc, much like I'd do in an > editor, but want to do it automatically. I have a set of generic > rules that my fingers follow to process these files, which all follow > a similar template. Doesn't your text editor have recordable macros? > Question: can I translate these types of rules into programmatical > constructs that Python can use to process these files? Can Python do > the trick? Impossible to tell, since we do not know these rules. If they need your good judgement, intelligence, knowledge or taste, a good text editor, with careful application of recorded macros, is the way to go. Maybe in combination with a few Perl or Python scripts and special features of the text editor. I often find myself doing that kind of work, when the text I start with is too irregular to be easily machine parsable. On the other hand, if the work is purely mechanical, tedious stuff, there is a fair chance that it can be completely automated using Python. (IMHO, Perl is often a better tool for this kind of work, but few other languages beat Python in this area.) /Jorgen -- // Jorgen Grahn R'lyeh wgah'nagl fhtagn! From allison.william at nospam.gmail.com Thu Jun 28 20:21:57 2007 From: allison.william at nospam.gmail.com (William Allison) Date: Thu, 28 Jun 2007 20:21:57 -0400 Subject: Looking for an interpreter that does not request internet access In-Reply-To: References: Message-ID: James Alan Farrell wrote: > At the risk of sounding clueless, what is "the regular interpreter"? > I've now read several python books, and they all recommend IDLE. > By typing "python" at your command prompt you'll also get an interactive interpreter. From blewguy at hotmail.com Mon Jun 25 16:09:50 2007 From: blewguy at hotmail.com (Miguel Oliveira) Date: Mon, 25 Jun 2007 16:09:50 -0400 Subject: finding an element in a string Message-ID: An HTML attachment was scrubbed... URL: From itkovian at gmail.com Mon Jun 18 06:23:48 2007 From: itkovian at gmail.com (itkovian) Date: Mon, 18 Jun 2007 10:23:48 -0000 Subject: xmlrpclib hangs execution In-Reply-To: <465d9040$0$326$e4fe514c@news.xs4all.nl> References: <45AC0631.8080601@ctw.utwente.nl><465890FB.4030405@utwente.nl> <465A9DC7.2010708@gmail.com> <465d9040$0$326$e4fe514c@news.xs4all.nl> Message-ID: <1182162228.246643.135210@u2g2000hsc.googlegroups.com> I think a better fix than the one I posted below is using the HTTPConnection library, as opposed to the HTTP library from httplib. A patch can be found below: --- /sw/lib/python2.5/xmlrpclib.py 2006-11-29 02:46:38.000000000 +0100 +++ xmlrpclib.py 2007-06-15 16:03:17.000000000 +0200 @@ -1182,23 +1182,13 @@ self.send_user_agent(h) self.send_content(h, request_body) - errcode, errmsg, headers = h.getreply() + response = h.getresponse() + + if response.status != 200: + raise ProtocolError(host + handler, response.status, response.reason, response.msg.headers) - if errcode != 200: - raise ProtocolError( - host + handler, - errcode, errmsg, - headers - ) - - self.verbose = verbose - - try: - sock = h._conn.sock - except AttributeError: - sock = None - - return self._parse_response(h.getfile(), sock) + payload = response.read() + return payload ## # Create parser. @@ -1250,7 +1240,7 @@ # create a HTTP connection object from a host descriptor import httplib host, extra_headers, x509 = self.get_host_info(host) - return httplib.HTTP(host) + return httplib.HTTPConnection(host) From ask at me Fri Jun 8 11:41:19 2007 From: ask at me (alf) Date: Fri, 08 Jun 2007 10:41:19 -0500 Subject: launching default browser Message-ID: Hi, I wonder how to launch from python default Windows browser? In fact I have the same question for Linux. thx in advancve, -- alf From thn at mail.utexas.edu Sat Jun 2 22:49:21 2007 From: thn at mail.utexas.edu (Thomas Nelson) Date: Sat, 02 Jun 2007 19:49:21 -0700 Subject: Trouble killing a process on windows In-Reply-To: References: <1180801625.231797.158370@p77g2000hsh.googlegroups.com> Message-ID: <1180838961.492129.28960@q66g2000hsg.googlegroups.com> On Jun 2, 11:43 am, Tim Golden wrote: > Thomas Nelson wrote: > > from subprocess import Popen > > from time import sleep > > import win32api > > war3game = Popen(["C:\Program Files\Warcraft III\Frozen Throne.exe"]) > > sleep(30) > > print "slept for 30" > > print win32api.TerminateProcess(int(war3game._handle),-1) > > #print > > ctypes.windll.kernel32.TerminateProcess(int(war3game._handle),-1) > > print "terminated process" > > > Here's the output: > > slept for 30 > > Traceback (most recent call last): > > File "C:\Python24\warcraft\runwar3.py", line 7, in ? > > print win32api.TerminateProcess(int(war3game._handle),-1) > > error: (5, 'TerminateProcess', 'Access is denied.') > > > I'm logged in as adminstrator. Does anyone know how to fix this > > problem? > > There's nothing obvious. I assume you got your info > from here? > > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/347462 > > Just for completeness, have you tried the pid-based technique > shown there? I've no idea why it should work if this one > doesn't but... (I have a slight suspicion that the fact that > it opens the process with a "for-termination" flag might help). > > Failing that, you can see if WMI can do it (although I assume > that, under the covers, WMI just calls TerminateProcess): > > http://timgolden.me.uk/python/wmi_cookbook.html#create_destroy_notepad > > I suppose you might have to adjust your token privs to include, > say the Debug priv. This is designed to let you take control > of any process (and terminate it, or whatever). If it looks > like you need to do that, post back and I -- or someone else -- > can try to run up an example. > > TJG I Tried the PID method, and the Taskkill method, and neither worked. This is what I get for trying to work on a windows machine. If you could explain how to add the debug privilege, that would be great. Just out of curiosity, is there a reason a python module like os couldn't have a universal terminateProcess type function, that works on all systems? Something like os.listdir seems to work really well everywhere. Maybe killing processes is too complicated for this? Thanks for the help, Tom From michael at stroeder.com Fri Jun 8 09:45:47 2007 From: michael at stroeder.com (=?ISO-8859-1?Q?Michael_Str=F6der?=) Date: Fri, 08 Jun 2007 15:45:47 +0200 Subject: python-ldap for Python 2.5 on Windows? In-Reply-To: References: Message-ID: Benedict Verheyen wrote: > > i found python-ldap for version Python 2.4. > Is there i place i can find a version for 2.5? > > If not, how can i build it myself for Windows? Depending on what you need you might want to dive into OpenLDAP's FAQ: http://www.openldap.org/faq/data/cache/300.html There has been some discussion on the python-ldap-dev mailing list about that. But there were no contributions coming out of that. Ciao, Michael. From http Fri Jun 22 03:13:39 2007 From: http (Paul Rubin) Date: 22 Jun 2007 00:13:39 -0700 Subject: PEP 3107 and stronger typing (note: probably a newbie question) References: <1182448413.966430.299590@m36g2000hse.googlegroups.com> Message-ID: <7xhcp0fom4.fsf@ruckus.brouhaha.com> John Nagle writes: > What we need are better implementations than CPython, not > hokey attribute schemes bolted onto the language. We're seeing > stuff go in that's easy to add to CPython, but not necessarily > good for the language as a whole. I think it was a real loss that Python 3.0 proposals were closed before PyPy was widely deployed and we had a chance to get more experience with it. From gagsl-py2 at yahoo.com.ar Fri Jun 1 23:24:16 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 02 Jun 2007 00:24:16 -0300 Subject: Observer-Pattern by (simple) decorator References: <4660B90E.9080705@freakmail.de> Message-ID: En Fri, 01 Jun 2007 21:25:50 -0300, Wildemar Wildenburger escribi?: > Steven Bethard wrote: >> I think you want to define __get__ on your Observable class so that it >> can do the right thing when the method is bound to the instance: > > It took me quite some time understanding what the __get__ method does, > but I think now I figured it out. I've made a quantum leap in my > understanding of Python (esp. method binding) with this! Awesome! To proceed to next energy level, read some articles from http://www.python.org/doc/newstyle/ -- Gabriel Genellina From basti.wiesner at gmx.net Thu Jun 28 14:06:32 2007 From: basti.wiesner at gmx.net (Sebastian Wiesner) Date: Thu, 28 Jun 2007 20:06:32 +0200 Subject: try/except/else/finally problem In-Reply-To: <1387teta99gajc4@corp.supernews.com> References: <1387teta99gajc4@corp.supernews.com> Message-ID: <200706282006.38171.basti.wiesner@gmx.net> [ Ed Jensen ] > try: > f = file('test.txt', 'r') > except IOError: > print 'except' > else: > print 'else' > finally: > print 'finally' > > > And the results are: > > File "./test.py", line 9 > finally: > ^ > SyntaxError: invalid syntax A finally block isn't allowed to appear together with an except block for releases previous to 2.5. You need to split your exception handling into two separate blocks. -- Freedom is always the freedom of dissenters. (Rosa Luxemburg) -------------- 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 grante at visi.com Wed Jun 6 10:43:35 2007 From: grante at visi.com (Grant Edwards) Date: Wed, 06 Jun 2007 14:43:35 -0000 Subject: which "GUI module" you suggest me to use? References: <136bvigp2ps99bc@corp.supernews.com> Message-ID: <136di0nsamvcgd0@corp.supernews.com> On 2007-06-06, Samuel wrote: > On Wed, 06 Jun 2007 00:22:40 +0000, Grant Edwards wrote: > >>> I know that WxPython work only under Windows and PyGTK work only under >>> Linux... >> >> You 'know' wrong. >> >> wxPython works fine under Windows, Linux and OSX. > > wxPython emulates Gtk What? On some platforms (Linux), wxPython _uses_ Gtk. I don't see how you could say it emulates it. > (though using some native widgets, it also uses some of its > own) and in many cases it looks non-native compared to Gtk. How can that be the case when wxPython is using Gtk? > If your target platform includes Unix systems, you'll have to > decide whether inconsistencies with the look and feel of the > desktop are an issue for you. wxPython looks completely native on Unix, because it's using a native widget set (Gtk). >> PyGTK works under Linux and Windows, but doens't use native widgets >> under Windows, so it won't look like a "normal" windows app. > > Gtk on Win32 can be themed to looked like Windows, AFAIK the Win32 > installer does this by default since a couple of months. That's good to know. -- Grant Edwards grante Yow! Hello? Enema Bondage? at I'm calling because I want visi.com to be happy, I guess ... From josiah.carlson at sbcglobal.net Thu Jun 14 15:15:55 2007 From: josiah.carlson at sbcglobal.net (Josiah Carlson) Date: Thu, 14 Jun 2007 19:15:55 GMT Subject: Method much slower than function? In-Reply-To: <1181846993.626541.160760@q19g2000prn.googlegroups.com> References: <1181781612.939800.238890@q19g2000prn.googlegroups.com> <1181795969.141307.94140@i13g2000prf.googlegroups.com> <7xtztbdstq.fsf@ruckus.brouhaha.com> <1181846993.626541.160760@q19g2000prn.googlegroups.com> Message-ID: sjdevnull at yahoo.com wrote: > On Jun 14, 1:10 am, Paul Rubin wrote: >> "sjdevn... at yahoo.com" writes: >>> take virtually the same amount of time on my machine (2.5), and the >>> non-join version is clearer, IMO. I'd still use join in case I wind >>> up running under an older Python, but it's probably not a big issue here. >> You should not rely on using 2.5 > > I use generator expressions and passed-in values to generators and > other features of 2.5. For reference, generator expressions are a 2.4 feature. >> or even on that optimization staying in CPython. > > You also shouldn't count on dicts being O(1) on lookup, or "i in > myDict" being faster than "i in myList". Python dictionaries (and most decent hash table implementations) may not be O(1) technically, but they are expected O(1) and perform O(1) in practice (at least for the Python implementations). If you have particular inputs that force Python dictionaries to perform poorly (or as slow as 'i in lst' for large dictionaries and lists), then you should post a bug report in the sourceforge tracker. - Josiah From paul_lautman at yahoo.com Mon Jun 11 04:46:37 2007 From: paul_lautman at yahoo.com (Captain Paralytic) Date: Mon, 11 Jun 2007 01:46:37 -0700 Subject: updating db with csv In-Reply-To: References: <1181234515.502945.43770@q66g2000hsg.googlegroups.com> Message-ID: <1181551597.685686.129100@k79g2000hse.googlegroups.com> On 11 Jun, 07:37, Tim Roberts wrote: | Not in standard SQL. MySQL supports a REPLACE extension that does an | UPDATE if the key already exists, and an INSERT if it does not. There is | also an extension clause to the INSERT statement called "ON DUPLICATE KEY | UPDATE xxx" that might do what you want. | -- | Tim Roberts, t... at probo.com | Providenza & Boekelheide, Inc. No Tim, that is not correct. the REPLACE extension does not do an update, it does a replace. It delets the old record and inserts a new one. The INSERT...ON DUPLICATE KEY UPDATE... does an update. So a REPLACE will remove all existing field values not referenced in the statement, whilst an INSERT...ON DUPLICATE KEY UPDATE... will preserve them. Also REPLACE will make a TIMESTAMP column which has a DEFAULT CURRENT_TIMESTAMP setting work like one which has ON UPDATE CURRENT_TIMESTAMP DEFAULT CURRENT_TIMESTAMP setting. From openopt at ukr.net Thu Jun 7 12:33:36 2007 From: openopt at ukr.net (dmitrey) Date: Thu, 07 Jun 2007 09:33:36 -0700 Subject: easiest way to count memory eaten by call to Python func? Message-ID: <1181234016.474318.34000@m36g2000hse.googlegroups.com> hi all, which way is the simplest for now to obtain the memory amount eaten by call to Python 'myfunc' function? Thx, D From ebgssth at gmail.com Mon Jun 4 09:31:56 2007 From: ebgssth at gmail.com (js ) Date: Mon, 4 Jun 2007 22:31:56 +0900 Subject: How do you htmlentities in Python Message-ID: Hi list. If I'm not mistaken, in python, there's no standard library to convert html entities, like & or > into their applicable characters. htmlentitydefs provides maps that helps this conversion, but it's not a function so you have to write your own function make use of htmlentitydefs, probably using regex or something. To me this seemed odd because python is known as 'Batteries Included' language. So my questions are 1. Why doesn't python have/need entity encoding/decoding? 2. Is there any idiom to do entity encode/decode in python? Thank you in advance... From newsgroups at nospam.demon.co.uk Tue Jun 5 05:15:09 2007 From: newsgroups at nospam.demon.co.uk (Douglas Woodrow) Date: Tue, 5 Jun 2007 10:15:09 +0100 Subject: Strange behavior in Windows References: <8B637660DDD59A40AA725C926CFC3D46035E39E4@nike.hir.is> Message-ID: On Mon, 4 Jun 2007 21:34:36, David Stockwell wxp wrote > >in DOS you can try this to see what your path is: > >echo "My path is %PATH%" or more simply: ,---- | C:> path `---- -- Doug Woodrow From jpeck at fedex.com Tue Jun 12 19:28:51 2007 From: jpeck at fedex.com (Jeff Peck) Date: Tue, 12 Jun 2007 18:28:51 -0500 Subject: excel column autofit In-Reply-To: References: Message-ID: <466F2C33.4010809@fedex.com> Lance Hoffmeyer wrote: > Hey all, > > Wondering why the syntax won't autofit Column A? > I am not getting any errors. > > Also, is there a way of reducing the number of > syntax lines? Basically, I am wondering if there > is an easier way to copy and paste? > > Thanks in Advance. > > Lance > > # ADD ROW LABELS > sh = wb.Worksheets ("Total") > sh.Select() > sh.Range(sh.Cells(2,1), sh.Cells(20,1)).Select() > sh.Range(sh.Cells(2,1), sh.Cells(20,1)).Copy() > sh = wb.Worksheets ("Current Total") > sh.Select() > sh.Range(sh.Cells(2,1),sh.Cells(20,1)).Select() > sh.Paste() > sh.Columns("A:A").EntireColumn.AutoFit > Looks like you just forgot to add the parenthesis after AutoFit sh.Columns("A:A").EntireColumn.AutoFit() Jeff From chowroc.z at gmail.com Thu Jun 21 23:30:43 2007 From: chowroc.z at gmail.com (Roc Zhou) Date: Fri, 22 Jun 2007 03:30:43 -0000 Subject: why __repr__ affected after __getattr__ overloaded? Message-ID: <1182483043.850101.110890@i13g2000prf.googlegroups.com> Now I have to design a class that overload __getattr__, but after that, I found the __repr__ have been affected. This is a simple example model: #!/usr/bin/env python class test: def __init__(self): self.x = 1 def __getattr__(self, attr_name): try: return self.__dict__[attr_name] except KeyError: self.__dict__[attr_name] = 'inexistent' return self.__dict__[attr_name] t = test() print t.x print t.y print type(t) T = t print T.x print t So far, I want the operation "print t" still return "", but the reuslt is: sh$ python test.py 1 inexistent 1 Traceback (most recent call last): File "testtree.py", line 23, in ? print t TypeError: 'str' object is not callable I also tried to overload __repr__ itself: #!/usr/bin/env python class test: def __init__(self): self.x = 1 def __getattr__(self, attr_name): try: return self.__dict__[attr_name] except KeyError: self.__dict__[attr_name] = 'inexistent' return self.__dict__[attr_name] def __repr__(self): return 'test.__repr__' t = test() print t.x print t.y print type(t) T = t print T.x print t But the result remains: Traceback (most recent call last): File "testtree.py", line 23, in ? print t TypeError: 'str' object is not callable So why? What is the principles? From mitko at qlogic.com Wed Jun 6 18:34:12 2007 From: mitko at qlogic.com (Mitko Haralanov) Date: Wed, 6 Jun 2007 15:34:12 -0700 Subject: Some questions about ipath error messages Message-ID: <20070606153412.4cfc92ce@opal.pathscale.com> Hi Dave, I have some questions about the ipath error messages that we print out. I am currently testing the error injection part of the matrix and I starting with "incorrect checksum" and "incorrect HW version". I have set the debug level on both machines to 0x83 and I am monitoring ipathstats. In the case of "incorrect checksum" I get an "ipathhdrerr" printed on the console and when running "incorrect HW version" test, I get "invalid ipathhdr" On previous release, the error messages that we used to print were a bit more descriptive of the problem (I remember that, at least for the checksum part, it did mention a checksum error, and for HW version, it did mention HW version problem). Am I using the correct debug level? Did the error messages change on purpose? -- Mitko Haralanov mitko at qlogic.com Senior Software Engineer 650.934.8064 System Interconnect Group http://www.qlogic.com ========================================== Professor: I've been a Harold Zoid fan since back when my hips were made of bone. From sergio at sergiomb.no-ip.org Wed Jun 20 09:46:29 2007 From: sergio at sergiomb.no-ip.org (sergio) Date: Wed, 20 Jun 2007 14:46:29 +0100 Subject: stftime %z time conversion character References: Message-ID: <46792fb4$0$11036$a729d347@news.telepac.pt> Evan Klitzke wrote: > Although it is not present in ANSI C, the GNU version of stftime > supports the conversion character %z, which is a time offset from GMT. > The four digit time offset is required in RFC 2822 dates/times, and is > used by a number of other programs as well. I need to convert times > that use this convention to python time representations, and because > Python does not support the %z time conversion character I cannot > simply use the time.strptime function. > > What solutions have people used for this? I'm currently thinking of > creating a dict that maps four digit time offsets to the time zone > name and then use the %Z token on that. Is there another (or better) > way? > I had a similar problem, currently I had solved with a system call #The Linux Date Command: TZ=WET date -d "20070823" +%:z #example timezone = "WET" year = 2007 month = 2 day = 27 #end of example cmd="TZ=%s /bin/date -d %.4d%.2d%.2d +%%z" % (timezone,year,month,day) print "DEBUG cmd=%s" % cmd handler=os.popen(cmd, 'r', 1) output = "".join(handler.readlines()).strip() tz=output[:3]+":"+output[3:] handler.close() print "DEBUG timezone=%sXX" % tz ---------------------------- before I test timezone of my machines like this : import time tzstr=time.strftime("%Z",time.localtime()) if tzstr == "WEST" : do something Hope that can help something Best regards, -- S?rgio M. B. From martin at v.loewis.de Sat Jun 2 06:22:01 2007 From: martin at v.loewis.de (=?ISO-8859-15?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sat, 02 Jun 2007 12:22:01 +0200 Subject: Python 2.5.1 broken os.stat module In-Reply-To: References: <1180648618.295955.68600@x35g2000prf.googlegroups.com> <465fa702$0$2944$9b622d9e@news.freenet.de> Message-ID: <466144C9.9010807@v.loewis.de> >> How did you do that? > > I used a "touch" utility to set the dates but let's try it a different way. What touch utility specifically? Is source code available of that tool? > Looks like Python 2.4.2 is reporting the timestamps correctly Unfortunately, no. Python 2.4 (and earlier) has an error that the time stamps it reports may be off by an hour. This error is offset by the fact that your rendering through localtime() gives result different by one hour also, giving you the impression that Python 2.4 returns the correct result. > Now let's see what Python 2.5.1 says > > Creation Time: 01/02/2003 11:34:56 > Last Access Time: 01/02/2003 11:34:56 > Last Write Time: 01/02/2003 11:34:56 > > All times are off by 1 hour! The rendered times, yes. They are still correct - they are just off by 1 hour, because your rendering algorithm is different from the one that dir uses. It was 11:34 at the time when the file was created, as there was no daylight-saving time in effect in January 2003. According to your current time zone (which does have daylight-saving time), it was 12:34 when the file was created. > h: joe .txt 0 1/02/03 12:34 \ > > The text editor is reporting the correct timestamps too. Define "correct". According to your current time zone, or taking into account that the DST offset was different when the file was created? > Python 2.4.2 ALWAYS got it correct. Unfortunately, it didn't. That was one of the reasons to change it. > So unless you are saying that Windows is wrong, Python 2.5.1 has to be wrong > since it does not compare to what Windows reports. Windows isn't wrong. It just uses a different algorithm to render historical time stamps. Neither approach is right or wrong: - if you use the current time zone, you display a time-stamp that wasn't the reading of the wall clock when the action happened - if you adjust for DST changes, you get ambiguous time stamps, as "2:30 am" may denote two different points in time on the day when daylight saving time returns to normal time. The one true way to render time stamps is in UTC/GMT/Zulu time :-) > Even if it turns out that Windows has a bug and is wrong I still think that > Python should be reporting the same thing because what Windows reports is > what is expected. If Python reports something different (even if it was > correct) the information is not useful if it differs from what everything > else is reporting. For the cases where there is a 1h difference, Python reports *exactly* what Windows reports. Python 2.4 didn't. Regards, Martin From gagsl-py2 at yahoo.com.ar Thu Jun 21 05:36:58 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 21 Jun 2007 06:36:58 -0300 Subject: Can python access windows clipboard References: <1182416346.377857.103540@z28g2000prd.googlegroups.com> Message-ID: En Thu, 21 Jun 2007 05:59:06 -0300, MaHL escribi?: > Can I use python to copy something(like a string) to the clipboard, so > that I can paste it somewhere else. Is there a way to do this? Yes, using the pywin32 extensions that you can download from Sourceforge py> from win32clipboard import * py> OpenClipboard() py> EmptyClipboard() py> SetClipboardText("Hello from Python!") 11272196 py> CloseClipboard() Ctrl-v: Hello from Python! -- Gabriel Genellina From doug at alum.mit.edu Fri Jun 22 12:42:31 2007 From: doug at alum.mit.edu (Douglas Alan) Date: Fri, 22 Jun 2007 12:42:31 -0400 Subject: Python's "only one way to do it" philosophy isn't good? References: <1181368143.874341.273140@r19g2000prf.googlegroups.com> <7x3b0nmkk6.fsf@ruckus.brouhaha.com> Message-ID: Neil Cerutti writes: > That said, I wouldn't give up the summer I spent studying _Simply > Scheme_. Sounds like fun. Is this like a kinder, gentler version of SICP? I'm not sure, though, that I could have learned computer science properly without the immortal characters of Ben Bittwiddler and Harry Reasoner intruding into every problem set. |>oug From john at datavoiceint.com Fri Jun 15 11:21:01 2007 From: john at datavoiceint.com (HMS Surprise) Date: Fri, 15 Jun 2007 08:21:01 -0700 Subject: Re printing on same line. Message-ID: <1181920861.071568.4860@w5g2000hsg.googlegroups.com> I want to print a count down timer on the same line. I tried print '\r', timeLeft, which just appends to the same line. thanx, jh From Graham.Dumpleton at gmail.com Sun Jun 24 20:19:10 2007 From: Graham.Dumpleton at gmail.com (Graham Dumpleton) Date: Mon, 25 Jun 2007 00:19:10 -0000 Subject: Using PSE under Win32 In-Reply-To: <1182611604.696515.143930@k79g2000hse.googlegroups.com> References: <1182611604.696515.143930@k79g2000hse.googlegroups.com> Message-ID: <1182730750.267265.74240@i38g2000prf.googlegroups.com> On Jun 24, 1:13 am, Eduardo Dobay wrote: > Hello, I've been playing around withmod_pythonthese days (using > Publisher and PSP), and it has been working smoothly under Windows XP > (using Apache 2.2). But when I installed PSE and went to use it withmod_python, it didn't work. The error I get whenever I try to load a > PSE page is: > > Traceback (most recent call last): > > File "C:\Python25\lib\site-packages\mod_python\importer.py", line > 1537, in HandlerDispatch > default=default_handler, arg=req, silent=hlist.silent) > > File "C:\Python25\lib\site-packages\mod_python\importer.py", line > 1229, in _process_target > result = _execute_target(config, req, object, arg) > > File "C:\Python25\lib\site-packages\mod_python\importer.py", line > 1128, in _execute_target > result = object(arg) > > TypeError: 'module' object is not callable > > I thought it could be some incompatibility issue between PSE andmod_python, but I tried both installing the PSE binary and building > the sources, and it didn't make a difference. Has anyone out there had > success using PSE under Windows? > > (Just for the record, I did install matching versions, at least for > Apache (2.2.3), Python (2.5) andmod_python(3.3.1). PSE doesn't seem > to have a strict version requirement.) What do you have PythonHandler set to and what does it identify? The error above suggests that whatever you identify as the handler is not a callable object like a function. Are you perhaps identifying some sort of PSE template object as target when you shouldn't be? Post your handler code so we can see it. Graham From marcpp at gmail.com Sat Jun 16 21:30:26 2007 From: marcpp at gmail.com (Marcpp) Date: Sat, 16 Jun 2007 18:30:26 -0700 Subject: Function that returns a tuple Message-ID: <1182043826.790070.4420@u2g2000hsc.googlegroups.com> Hi, I need to returns a tuple from a function (reads a database) Any idea?. From google at mrabarnett.plus.com Wed Jun 13 17:41:14 2007 From: google at mrabarnett.plus.com (MRAB) Date: Wed, 13 Jun 2007 14:41:14 -0700 Subject: Windows XP timezone language issue In-Reply-To: <466f8f45$0$329$e4fe514c@news.xs4all.nl> References: <466f8f45$0$329$e4fe514c@news.xs4all.nl> Message-ID: <1181770874.510964.157530@i13g2000prf.googlegroups.com> On Jun 13, 7:31 am, Paul Sijben wrote: > I ran into an internationalization issue. I need a consistent idea about > the timezone my application is running on. However when I run the following: > >>> import time > >>> time.tzname > > I get back ('West-Europa (standaardtijd)', 'West-Europa (zomertijd)') > which is in dutch (the language of the host machine) and verbose. > I wanted to get ('CEST','CET') or something international so I can work > with itin the same way on all platforms. > > That is the right way to find out the timezone in a consistent way > across platforms (windows/linux/mac) and languages? > Well, time.timezone will return the timezone as an integer. From dfabrizio51 at gmail.com Mon Jun 4 16:47:53 2007 From: dfabrizio51 at gmail.com (chewie54) Date: Mon, 04 Jun 2007 20:47:53 -0000 Subject: wxPython splitwindow with interpreter on bottom In-Reply-To: <1180989419.705079.251540@k79g2000hse.googlegroups.com> References: <1180969036.773130.219700@n4g2000hsb.googlegroups.com> <1180989419.705079.251540@k79g2000hse.googlegroups.com> Message-ID: <1180990073.769185.229000@h2g2000hsg.googlegroups.com> On Jun 4, 4:36 pm, kyoso... at gmail.com wrote: > On Jun 4, 9:57 am, chewie54 wrote: > > > Hi all, > > > Does anyone know of an example of wxPython source code that shows how > > to put a python shell (interpreter) in a bottom window with a > > graphical application in the top window? > > > Thanks, > > There's the pyCrust/pyShell examples in the wxPython demo. They are > quite similar to what you want, I think. > > Mike Thank you. Yes, that is exactly what I want. From pydecker at gmail.com Wed Jun 20 17:10:02 2007 From: pydecker at gmail.com (Peter Decker) Date: Wed, 20 Jun 2007 17:10:02 -0400 Subject: visual gui ides for python/jythpn In-Reply-To: <1182363400.993370.109800@k79g2000hse.googlegroups.com> References: <1182363400.993370.109800@k79g2000hse.googlegroups.com> Message-ID: On 6/20/07, kromakey wrote: > Hi, > > Are there any free visual GUI IDE's available for python/jython, which > have a drag and drop form designer similar to Visual Studio or > Delphi ? Watch these screencasts, and then check out Dabo: http://leafe.com/screencasts/dataenvironment1.html http://leafe.com/screencasts/dataenvironment2.html Dabo's site is http://dabodev.com. -- # p.d. From tjreedy at udel.edu Fri Jun 15 23:21:39 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 15 Jun 2007 23:21:39 -0400 Subject: Python's "only one way to do it" philosophy isn't good? References: <1181368143.874341.273140@r19g2000prf.googlegroups.com> Message-ID: "Douglas Alan" wrote in message news:lc4pl9gc88.fsf at gaffa.mit.edu... | "Terry Reedy" writes: | | > Here's the situation. Python is making inroads at MIT, Scheme home turf. | > The co-developer of Scheme, while writing about some other subject, tosses | > in an off-the-wall slam against Python. Someone asks what we here think. | > I think that the comment is a crock and the slam better directed, for | > instance, at Scheme itself. Hence 'he should look in a mirror'. | | You are ignoring the fact that This prefactory clause is false and as such it turns what was a true statement into one that is not. Better to leave off such ad hominisms and stick with the bare true statement. | Scheme has a powerful syntax extension mechanism I did not and do not see this as relevant to the main points of my summary above. Python has powerful extension mechanisms too, but comparing the two languages on this basis is a whole other topic. tjr From kyosohma at gmail.com Wed Jun 20 10:44:42 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Wed, 20 Jun 2007 07:44:42 -0700 Subject: python website In-Reply-To: <1182349364.574645.279350@q19g2000prn.googlegroups.com> References: <1182349364.574645.279350@q19g2000prn.googlegroups.com> Message-ID: <1182350682.869812.256180@g4g2000hsf.googlegroups.com> On Jun 20, 9:22 am, james_027 wrote: > hi, > > what are you list of favorite python website (news, articles, > tutorials)? > > cheers, > james wxPython.org (and the wxPython wiki) Python.org ActiveState - http://aspn.activestate.com/ASPN/Python/Cookbook/ Charming python series - http://www.ibm.com/developerworks/library/l-pycon.html http://gnosis.cx/publish/tech_index_cp.html Devshed - http://www.devshed.com/c/b/Python/ Mike From eadmund42 at NOSPAMgmail.com Sun Jun 24 21:42:20 2007 From: eadmund42 at NOSPAMgmail.com (Robert Uhl) Date: Sun, 24 Jun 2007 19:42:20 -0600 Subject: The Modernization of Emacs: terminology buffer and keybinding References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182272495.990807.99110@a26g2000pre.googlegroups.com> <87tzt3ihev.fsf@kobe.laptop> <1182370216.961241.6960@n60g2000hse.googlegroups.com> <85zm2ufjpb.fsf@lola.goethe.zz> <1182372592.803332.288260@u2g2000hsc.googlegroups.com> <5dtk4tF34jrimU1@mid.dfncis.de> <1182375388.814275.227380@n2g2000hse.googlegroups.com> <87645h73ei.fsf@W0053328.mgh.harvard.edu> <1182548563.561252.82480@i13g2000prf.googlegroups.com> <1182666078.511962.280030@w5g2000hsg.googlegroups.com> <1182729450.495841.296140@q69g2000hsb.googlegroups.com> Message-ID: Twisted writes: > >> > Really? None of [navigating a folder window analogue] happens if >> > you just do the straightforward file-open command, which should >> > obviously at least provide a navigable directory tree, but >> > definitely does not. >> >> The first does. Really, it does. Fire up emacs (which you've never >> done before) and type C-x C-f. > > Whoa, Nellie. I seem to recall we were discussing the file-open > command. That was something else, like C-x C-o or something. More > apples-and- oranges? Fortunately, emacs has a facility to tell exactly what's bound to a key sequence. C-h k (or f1 k, if you prefer)followed by that sequence will display what's bound to it, and the documentation for that function. C-h k C-x C-o yields: C-x C-o runs the command delete-blank-lines C-h k C-x o yields: C-x o runs the command other-window C-h k C-x C-f yields: C-x C-f runs the command find-file So you can see how cool emacs is, here's the entire output for C-x C-f, demonstrating how the editor documents itself: C-x C-f runs the command find-file which is an interactive compiled Lisp function in `files.el'. It is bound to , C-x C-f, . (find-file filename &optional wildcards) Edit file filename. Switch to a buffer visiting file filename, creating one if none already exists. Interactively, the default if you just type RET is the current directory, but the visited file name is available through the minibuffer history: type M-n to pull it into the minibuffer. Interactively, or if wildcards is non-nil in a call from Lisp, expand wildcards (if any) and visit multiple files. You can suppress wildcard expansion by setting `find-file-wildcards' to nil. To visit a file without any kind of conversion and without automatically choosing a major mode, use M-x find-file-literally. >> You will be presented with a prompt >> something like 'Find file: ~/'; hit tab once; you'll see the message >> '[Complete, but not unique]'; hit tab again and you will be presented a >> list of all files in that directory. > > Sounds clunky anyway. I don't need a bunch of keypresses to do the > equivalent in an Explorer-based file-open dialog in a native Windows > app. Just a double-click. Generally, you need to scroll, too, as the Windows file widget doesn't display a lot of files at once. > Of course, there's an even faster Windows way, if you don't mind not > seeing lists of possible items: > Alt, f, o > Startofname-down-/-Subd-down-/ How is this different from C-x C-f Startofname-tab-Subd-tab? Except emacs saves you type slashes... >> If you like 'em, though, just select File:Visit New File. It gives >> you a platform-default (gtk+, for me) file selector. > > Now we're talking about a graphical port instead of stock emacs > again. :P That _is_ stock emacs, I assure you. >> Fortunately, folks brighter than you & I have imagined a nice way for >> us. It pops up a new Emacs window (pane, if you prefer the >> terminology) showing a list of all filenames. You could continue >> typing, or just click on a filename in the window, or hit return >> while the cursor is on a filename in that window. > > Back to discussing a graphical port again. It's not a port--it's emacs. And save for the click all of the above works in both a GUI and a console. It's nice working the same way in multiple places. > Besides the apples and oranges issue, this amounts to implementing a > dodgy imitation of a file open dialog anyway. Why bother with such an > imitation when you can use a natively-GUI editor written for your > platform and get access to the real thing? Because it's nice having the same interface no matter what. Because GUIs come and GUIs go (remember CDE? OpenView?), but emacs will always be there. Because it's nice being able to fire up emacs and not care what platform one is running on. -- Robert Uhl prepBut nI vrbLike adjHungarian! qWhat's artThe adjBig nProblem? -- Alec Flett From hg at nospam.org Sun Jun 3 12:29:35 2007 From: hg at nospam.org (hg) Date: Sun, 03 Jun 2007 11:29:35 -0500 Subject: Python 2.5 and stdin Message-ID: Hi, I have upgraded to 2.5 and one of my program no longre functions: In a thread run function, I attempts to get a "raw_input('')" and get the error *********************************** Exception in thread Thread-2: Traceback (most recent call last): File "/usr/lib/python2.5/threading.py", line 460, in __bootstrap self.run() File "/usr/local/games/RealTimeBattle/Robots/pyrobot.py", line 89, in run l_res = raw_input('') IOError: [Errno 11] Resource temporarily unavailable *********************************** The full source code is here: http://snakecard.com/rtb/ Any clue ? Thanks, hg From see.signature at no.spam Tue Jun 12 05:24:50 2007 From: see.signature at no.spam (Eric Brunel) Date: Tue, 12 Jun 2007 11:24:50 +0200 Subject: Pasting an image from clipboard in Tkinter? References: <1181564628.443138.165380@k79g2000hse.googlegroups.com> Message-ID: On Mon, 11 Jun 2007 14:23:48 +0200, exhuma.twn wrote: > As many might know, windows allows to copy an image into the clipboard > by pressing the "Print Screen" button on the keyboard. Is it possible > to paste such an image from the clipboard into a "Text" widget in > Tkinter? Here is my first attempt with just trying to print out the > image data: > > ----------------- > def pasteImg(tgt): > global clipboardEnabled > if not clipboardEnabled: return > > win32clipboard.OpenClipboard(0) > print win32clipboard.GetClipboardData() > win32clipboard.CloseClipboard() > ----------------- > > This works fine with selecting text, but comes up with the following > error when trying to paste an image: > > ----------------- > Exception in Tkinter callback > Traceback (most recent call last): > File "C:\Python25\lib\lib-tk\Tkinter.py", line 1403, in __call__ > return self.func(*args) > File "X:\development\testing\tkwiki\tkwiki.py", line 52, in > Button( root, command=lambda: pasteImg(txt) ).pack() > File "X:\development\testing\tkwiki\tkwiki.py", line 38, in pasteImg > print win32clipboard.GetClipboardData() > TypeError: Specified clipboard format is not available > ----------------- > > Obviously the clipboard does not know about that format. Does that > mean I have to wait until it's implemented or are there other ways to > access the image data? According to http://msdn2.microsoft.com/en-us/library/ms649039.aspx, there is format that you should pass to GetClipboardData telling the data type you expect to get. The format you should specify to get a bitmap image is named CF_BITMAP in the Windows API. AFAIK, this constant is not exposed in the Python world, so you have to pass directly the numeric value, which is 2. But even if you do get the clipboard contents, you'll get it in BMP format, that tk/Tkinter does not understand by default. So you'll need a means to convert it to the only format known to tk/Tkinter by default, which is GIF. PIL is certainly able to do that (I don't use it myself); you may also rely on an external conversion utility. HTH -- python -c "print ''.join([chr(154 - ord(c)) for c in 'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])" From jimxu at google.com Tue Jun 5 13:38:16 2007 From: jimxu at google.com (Yongjian Xu) Date: Tue, 5 Jun 2007 10:38:16 -0700 Subject: Sending cookies with python. When download with python In-Reply-To: <1181060091.747809.91520@p47g2000hsd.googlegroups.com> References: <1181060091.747809.91520@p47g2000hsd.googlegroups.com> Message-ID: <9c09a1210706051038w25652b3ay148d9392c29ff1a7@mail.gmail.com> yes. urllib2 has Request class that compose html headers (dict object) into a request object where you can put Cookie: header into it. Also, there are a few Cookie related modules you can use too. An example using urllib2 can be something like this: def myrequest(url): req = urllib2.Request(url) headers = {'Cookie':'cookies','some_other_headers':'contents'} for k,v in headers.iteritems(): req.add_header(k,v) return req Hope it helps. Jim On 6/5/07, moishyyehuda at gmail.com wrote: > > I need to download files off a password protected website. So if I try > to download files off the site with python I will be blocked. Is there > anyway to send cookies with python. So I will be authenticated. > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Yongjian (Jim) Xu =========== Sysops -------------- next part -------------- An HTML attachment was scrubbed... URL: From sjmachin at lexicon.net Sun Jun 17 06:11:11 2007 From: sjmachin at lexicon.net (John Machin) Date: Sun, 17 Jun 2007 03:11:11 -0700 Subject: Function that returns a tuple In-Reply-To: <1182073753.544045.256670@g4g2000hsf.googlegroups.com> References: <1182043826.790070.4420@u2g2000hsc.googlegroups.com> <1182071765.760451.298490@u2g2000hsc.googlegroups.com> <1182073753.544045.256670@g4g2000hsf.googlegroups.com> Message-ID: <1182075071.804772.196630@d30g2000prg.googlegroups.com> On Jun 17, 7:49 pm, Baltimore wrote: > On 17 juin, 11:16, Marcpp wrote: > > > > > On 17 jun, 03:53, Dan Hipschman wrote:> On Sat, Jun 16, 2007 at 06:30:26PM -0700, Marcpp wrote: > > > > Hi, I need to returns a tuple from a function (reads a database) > > > > Any idea?. > > > > Like this? > > > > def foo(): > > > return 1, 2, 3, 4 > > > Hi, I need to return a tupla like this function: > > > def BDllids(a): > > a = () > > conn = sqlite.connect('tasques.db') > > cursor = conn.cursor() > > cursor.execute('SELECT * FROM tasques') > > for row in cursor: > > a.append (row[0]) > > return a() > > > I'm doing the correct, method? > > Why is 'a' used as argument of the function ? > You don't need to put it in argument. > > def BDllids(): > a = () > conn = sqlite.connect('tasques.db') > cursor = conn.cursor() > cursor.execute('SELECT * FROM tasques') > for row in cursor: > a.append (row[0]) > return a > > But that's the correct method ! Say what? | >>> a = () | >>> a.append('x') | Traceback (most recent call last): | File "", line 1, in | AttributeError: 'tuple' object has no attribute 'append' | >>> Instead of a = () the OP should do a = [] and at the end, return tuple(a) Of course if the caller is not being so anal as to check that the returned gizmoid is actually a tuple, then return a would suffice. Cheers, John From eddie at holyrood.ed.ac.uk Fri Jun 8 08:38:35 2007 From: eddie at holyrood.ed.ac.uk (Eddie Corns) Date: Fri, 8 Jun 2007 12:38:35 +0000 (UTC) Subject: How Can I Increase the Speed of a Large Number of Date Conversions References: <1181266113.100863.174410@q19g2000prn.googlegroups.com> Message-ID: vdicarlo writes: >I am a programming amateur and a Python newbie who needs to convert >about 100,000,000 strings of the form "1999-12-30" into ordinal dates >for sorting, comparison, and calculations. Though my script does a ton >of heavy calculational lifting (for which numpy and psyco are a >blessing) besides converting dates, it still seems to like to linger >in the datetime and time libraries. (Maybe there's a hot module in >there with a cute little function and an impressive set of >attributes.) >Anyway, others in this group have said that the date and time >libraries are a little on the slow side but, even if that's true, I'm >thinking that the best code I could come up with to do the conversion >looks so clunky that I'm probably running around the block three times >just to go next door. Maybe someone can suggest a faster, and perhaps >simpler, way. >Here's my code, in which I've used a sample date string instead of its >variable name for the sake of clarity. Please don't laugh loud enough >for me to hear you in Davis, California. >dateTuple = time.strptime("2005-12-19", '%Y-%m-%d') > dateTuple = dateTuple[:3] > date = datetime.date(dateTuple[0], dateTuple[1], >dateTuple[2]) > ratingDateOrd = date.toordinal() >P.S. Why is an amateur newbie trying to convert 100,000,000 date >strings into ordinal dates? To win try to win a million dollars, of >course! In case you haven't seen it, the contest is at www.netflixprize.com. >There are currently only about 23,648 contestants on 19,164 teams from >151 different countries competing, so I figure my chances are pretty >good. ;-) I can't help noticing that dates in 'yyyy-mm-dd' format are already sortable as strings. >>> '1999-12-30' > '1999-12-29' True depending on the pattern of access the slightly slower compare speed _might_ compensate for the conversion speed. Worth a try. Eddie From paul at boddie.org.uk Mon Jun 25 19:28:16 2007 From: paul at boddie.org.uk (Paul Boddie) Date: Mon, 25 Jun 2007 16:28:16 -0700 Subject: eggs considered harmful In-Reply-To: <1182804072.789708.302980@c77g2000hse.googlegroups.com> References: <1182804072.789708.302980@c77g2000hse.googlegroups.com> Message-ID: <1182814096.194071.273340@n2g2000hse.googlegroups.com> Fuzzyman wrote: > > I understand your situation and I have some misgivings myself. It > reminds me of the time when I worked in a 'corporate environment' and > I was trying to install a Perl application to get round the internet > blocking. > > The application (localproxy - very good) was *intended* to be > installed via CPAN for tracking requirements - which didn't work > behind our proxy firewall. Sounds like an "interesting" bootstrapping issue to me. [...] > My guess is that a lot of the world's computers are behind firewalls > or proxies that preclude automatic dependency resolution. I'd argue that mechanisms already exist for automatic upgrades even in restricted environments, and we're not always talking about "big bucks" corporate solutions, either. Indeed, the more established GNU/ Linux distributions seem to have had the required flexibility of dependency resolution *and* not requiring an "always on" connection to the Internet for quite some time - for obvious reasons if you consider how long they've been going. > *However*, there is a very good reason why setuptools and eggs are > gaining in popularity (and will continue to do so). For the majority > of users eggs are just *so damned convenient*. Being able to do > ``easy_install some_project`` and have it just work is fantastic. Sure. But being able to install any software (not just eggs via the Package Index, or Perl software via CPAN, or...) with dependency resolution isn't alien to a lot of people. Again, it's time to look at established practice rather than pretend it doesn't exist: http://mail.python.org/pipermail/python-dev/2006-November/070101.html Paul From xavier_berard at hotmail.com Sat Jun 9 11:09:08 2007 From: xavier_berard at hotmail.com (=?iso-8859-1?q?Xavier_B=E9rard?=) Date: Sat, 09 Jun 2007 08:09:08 -0700 Subject: Tkinter custom drawing In-Reply-To: References: <1181224696.484887.29980@q66g2000hsg.googlegroups.com> <18ffa$4668282d$4275d90a$7087@FUSE.NET> <1181311587.317955.28650@q69g2000hsb.googlegroups.com> Message-ID: <1181401748.938648.75680@q66g2000hsg.googlegroups.com> Thank you this is nice code. I never thought of using the move_pending method.. Still it doesn't answer my question (which I ensure is very unclear). But do not worry, I found some way to get throught my dilemma and I can live easily with it. Thanks for your help. From giles_brown at hotmail.com Mon Jun 11 07:46:48 2007 From: giles_brown at hotmail.com (Giles Brown) Date: Mon, 11 Jun 2007 04:46:48 -0700 Subject: Postpone creation of attributes until needed In-Reply-To: <1181556643.693661.179280@g4g2000hsf.googlegroups.com> References: <1181553891.447344.109390@g4g2000hsf.googlegroups.com> <1181556643.693661.179280@g4g2000hsf.googlegroups.com> Message-ID: <1181562408.298358.97690@k79g2000hse.googlegroups.com> On 11 Jun, 11:10, Frank Millman wrote: > On Jun 11, 11:47 am, Phil Thompson > wrote: > > > > > On Monday 11 June 2007 10:24 am, Frank Millman wrote: > > > > Hi all > > > > I have a small problem. I have come up with a solution, but I don't > > > know if it is a) safe, and b) optimal. > > > > I have a class with a number of attributes, but for various reasons I > > > cannot assign values to all the attributes at __init__ time, as the > > > values depend on attributes of other linked classes which may not have > > > been created yet. I can be sure that by the time any values are > > > requested, all the other classes have been created, so it is then > > > possible to compute the missing values. > > > Properties... > > > @property > > def z(self): > > return self.x * self.y > > In my simple example I showed only one missing attribute - 'z'. In > real life I have a number of them, so I would have to set up a > separate property definition for each of them. > > With my approach, __getattr__ is called if *any* of the missing > attributes are referenced, which seems easier and requires less > maintenance if I add additional attributes. > > Another point - the property definition is called every time the > attribute is referenced, whereas __getattr__ is only called if the > attribute does not exist in the class __dict__, and this only happens > once. Therefore I think my approach should be slightly quicker. > > Frank You could treat the property access like a __getattr__ and use it to trigger the assignment of instance variables. This would mean that all future access would pick up the instance variables. Following a kind "class variable access causes instance variable creation" pattern (anyone know a better name for that?). You may want to construct a little mechanism that sets up these properties (a loop, a list of attribute names, and a setattr on the class?). If you've got to allow access from multiple threads and aren't happy that the calculations being idempotent is going to be sufficient (e.g. if the calculations are really expensive) then you need some kind of threading lock in your (one and only?) lazy loading function. Ok. Enough lunchtime diversion (I should get some fresh air). Giles From bscrivener42 at gmail.com Sat Jun 9 21:33:52 2007 From: bscrivener42 at gmail.com (BartlebyScrivener) Date: Sat, 09 Jun 2007 18:33:52 -0700 Subject: VIM editor question In-Reply-To: References: <1181393067.068779.265610@g4g2000hsf.googlegroups.com> Message-ID: <1181439232.374275.296700@h2g2000hsg.googlegroups.com> On Jun 9, 1:23 pm, "Jerry Van Brimmer" wrote: > On 6/9/07, BartlebyScrivener wrote: > > > No! That's completely wrong. > > No, it's not *completely* wrong. Yes, I should have mentioned the > bg=dark entry, but that doesn't make it *completely* wrong. you're > just showing your preference for the moria colorscheme, which is fine, > but don't say my suggestion is *completely* wrong. > Er, I was kidding. Point being, it's totally customizable. I guess I should have included a smiley face for your literal-minded self. rd From cai.haibin at gmail.com Wed Jun 13 04:40:20 2007 From: cai.haibin at gmail.com (james_027) Date: Wed, 13 Jun 2007 08:40:20 -0000 Subject: Dive into Python 5.5 Message-ID: <1181724020.770062.286220@o11g2000prd.googlegroups.com> Hi, class UserDict: def __init__(self, dict=None): self.data = {} if dict is not None: self.update(dict) I just don't understant this code, as it is not also mention in the book. the update is a method of a dict right? in my understanding the last statement should be self.data.update(dict). someone please explain to me what happen where? Thanks james From nikbaer at gmail.com Tue Jun 19 18:38:51 2007 From: nikbaer at gmail.com (nik) Date: Tue, 19 Jun 2007 22:38:51 -0000 Subject: save class In-Reply-To: <5df7drF34ivvjU1@mid.uni-berlin.de> References: <1181784016.454693.42340@o11g2000prd.googlegroups.com> <1181787082.712869.72770@z28g2000prd.googlegroups.com> <1181847914.603957.174200@n15g2000prd.googlegroups.com> <5df7drF34ivvjU1@mid.uni-berlin.de> Message-ID: <1182292731.370386.236280@i38g2000prf.googlegroups.com> Thank you for all the responses. In light of what you've told me I have gone back to storing my specific dictionaries in text files and then reading them in to the class. Thank you, Nik From flyzone at technologist.com Fri Jun 15 13:17:36 2007 From: flyzone at technologist.com (Flyzone) Date: Fri, 15 Jun 2007 10:17:36 -0700 Subject: problem on waiting exit thread and write on file In-Reply-To: References: <1181749731.260357.192390@q19g2000prn.googlegroups.com> Message-ID: <1181927856.754681.160610@o61g2000hsh.googlegroups.com> Marc 'BlackJack' Rintsch ha scritto: > for thread in threads: > thread.join() > > Much shorter, isn't it!? :-) If i do like you tell, all thread will run together right? So i'll get troubles! I have a list of hostname, i run a network program and then i need to write some of the output that give me this command to a file. If i run the thread together, they can get problems writing on the same file. So I have splitted the list in 5 groups, the group 1 have filetmp 1, group 2 have filetmp 2 and so on... Then I start one thread for all groups, so 5 threads running together, the other waiting the end of one of them. From deets at nospam.web.de Thu Jun 21 03:01:47 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 21 Jun 2007 09:01:47 +0200 Subject: PEP 3107 and stronger typing (note: probably a newbie question) In-Reply-To: References: <1182369568.941307.316260@p77g2000hsh.googlegroups.com> <5dtmtnF36t3pfU1@mid.uni-berlin.de> Message-ID: <5dum32F36578jU1@mid.uni-berlin.de> kaens schrieb: > On 6/20/07, Diez B. Roggisch wrote: > >> That is exactly the problem - there is no "some more" static typing. >> There is static typing - or not. You can't have it "just a bit". > > Couldn't a language be made so that if you declared a variable like, say: > > string foo = "I'm a string" > > it would be a string, and always a string, and if you declared a > variable like > > foo = "i'm a dynamic variable" > > it would be considered dynamic? > > This doesn't seem like it would be too hard to add in to a language > that already had dynamic typing (But then again, I am inexperienced - > although interested in - language design). It isn't too hard. All it needs is a bucket at a name that contains a type reference. But what you DO with that is the hard thing. Just enforcing types at runtime is easy. Making JIT-compilation for such code and then put guarding statements around it - somewhat harder, but easier than full type inference. But the OP wanted compile-time static typing checks. And _thats_ virtually impossible unless _everything_ is statically typed. And even if it is, the ClassCastExceptions of Java prove that. Take this classic example from the java-world that is statically correct, but will fail at runtime class A class B extends A B[] bs = new B[100]; A[] as = bs; as[0] = new A(); The problem here is that the as-array has less type information, and because of polymorphism rules is allowed to actually hold an B-array. But that can't allow mere A-objects to be assigned to it! So the JVM introduces a runtime type check here. Mixing static and dynamic type information like proposed will only make this problem more severe, as you know even less about your types. Thus the whole purpose of static checking vanishes, and the whole thing shifts to a purely runtime checking. > It seems to me like this could be really useful, but I'm not aware of > any language implementing something like this. Which _might_ be a hint... :) Diez From joshua at eeinternet.com Tue Jun 26 16:00:56 2007 From: joshua at eeinternet.com (Joshua J. Kugler) Date: Tue, 26 Jun 2007 12:00:56 -0800 Subject: Python plain-text database or library that supports joins? References: <1182532691.182581.110940@m37g2000prh.googlegroups.com> Message-ID: <46816442$0$31271$88260bb3@free.teranews.com> On Friday 22 June 2007 09:18, felciano wrote: > Hello -- > > Is there a convention, library or Pythonic idiom for performing > lightweight relational operations on flatfiles? I frequently find > myself writing code to do simple SQL-like operations between flat > files, such as appending columns from one file to another, linked > through a common id. For example, take a list of addresses and append > a 'district' field by looking up a congressional district from a > second file that maps zip codes to districts. Two pointers, but maybe not a complete solution: http://search.cpan.org/dist/DBD-Sprite/ Perl library that uses CSV files and supports simple joins. Maybe a port of this? http://www.biostat.wisc.edu/~annis/creations/pseudb.html Functional interface for CSV files inspired by Sprite, but does not support joins. Possibly could be extended? j -- Joshua Kugler Lead System Admin -- Senior Programmer http://www.eeinternet.com PGP Key: http://pgp.mit.edu/ ?ID 0xDB26D7CE -- Posted via a free Usenet account from http://www.teranews.com From openopt at ukr.net Thu Jun 7 07:19:14 2007 From: openopt at ukr.net (dmitrey) Date: Thu, 07 Jun 2007 04:19:14 -0700 Subject: howto obtain directory where current (running) py-file is placed? In-Reply-To: <1181200735.220105.19250@q69g2000hsb.googlegroups.com> References: <1181198387.952428.163120@q75g2000hsh.googlegroups.com> <1181200735.220105.19250@q69g2000hsb.googlegroups.com> Message-ID: <1181215154.325114.318910@g4g2000hsf.googlegroups.com> On Jun 7, 10:18 am, Gerard Flanagan wrote: > On Jun 7, 8:39 am, dmitrey wrote: Thank you. And what is the simplest way (without split/join, if exist) to obtain name of directory parent to directory my_directory_name? Thx, D. > > > Hi all, > > I guess this question was asked many times before, but I don't know > > keywords for web search. > > > Thank you in advance, D. > > import os > > d1 = os.path.dirname(__file__) > d2 = os.path.dirname(os.__file__) > > print d1 > print d2 From mike.klaas at gmail.com Tue Jun 5 19:09:52 2007 From: mike.klaas at gmail.com (Klaas) Date: Tue, 05 Jun 2007 23:09:52 -0000 Subject: Python rocks In-Reply-To: <1hz4i2g.cn86v2nz0vlwN%aleax@mac.com> References: <4661700a$0$19261$da0feed9@news.zen.co.uk> <4661adda$0$19256$da0feed9@news.zen.co.uk> <1hz3e3u.e9p5xz1u3ekfhN%aleax@mac.com> <46627fb2$0$19248$da0feed9@news.zen.co.uk> <1hz4i2g.cn86v2nz0vlwN%aleax@mac.com> Message-ID: <1181084992.907808.90650@a26g2000pre.googlegroups.com> On Jun 3, 8:56 am, a... at mac.com (Alex Martelli) wrote: > Allowing a trailing ! in method names has no such cost, because in no > language I know is ! used as a "postfix unary operator"; the gain in the > convention "mutators end with !" is not huge, but substantial. So, the > tradeoffs are different: small pain, substantial gain == not a bad idea. > > However, this is all quite theoretical, because no more PEPs will be > accepted for Python 3000, so any language change like this would have to > wait for Python 4000, which is no doubt quite a distant prospect:-). Would it? If it isn't backwards-incompatible, it could even go in 2.6 -Mike From senwin30 at gmail.com Thu Jun 28 13:23:28 2007 From: senwin30 at gmail.com (senthil arasu) Date: Thu, 28 Jun 2007 12:23:28 -0500 Subject: Help needed for Pmw and WxPython Interface In-Reply-To: <1ef9860e0706280928l2d000ba8g555d568228ee1b7b@mail.gmail.com> References: <1ef9860e0706280928l2d000ba8g555d568228ee1b7b@mail.gmail.com> Message-ID: <1ef9860e0706281023l5d3719b2qef8e5e51d2fdee28@mail.gmail.com> I On 6/28/07, senthil arasu wrote: > > Hi, > Iam creating tab pages using pmw > nb = Pmw.NoteBook(master) > p1 = nb.add('Page 1') > p2 = nb.add('Page 2') > p3 = nb.add('Page 3') > > created button control for every tabe page to open HTML > > Button(p1, fg='blue',command=f.call,command=call1).pack(pady=40) > Button(p2, fg='blue',command=f.call,command=call2).pack(pady=40) > Button(p3, fg='blue',command=f.call,command=call2).pack > > since HTML rendering supported in WxPython library .I have defined call > backs with WxPython HTML routines > > eg. > def call1:() > { > > html.LoadPage("http://wxwidgets.org/manuals/2.5.4/wx_wxbutton.html") > > } > > Iam facing problem in integration of both the libraries. > > Is it possible to integrate the functionalities of libraries WxPython and > pmw.? > > please help me. > > > > thanks > > > > > > > > iS IT > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From mstepnicki at gmail.com Wed Jun 27 03:25:16 2007 From: mstepnicki at gmail.com (=?iso-8859-2?q?Marcin_St=EApnicki?=) Date: Wed, 27 Jun 2007 07:25:16 +0000 (UTC) Subject: XML from SQL result Message-ID: Hello. I've skimmed through many Python&XML related books/articles but I am unable to find anything that is similar to my problem - but it seems to me that it should be common. Anyway: I've got the SQL query which returns: col1 | col2 | col3 -----+------+----- a | a10 | b20 a | a10 | b30 a | a20 | b30 I need to generate the following: Using Elementree it's not a problem when returned data is "flat", not hierarchical. However, that's not the case. Questions: 1) (I'll ask that on PostgreSQL group too) I use PostgreSQL. I understand that in order to achieve what I want directly from RDBMS I need SQL/XML language support which will be included in 8.3 which is not yet available. 2) Provided that I can't generate it from 1) should I take a deeper look into Gnosis Utils? http://www.gnosis.cx/download/Gnosis_Utils.More/ ? 3) I can generate series of select queries based on previous queries, but I can't imagine there isn't a better solution. Could you please clarify these for me? I'm a bit puzzled and frankly don't know where to start. Even a single URL which explains it in detail is greatly anticipated :). Thank you for your time, Marcin -- | And Do What You Will be the challenge | http://apcoln.linuxpl.org | So be it in love that harms none | http://biznes.linux.pl | For this is the only commandment. | http://www.juanperon.info `---* JID: Aragorn_Vime at jabber.org *---' http://www.naszedzieci.org From scott.daniels at acm.org Sun Jun 24 11:20:01 2007 From: scott.daniels at acm.org (Scott David Daniels) Date: Sun, 24 Jun 2007 08:20:01 -0700 Subject: is this a valid import sequence ? In-Reply-To: References: <4f97$467c254d$d443bb3a$9522@news.speedlinq.nl> <137qo1egg4v1k04@corp.supernews.com> <1i0694u.1n6evsntoei0wN%aleax@mac.com> <1i06hm3.1ii0h87p707f2N%aleax@mac.com> Message-ID: <137t2ro7p1cp531@corp.supernews.com> Steven D'Aprano wrote: > On Sat, 23 Jun 2007 21:11:42 -0700, Alex Martelli wrote a lot, with lots > of YELLING. > > Given the amount of SHOUTING in your post, and the fact that you feel so > strongly about the trivial question of the redundant use of the global > statement that you would "fail a student" who did it -- even if they did > everything else correctly, efficiently and elegantly -- it seems to me > that you are beyond rational discussion on this subject. I, for one, appreciate a second voice suggesting that your (Steve's) vehement rejection of my technically correct and non-condemnatory post explaining that one use of global in the OP's code was superfluous. You said (in the previous post): > That's technically true, but declaring it with global makes the code > self-documenting and therefore easier to read. > > It's never _wrong_ to use the global statement, even if it is strictly > unnecessary for the Python compiler. Your post led a newbie to presume the extra use of global was "good style," while I think you'll find there is no such consensus. --Scott David Daniels scott.daniels at acm.org From venner at gmail.com Fri Jun 15 09:38:54 2007 From: venner at gmail.com (Eric) Date: Fri, 15 Jun 2007 06:38:54 -0700 Subject: Want to learn Python In-Reply-To: <1181907696.878873.214760@i13g2000prf.googlegroups.com> References: <1181907696.878873.214760@i13g2000prf.googlegroups.com> Message-ID: <1181914734.324919.219830@n2g2000hse.googlegroups.com> On Jun 15, 7:41 am, Amol wrote: > Hi, I want to learn Python in less than a month which resources should > I use. I prefer to read books . Please give me a list of *recognized* > resources. Thank You all I started here: http://docs.python.org/tut/tut.html From nagle at animats.com Thu Jun 28 16:12:03 2007 From: nagle at animats.com (John Nagle) Date: Thu, 28 Jun 2007 13:12:03 -0700 Subject: Too many 'self' in python.That's a big flaw in this language. In-Reply-To: <1i0e2aq.1db0o2mbi0je1N%aleax@mac.com> References: <1182942154.185461.89620@e9g2000prf.googlegroups.com> <5efe34F37shinU1@mid.individual.net> <1i0e2aq.1db0o2mbi0je1N%aleax@mac.com> Message-ID: Alex Martelli wrote: > Bjoern Schliessmann > wrote: > ... > >>Mh, strange, I personally like to use "this.a" in C++, to make clear >>I use an instance variable. > > > That would be nice, unfortunately your C++ compiler will refuse that, > and force you to use this->a instead;-). Yes, as Strostrup admits, "this" should have been a reference. Early versions of C++ didn't have references. One side effect of that mistake was the "delete(this)" idiom, which does not play well with inheritance. But that's a digression here. John Nagle From bignose+hates-spam at benfinney.id.au Tue Jun 19 20:29:13 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 20 Jun 2007 10:29:13 +1000 Subject: Python and (n)curses References: <1182211133.956524.160020@g4g2000hsf.googlegroups.com> <87y7igzapo.fsf@benfinney.id.au> <1182252362.643492.93890@n2g2000hse.googlegroups.com> <87myywyszg.fsf@benfinney.id.au> <1182260860.240519.3570@n60g2000hse.googlegroups.com> Message-ID: <87abuvzcx2.fsf@benfinney.id.au> "pinkfloydhomer at gmail.com" writes: > On Jun 19, 3:27 pm, Ben Finney > wrote: > > "pinkfloydho... at gmail.com" writes: > > > Just to be more precise: curses is not a requirement, a > > > multi-platform console library with a single API is. So are there > > > alternatives to curses? Python-only or not. > > You wouldn't happen to have an answer to this question? No. -- \ "Most people, I think, don't even know what a rootkit is, so | `\ why should they care about it?" -- Thomas Hesse, Sony BMG, 2006 | _o__) | Ben Finney From S.Mientki-nospam at mailbox.kun.nl Thu Jun 7 14:43:50 2007 From: S.Mientki-nospam at mailbox.kun.nl (Stef Mientki) Date: Thu, 07 Jun 2007 20:43:50 +0200 Subject: Who uses Python? In-Reply-To: References: <1180985830.288414.208850@q69g2000hsb.googlegroups.com><1181028719.829671.22230@a26g2000pre.googlegroups.com><1181034089.239173.282900@g4g2000hsf.googlegroups.com><1181062218.780387.219200@n4g2000hsb.googlegroups.com> Message-ID: Hendrik van Rooyen wrote: > "Stef Mientki" wrote: > >> I use Python as a replacement for MatLab, >> and intend to use it as replacement for Delphi, AutoIt, PHP, VB. >> And I'ld love to use it as a replacement for micro controller programming. > > If you have a little sub - 64k micro this is not really practical. > > What we have done is to define a limited virtual machine with > a simple "assembler" language and used Python to write the > "compiler" for it. > > Then you have to write the interpreter for the virtual machine > in the native micro's code - Either using C or assembler, and > you are away from the hardware, into a useful layer of abstraction. > > ... well sort of - in such a small thing, you are never really far from > the hardware, as that is what its supposed to be controlling - but > what it definitely buys you is that your apps written in your special > language become portable between disparate processors like say > an ARM at the upper end and an 8031/8051 at the lower... > > Such "interpreters" are surprisingly little code, and they work > well - faster than what one would expect. - often outperforming > C code that does pass by value... > > - Hendrik > hello Hendrik, I use even smaller micro controllers (PIC) and as I'm just writing a functional simulator for it in Python, (see http://oase.uci.kun.nl/~mientki/data_www/pic/jalcc/python/jal_simulation.html and even a small movie: (600 kB) http://oase.uci.ru.nl/~mientki/download/jal_simulator1.htm I would love to see your code, not directly to use it (I want JAL), but it might give me some good ideas. cheers, Stef Mientki From nun at example.com Tue Jun 19 17:23:30 2007 From: nun at example.com (Mitja Trampus) Date: Tue, 19 Jun 2007 23:23:30 +0200 Subject: PIL cutting off letters In-Reply-To: <1181934049.401650.115360@q19g2000prn.googlegroups.com> References: <1181934049.401650.115360@q19g2000prn.googlegroups.com> Message-ID: <8PXdi.984$553.895758@news.siol.net> Matt Haggard wrote: > I'm using PIL (Python Imaging Library) to generate button images. > They consist of a left end image, a middle, repeating image and a > right side image.... anyway, that's not important > > I'm using a TTF font for the text of the button (Verdana.TTF) and it > keeps cutting the bottom part of the the g's q's and y's off. I've had the same problems. What worked for me was to use aggdraw instead of PIL's Draw class. http://effbot.org/zone/aggdraw-index.htm Mitja From steven.bethard at gmail.com Wed Jun 13 18:54:01 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 13 Jun 2007 16:54:01 -0600 Subject: one-time initialization of class members In-Reply-To: <1181772494.803499.266690@o11g2000prd.googlegroups.com> References: <1181772494.803499.266690@o11g2000prd.googlegroups.com> Message-ID: James Turk wrote: > Hi, > > I have a situation where I have some class members that should only be > done once. Essentially my problem looks like this: > > class Base(object): > dataset = None > > def __init__(self, param): > if type(self).dataset is None: > # code to load dataset based on param, expensive > > class ChildClass1(Base): > def __init__(self): > Base.__init__(self, data_params) > > class AnotherChildClass(Base): > def __init__(self): > Base.__init__(self, other_data_params) > > > This seems to work, initialization is only done at the first creation > of either class. I was just wondering if this is the 'pythonic' way > to do this as my solution does feel a bit hackish. What should happen with code like:: ChildClass1('foo') ChildClass1('bar') The 'param' is different, but 'dataset' should only get set the first time? STeVe From steve at REMOVE.THIS.cybersource.com.au Thu Jun 14 13:17:25 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Fri, 15 Jun 2007 03:17:25 +1000 Subject: Method much slower than function? References: <1181781612.939800.238890@q19g2000prn.googlegroups.com> Message-ID: On Thu, 14 Jun 2007 00:40:12 +0000, idoerg wrote: >>>> cProfile.run("bar.readgenome(open('cb_foo'))") > 20004 function calls in 10.214 CPU seconds This calls the method on the CLASS, instead of an instance. When I try it, I get this: TypeError: unbound method readgenome() must be called with bar instance as first argument (got file instance instead) So you're running something subtly different than what you think you're running. Maybe you assigned bar = bar() at some point? However, having said that, the speed difference does seem to be real: even when I correct the above issue, I get a large time difference using either cProfile.run() or profile.run(), and timeit agrees: >>> f = bar().readgenome >>> timeit.Timer("f(open('cb_foo'))", "from __main__ import f").timeit(5) 18.515995025634766 >>> timeit.Timer("readgenome(open('cb_foo'))", "from __main__ import readgenome").timeit(5) 0.1940619945526123 That's a difference of two orders of magnitude, and I can't see why. -- Steven. From boyee118 at gmail.com Sat Jun 9 21:53:08 2007 From: boyee118 at gmail.com (boyeestudio) Date: Sun, 10 Jun 2007 09:53:08 +0800 Subject: Are there any python jobs worked at home from the internet? Message-ID: Hi,all buddies. Are there any python jobs worked at home from the internet? I want to find a part time job. Please give a clue to this for me. Thanks a lot! -------------- next part -------------- An HTML attachment was scrubbed... URL: From gagsl-py2 at yahoo.com.ar Tue Jun 19 23:44:52 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 20 Jun 2007 00:44:52 -0300 Subject: Help With Better Design References: <1182303267.427179.223720@i13g2000prf.googlegroups.com> Message-ID: En Tue, 19 Jun 2007 22:34:27 -0300, escribi?: > I have been working on a little project today to help me better > understand classes in Python (I really like Python). I am a self > taught programmer and consider myself to fall in the "beginner" > category for sure. It was initially sparked by reading about "state > machines". This was my attempt at it however I feel it is not quite > where it should be: That's rather good as it is! > ON = "ON" > OFF = "OFF" > > class LightBulb: > def __init__(self, initial_state): > self.state = initial_state > > def TurnOn(self): > if self.state == OFF: > self.state = ON > else: > print "The Bulb Is Already ON!" One could argue here: is it an error to attempt to turn the light on again, if it is already on? If yes: raising an exception is the usual way to report error conditions (let the caller handle it, if he cares enough) If not: why to check the current state? Just set the new state as ON, whatever was the prior state. The same for TurnOff. (BTW, the reccomended style is to use lower_case (best) or mixedCase for method names: turn_on or turnOn) > def TurnOff(self): > if self.state == ON: > self.state = OFF > else: > print "The Bulb Is Aleady OFF!" > > if __name__== "__main__": > light = LightBulb(OFF) > simulation_running = True > while simulation_running: > print "The light is", light.state > print "" > print "Please choose an action:" > print "" > print "[1] Turn Light On" > print "[2] Turn Light Off" > print "[3] Exit Simulation" > print "" > u_choice = raw_input("Please Enter Your Choice: ") > if u_choice == '1': > light.TurnOn() > if u_choice == '2': > light.TurnOff() > elif u_choice == '3': > break > else: > continue > > The test portion of the code is actually longer than the class > itself :-) That's often the case! > I would like to be able to get a good hold of the concept > with this example before I try to model a more complex problem. Would > someone be willing to give me some feedback on this class and whether > I am on the right track or how I might better go about it? The example is fine. You could move on from "interactive testing" (your "demo" program, where a human runs some code, more-or-less at random, sees the results and judges by himself if it is "OK" or "wrong") into "automated unit testing": an automated sequence of tests, each with its input and expected output, that can be executed automatically and without any human intervention. There is a framework for writing those (see the unittest module), but you can start just by using the assert statement: light = LightBulb(OFF) assert light.state == OFF # ensure that it gets initialized correctly light.TurnOn() assert light.state == ON # ensure that TurnOn actually does as intended light.TurnOff() assert light.state == OFF light.TurnOff() assert light.state == OFF # an attempt to turn it off again should leave it off light.TurnOn() light.TurnOn() # an attempt to turn it on again assert light.state == ON # some more tests light = LightBulb(ON) assert light.state == ON # should test both initial states light = LightBulb(0) # what should happen here? light.TurnOn() assert light.state == ON # oops! light.TurnOff() assert light.state == OFF # oops! This has many advantages: you can write the tests carefully once and run many times later, and detect breakages; you can't take a "likely" answer for a "true" answer; etc. -- Gabriel Genellina From nejtak... Sat Jun 30 04:54:43 2007 From: nejtak... (Troels Thomsen) Date: Sat, 30 Jun 2007 10:54:43 +0200 Subject: ironpython exception line number References: <46817805$0$25410$edfadb0f@dread11.news.tele.dk> Message-ID: <46861a5b$0$19356$edfadb0f@dread11.news.tele.dk> >If you're hosting IronPython and catching this from a .NET language >then you'll be catching the .NET exception. Yes >In that case you can access the original Python exception >from ex.Data["PythonExceptionInfo"]. Yes ! YES ! Thx regards tpt From moishyyehuda at gmail.com Thu Jun 28 09:42:01 2007 From: moishyyehuda at gmail.com (comeshopcheap) Date: Thu, 28 Jun 2007 13:42:01 -0000 Subject: using urllib, urllib2 ,mechanize to access password protected site Message-ID: <1183038121.174729.230750@c77g2000hse.googlegroups.com> Hi I am using this script to access doba.com (I need to download some files) but I keep on being sent back to the login page not the user home page. Any help. I think I may need to use a post method and opener is using a get method Thanks import mechanize cookies = mechanize.CookieJar() # build_opener() adds standard handlers (such as HTTPHandler and # HTTPCookieProcessor) by default. The cookie processor we supply # will replace the default one. opener = mechanize.build_opener(mechanize.HTTPCookieProcessor(cookies)) opener.addheaders = [("User-agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.4) Gecko/20070515 Firefox/2.0.0.4"), ] data="username=user&password=pw" #r = opener.open("http://comeshopcheap.com/") # GET r = opener.open("https://www.doba.com/members/login.php", data) # POST From bruno.42.desthuilliers at wtf.websiteburo.oops.com Thu Jun 28 03:30:28 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Thu, 28 Jun 2007 09:30:28 +0200 Subject: PEP 3107 and stronger typing (note: probably a newbie question) In-Reply-To: References: <1182369568.941307.316260@p77g2000hsh.googlegroups.com> <5dveb4F360un0U1@mid.individual.net> <467a9209$0$22165$426a74cc@news.free.fr> <1182858785.886469.93060@n60g2000hse.googlegroups.com> <46824d8d$0$2324$426a74cc@news.free.fr> <4682eddc$0$23164$426a74cc@news.free.fr> Message-ID: <46836382$0$10976$426a34cc@news.free.fr> Stephen R Laniel a ?crit : > On Thu, Jun 28, 2007 at 09:08:16AM +0200, Bruno Desthuilliers wrote: >> You said ? > > I could link again to Mark-Jason Dominus, who writes that > people often make the following inference: > > 1) C is strongly typed. Lol. C is well known for it's very weak typing. > 2) C's typing sucks. > 3) Hence strong typing sucks. Whoever make such a braindead inference should better learn the meaning of words, read more about the concepts and applications of 'typing' in CS, and experiment with type-inference based languages. > But I won't. > > It doesn't need to be a religious war. Why can't people just > say "When strong typing is done and used well, it's a > useful tool; when it's not, it's not"? Python is actually a rather strongly typed language. Some would even say it's more strongly typed than C. Please stop confusing static with strong. "static" means 'at compile time' - by opposition with "dynamic", meaning 'at run time'. This is somewhat orthogonal to the 'weak/strong' axis. From deets at nospam.web.de Wed Jun 20 08:27:21 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 20 Jun 2007 14:27:21 +0200 Subject: Packing a simple dictionary into a string - extending struct? References: Message-ID: <5dskp9F366t82U1@mid.uni-berlin.de> > What about JSON? You can serialize your dictionary, for example, in > JSON format and then unserialize it in any language that has a JSON > parser (unless it is Javascript). There is an implementation available for python called simplejson, available through easy_install. Diez From mkb at incubus.de Tue Jun 19 10:30:09 2007 From: mkb at incubus.de (Matthias Buelow) Date: Tue, 19 Jun 2007 16:30:09 +0200 Subject: The Modernization of Emacs In-Reply-To: <861wg8rqy6.fsf@lola.quinscape.zz> References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <873b0p9vpm.fsf@W0053328.mgh.harvard.edu> <861wg8rqy6.fsf@lola.quinscape.zz> Message-ID: <5dq7j6F33s1anU1@mid.dfncis.de> David Kastrup wrote: > My favorite killing offence is /* vi:set ts=4: */. This is apparently the default setting in many of the so-called "IDE"s today.. I think it's another unwelcome poison gift from the ignorant M$FT world (I suspect some primitive Windoze IDE which couldn't differentiate between TAB and indent probably offered the programmer changing the tabwidth as the only method for changing indentation, and then this method got stuck...) F'up to comp.emacs. From david08520 at yahoo.com Fri Jun 8 13:38:32 2007 From: david08520 at yahoo.com (David) Date: Fri, 8 Jun 2007 13:38:32 -0400 Subject: VIM editor question Message-ID: Is anyone in the group familiar with the VIM editor? I rather like it but any time I right click on a file and select "Edit with Vim" It opens the file in a rather ugly default color scheme. I'd love to know how to make it automatically open files I select in my favorite color scheme rather than having to go into the " EDIT "pull down menu and select my preferred Color Scheme every time I open a file. thanks for any wisdom you can share David KG2LI From __peter__ at web.de Tue Jun 26 16:55:08 2007 From: __peter__ at web.de (Peter Otten) Date: Tue, 26 Jun 2007 22:55:08 +0200 Subject: problem mixing gettext and properties References: <1182880358.100599.139120@j4g2000prf.googlegroups.com> <1182885474.515335.242470@e9g2000prf.googlegroups.com> <1182890787.295156.161000@g37g2000prf.googlegroups.com> Message-ID: Andr? wrote: > On Jun 26, 4:17 pm, Andr? wrote: >> On Jun 26, 3:56 pm, Peter Otten <__pete... at web.de> wrote: >> >> >> >> > Andr? wrote: >> > > I've encountered a problem using gettext with properties while using >> > > a Python interpreter. >> >> > > Here's a simple program that illustrate the problem. >> > > ============== >> > > # i18n_test.py: test of gettext & properties >> >> > > import gettext >> >> > > fr = gettext.translation('i18n_test', './translations', >> > > languages=['fr']) >> >> > _ = fr.gettext # untested >> >> > > help = _("Help me!") >> >> > > class Test_i18n(object): >> > > def get(self): >> > > __help = _("HELP!") >> > > return __help >> > > help_prop = property(get, None, None, 'help') >> >> > > test = Test_i18n() >> >> > > print help >> > > print test.help_prop >> > > #### end of file >> >> > > To run the above program, you need to have the strings translated and >> > > the proper ".po" and ".mo" files created. (for those interested, I >> > > can send the whole lot in a zip file) >> >> > > If I run the program as is, the output is: >> > > Aidez-moi! >> > > AIDE!!! >> >> > > Ok, let's try with the Python interpreter: >> >> > > ActivePython 2.4.2 Build 248 (ActiveState Corp.) based on >> > > Python 2.4.2 (#67, Oct 30 2005, 16:11:18) [MSC v.1310 32 bit (Intel)] >> > > on win32 >> > > Type "help", "copyright", "credits" or "license" for more >> > > information. >> > >>>> import i18n_test >> > > Aidez-moi! >> > > AIDE!!!_("HELP!") >> >> > > # No surprise there so far. >> >> > >>>> print i18n_test.help >> > > Aidez-moi! >> > >>>> print i18n_test.test.help_prop >> > > AIDE!!! >> > >>>> i18n_test.help >> > > 'Aidez-moi!' >> >> > > # all of the above are as expected; now for the first surprise >> >> > >>>> i18n_test.test.help_prop >> > > Traceback (most recent call last): >> > > File "", line 1, in ? >> > > File "i18n_test.py", line 12, in get >> > > __help = _("HELP!") >> > > TypeError: 'str' object is not callable >> >> > > # and a second surprise where we try to repeat something that used to >> > > work >> >> > >>>> print i18n_test.test.help_prop >> > > Traceback (most recent call last): >> > > File "", line 1, in ? >> > > File "i18n_test.py", line 12, in get >> > > __help = _("HELP!") >> > > TypeError: 'str' object is not callable >> >> > > #============= >> >> > > Dare I say: "Help!" I really need to use the above at the >> > > interpreter prompt. >> >> > > Andr? >> >> > The _ builtin is set to the result of the last expression evaluated by >> > the interpreter: >> >> > >>> for i in range(3): >> >> > ... i >> > ... >> > 0 >> > 1 >> > 2>>> _ >> > 2 >> > >>> import __builtin__ >> > >>> __builtin__._ >> >> > 2 >> >> > Therefore you get a name clash with _() as an alias for gettext(). Use >> > module-global aliases instead, e. g. >> >> > _ = fr.gettext >> >> > in the above code. >> >> > Peter >> >> Thanks, that works ... but, > [snip...] > One more question (back to the original) post. > Why does > i18n_test.help > does the right thing > but > i18n_test.test.help_prop > does not? Both use _() ... > > Is it because help = _(...) is defined at the module level but > test.help_prop is defined locally, and that the lookup for _() is done > first locally (finds nothing) and then globally (outside the module > scope) ? No, it has nothing to do with the scope. It is just that (assuming a single-threaded environment) help = _("Help me!") is evaluated once immediately after the install() call which sets __builtin__._ to gettext(). i18n_test.test.help_prop on the other hand invokes __builtin__._() every time, and because you implicitly set it to a string with >>> i18n_test.help you saw the exception. Peter From gnewsg at gmail.com Fri Jun 8 15:57:56 2007 From: gnewsg at gmail.com (billiejoex) Date: Fri, 08 Jun 2007 12:57:56 -0700 Subject: FTP/SSL In-Reply-To: References: <846ee3740706060745r67eff604j770be015b3b37785@mail.gmail.com> Message-ID: <1181332676.534242.92110@h2g2000hsg.googlegroups.com> On 8 Giu, 16:54, "Dave Borne" wrote: > > I'm trying to figure out how to use FTP/SSL (FTPS) - just as a client. Can I > > do this in Python? Is everything I need in ftplib? Where else do I look? And > > - any good newbie references on using FTPS? > > Hi, Nancy, > I'm not sure if ftplib can handle ssh or not, but googling for > "python sftp" turned up this link:http://www.lag.net/paramiko/ > > It looks like it might do what you want. > > -Dave SFTP is FTP over SSH, quite different from FTPS that's FTP over TLS/ SSL. Actually Python really lacks of good / maintained SSL libraries. From paul.sijben at xs4all.nl Wed Jun 13 02:31:33 2007 From: paul.sijben at xs4all.nl (Paul Sijben) Date: Wed, 13 Jun 2007 08:31:33 +0200 Subject: Windows XP timezone language issue Message-ID: <466f8f45$0$329$e4fe514c@news.xs4all.nl> I ran into an internationalization issue. I need a consistent idea about the timezone my application is running on. However when I run the following: >>> import time >>> time.tzname I get back ('West-Europa (standaardtijd)', 'West-Europa (zomertijd)') which is in dutch (the language of the host machine) and verbose. I wanted to get ('CEST','CET') or something international so I can work with itin the same way on all platforms. That is the right way to find out the timezone in a consistent way across platforms (windows/linux/mac) and languages? Paul From bjobrien62 at gmail.com Thu Jun 14 16:16:42 2007 From: bjobrien62 at gmail.com (SpreadTooThin) Date: Thu, 14 Jun 2007 13:16:42 -0700 Subject: Convert to C/C++? Message-ID: <1181852202.897976.312280@j4g2000prf.googlegroups.com> I am wondering if someone who knows the implemention of python's time could help converting this to c/c++.... nanoseconds = int(time.time() * 1e9) # 0x01b21dd213814000 is the number of 100-ns intervals between the # UUID epoch 1582-10-15 00:00:00 and the Unix epoch 1970-01-01 00:00:00. self.timestamp = int(nanoseconds/100) + 0x01b21dd213814000L self.clock_seq = random.randrange(1<<14L) # instead of stable storage self.time_low = self.timestamp & 0xffffffffL self.time_mid = (self.timestamp >> 32L) & 0xffffL self.time_hi_version = (self.timestamp >> 48L) & 0x0fffL self.clock_seq_low = self.clock_seq & 0xffL self.clock_seq_hi_variant = (self.clock_seq >> 8L) & 0x3fL #print 'timestamp ', self.timestamp, self.time_low, self.time_mid, self.time_hi_version #print 'clock_seq ', self.clock_seq, self.clock_seq_low, self.clock_seq_hi_variant vs unix gettimeofday.... int gettimeofday(struct timeval *tp, struct timezone *tzp); struct timeval { long tv_sec; /* seconds since Jan. 1, 1970 */ long tv_usec; /* and microseconds */ }; struct timezone { int tz_minuteswest; /* of Greenwich */ int tz_dsttime; /* type of dst correction to apply */ }; From bbxx789_05ss at yahoo.com Mon Jun 18 19:00:06 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: Mon, 18 Jun 2007 16:00:06 -0700 Subject: getting the size of an object In-Reply-To: References: Message-ID: <1182207606.651533.285020@c77g2000hse.googlegroups.com> On Jun 18, 10:07 am, "filox" wrote: > is there a way to find out the size of an object in Python? e.g., how could > i get the size of a list or a tuple? > > -- > You're never too young to have a Vietnam flashback You can use the struct module to find the size in bytes: import struct mylist = [10, 3.7, "hello"] int_count = 0 float_count = 0 char_count = 0 for elmt in mylist: if type(elmt) == int: int_count += 1 elif type(elmt) == float: float_count += 1 elif type(elmt) == str: char_count += len(elmt) format_string = "%di%dd%dc" % (int_count, float_count, char_count) list_size_in_bytes = struct.calcsize(format_string) print list_size_in_bytes --output:-- 17 From f.guerrieri at gmail.com Wed Jun 6 06:14:17 2007 From: f.guerrieri at gmail.com (Francesco Guerrieri) Date: Wed, 6 Jun 2007 12:14:17 +0200 Subject: overriding setting Message-ID: <79b79e730706060314x4d401393r810574f7c2d46406@mail.gmail.com> Hello, this is my first post to the list :-) I've looked around a bit before asking, and since I haven't found... I'm here to ask my question. I'm trying to ovveride attribute setting, but I haven't still found the right way to use all the fancy __get__, __set__ and __getattribute__ :-) I would like to retain initialization of an object by use of the = and not as a function call. A simple example is this: I want to define an "enhanced" list class, whose items will be other (built in) lists and providing a "padding" method which fills all the contained lists to the same lenght. An example could be: class myList(list): def __init__(self): self._max = None list.__init__(self) def pad(self): for item in self: if type(item)== list: while len(item) < self._max: item.append("") Now the question is this: I would like to initialize such an object in this way: a = myList() a = [[1, 2, 3], [4, 5, 6, 7]] a.pad() # and now a _should_ contain [[1, 2, 3, ""], [4, 5, 6, 7]] Obviously this doesn't work, because when at the second line I do the initialization, type(a) becomes , and so I get the expected AttributeError since pad cannot be found. A possible solution could be to create a container class, intercepting every attribute accession with __getattribute__. In this case I should refer to Container.myFirstList, Container.mySecondList, which is ugly because of the need to refer to Container first...(not to mention that I'm still working on making the __getattribute__ work properly... :-) ) Do you have any suggestions? or maybe I should simply stop trying to do that and resort to adding some sort of insert or append method (this is what I have done for the time being, but I found this solution less appealing and nice ...) thanks in advance, Francesco -- "Voil?! In view, a humble vaudevillian veteran, cast vicariously as both victim and villain by the vicissitudes of fate. This visage, no mere veneer of vanity, is a vestige of the vox populi, now vacant, vanished. However, this valorous visitation of a bygone vexation stands vivified, and has vowed to vanquish these venal and virulent vermin vanguarding vice and vouchsafing the violently vicious and voracious violation of volition. The only verdict is vengeance; a vendetta held as a votive, not in vain, for the value and veracity of such shall one day vindicate the vigilant and the virtuous. Verily, this vichyssoise of verbiage veers most verbose vis-?-vis an introduction, so let me simply add that it's my very good honor to meet you and you may call me V." -- V's introduction to Evey From pelonpelon at gmail.com Thu Jun 21 05:22:34 2007 From: pelonpelon at gmail.com (pelon) Date: Thu, 21 Jun 2007 09:22:34 -0000 Subject: SimplePrograms challenge In-Reply-To: References: Message-ID: <1182417754.553370.206910@m36g2000hse.googlegroups.com> And while I'm at it... Although Guido's tutorial was a great place to start when I first came to python I would have learned more and faster had SimplePrograms existed. My only complaint with the python documentation is the dearth of examples. The PHP documentation is chock full. Steve, You introduced this as a challenge. Why not make it so? JUST FOR FUN I propose that blank lines and comments not be counted. There should probably be an upper and lower limit on new concepts introduced. There should be an emphasis on common, real world functionality. The standard library should be used freely (although limited to the most common modules). I don't mean to turn this game into something too formal and serious, but it's obvious from the enthusiasm shown on this thread that pythonistas take their fun seriously. From wheezl at gmail.com Wed Jun 6 08:38:07 2007 From: wheezl at gmail.com (wheezl at gmail.com) Date: Wed, 06 Jun 2007 05:38:07 -0700 Subject: Who uses Python? In-Reply-To: <1180985830.288414.208850@q69g2000hsb.googlegroups.com> References: <1180985830.288414.208850@q69g2000hsb.googlegroups.com> Message-ID: <1181133487.651632.127130@g4g2000hsf.googlegroups.com> walterbyrd ha scritto: > I mean other than sysadmins, programmers, and web-site developers? > > I have heard of some DBAs who use a lot of python. > > I suppose some scientists. I think python is used in bioinformatics. I > think some math and physics people use python. > > I suppose some people use python to learn "programming" in general. > Python would do well as a teaching language. > > I would think that python would be a good language for data analysis. > > Anything else? Finance? Web-analytics? SEO? Digital art? We use it for everything from automated tape handling and cleaning systems to driving encoders and specialized TBCs as well as controlling creaky old video decks. The core logic of our system is also in python which using a little bit of Twisted ties together the FreeBSD and Windows machines that the various daemons run on. Though that doesn't answer your question since I guess that makes us "programmers" whom I am sure own the lion's share of python usage. From china_city2008 at yahoo.com.cn Wed Jun 20 11:11:04 2007 From: china_city2008 at yahoo.com.cn (jim) Date: Wed, 20 Jun 2007 08:11:04 -0700 Subject: business on line follow me ! Message-ID: <1182352264.327987.130470@e9g2000prf.googlegroups.com> hello: madam and sir . we sell all kinds of laptops and digital cam .our product is a quantity best, the price is the lowest in the world, i think you will be interested in our product . thanks a lot! Our Website:http://www.prs-123.com/ Msn: prs_cool_123 at hotmail.com mail: prs_cool_123 at yahoo.com.cn thanks for everyone good luck with everyone . @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ hello : madam and sir. we sell all kinds of laptops and digital cam .our product is a quantity best, the price is the lowest in the world, i think you will be interested in our product . thanks a lot! Our Website:http:// www.prs-123.com/ Msn: prs_cool_123 at hotmail.com mail: prs_cool_123 at yahoo.com.cn thanks for everyone good luck with everyone @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ hello: madam and sir . we sell all kinds of laptops and digital cam .our product is a quantity best, the price is the lowest in the world, i think you will be interested in our product . thanks a lot! Our Website:http:// www.prs-123.com/ Msn: prs_cool_123 at hotmail.com mail: prs_cool_123 at yahoo.com.cn thanks for everyone good luck with everyone . @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ hello : madam and sir. we sell all kinds of laptops and digital cam .our product is a quantity best, the price is the lowest in the world, i think you will be interested in our product . thanks a lot! Our Website:http:// www.prs-123.com/ Msn: prs_cool_123 at hotmail.com mail: prs_cool_123 at yahoo.com.cn thanks for everyone good luck with everyone hello: madam and sir . we sell all kinds of laptops and digital cam .our product is a quantity best, the price is the lowest in the world, i think you will be interested in our product . thanks a lot! Our Website:http://www.prs-123.com/ Msn: prs_cool_123 at hotmail.com mail: prs_cool_123 at yahoo.com.cn thanks for everyone good luck with everyone . @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ hello : madam and sir. we sell all kinds of laptops and digital cam .our product is a quantity best, the price is the lowest in the world, i think you will be interested in our product . thanks a lot! Our Website:http:// www.prs-123.com/ Msn: prs_cool_123 at hotmail.com mail: prs_cool_123 at yahoo.com.cn thanks for everyone good luck with everyone @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ hello: madam and sir . we sell all kinds of laptops and digital cam .our product is a quantity best, the price is the lowest in the world, i think you will be interested in our product . thanks a lot! Our Website:http:// www.prs-123.com/ Msn: prs_cool_123 at hotmail.com mail: prs_cool_123 at yahoo.com.cn thanks for everyone good luck with everyone . @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ hello : madam and sir. we sell all kinds of laptops and digital cam .our product is a quantity best, the price is the lowest in the world, i think you will be interested in our product . thanks a lot! Our Website:http:// www.prs-123.com/ Msn: prs_cool_123 at hotmail.com mail: prs_cool_123 at yahoo.com.cn thanks for everyone good luck with everyone hello: madam and sir . we sell all kinds of laptops and digital cam .our product is a quantity best, the price is the lowest in the world, i think you will be interested in our product . thanks a lot! Our Website:http://www.prs-123.com/ Msn: prs_cool_123 at hotmail.com mail: prs_cool_123 at yahoo.com.cn thanks for everyone good luck with everyone . @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ hello : madam and sir. we sell all kinds of laptops and digital cam .our product is a quantity best, the price is the lowest in the world, i think you will be interested in our product . thanks a lot! Our Website:http:// www.prs-123.com/ Msn: prs_cool_123 at hotmail.com mail: prs_cool_123 at yahoo.com.cn thanks for everyone good luck with everyone @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ hello: madam and sir . we sell all kinds of laptops and digital cam .our product is a quantity best, the price is the lowest in the world, i think you will be interested in our product . thanks a lot! Our Website:http:// www.prs-123.com/ Msn: prs_cool_123 at hotmail.com mail: prs_cool_123 at yahoo.com.cn thanks for everyone good luck with everyone . @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ hello : madam and sir. we sell all kinds of laptops and digital cam .our product is a quantity best, the price is the lowest in the world, i think you will be interested in our product . thanks a lot! Our Website:http:// www.prs-123.com/ Msn: prs_cool_123 at hotmail.com mail: prs_cool_123 at yahoo.com.cn thanks for everyone good luck with everyone hello: madam and sir . we sell all kinds of laptops and digital cam .our product is a quantity best, the price is the lowest in the world, i think you will be interested in our product . thanks a lot! Our Website:http://www.prs-123.com/ Msn: prs_cool_123 at hotmail.com mail: prs_cool_123 at yahoo.com.cn thanks for everyone good luck with everyone . @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ hello : madam and sir. we sell all kinds of laptops and digital cam .our product is a quantity best, the price is the lowest in the world, i think you will be interested in our product . thanks a lot! Our Website:http:// www.prs-123.com/ Msn: prs_cool_123 at hotmail.com mail: prs_cool_123 at yahoo.com.cn thanks for everyone good luck with everyone @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ hello: madam and sir . we sell all kinds of laptops and digital cam .our product is a quantity best, the price is the lowest in the world, i think you will be interested in our product . thanks a lot! Our Website:http:// www.prs-123.com/ Msn: prs_cool_123 at hotmail.com mail: prs_cool_123 at yahoo.com.cn thanks for everyone good luck with everyone . @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ hello : madam and sir. we sell all kinds of laptops and digital cam .our product is a quantity best, the price is the lowest in the world, i think you will be interested in our product . thanks a lot! Our Website:http:// www.prs-123.com/ Msn: prs_cool_123 at hotmail.com mail: prs_cool_123 at yahoo.com.cn thanks for everyone good luck with everyone hello: madam and sir . we sell all kinds of laptops and digital cam .our product is a quantity best, the price is the lowest in the world, i think you will be interested in our product . thanks a lot! Our Website:http://www.prs-123.com/ Msn: prs_cool_123 at hotmail.com mail: prs_cool_123 at yahoo.com.cn thanks for everyone good luck with everyone . @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ hello : madam and sir. we sell all kinds of laptops and digital cam .our product is a quantity best, the price is the lowest in the world, i think you will be interested in our product . thanks a lot! Our Website:http:// www.prs-123.com/ Msn: prs_cool_123 at hotmail.com mail: prs_cool_123 at yahoo.com.cn thanks for everyone good luck with everyone @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ hello: madam and sir . we sell all kinds of laptops and digital cam .our product is a quantity best, the price is the lowest in the world, i think you will be interested in our product . thanks a lot! Our Website:http:// www.prs-123.com/ Msn: prs_cool_123 at hotmail.com mail: prs_cool_123 at yahoo.com.cn thanks for everyone good luck with everyone . @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ hello : madam and sir. we sell all kinds of laptops and digital cam .our product is a quantity best, the price is the lowest in the world, i think you will be interested in our product . thanks a lot! Our Website:http:// www.prs-123.com/ Msn: prs_cool_123 at hotmail.com mail: prs_cool_123 at yahoo.com.cn thanks for everyone good luck with everyone From sebzzz at gmail.com Mon Jun 18 10:00:39 2007 From: sebzzz at gmail.com (sebzzz at gmail.com) Date: Mon, 18 Jun 2007 07:00:39 -0700 Subject: Parsing HTML, extracting text and changing attributes. Message-ID: <1182175239.122827.4150@g4g2000hsf.googlegroups.com> Hi, I work at this company and we are re-building our website: http://caslt.org/. The new website will be built by an external firm (I could do it myself, but since I'm just the summer student worker...). Anyways, to help them, they first asked me to copy all the text from all the pages of the site (and there is a lot!) to word documents. I found the idea pretty stupid since style would have to be applied from scratch anyway since we don't want to get neither old html code behind nor Microsoft Word BS code. I proposed to take each page and making a copy with only the text, and with class names for the textual elements (h1, h1, p, strong, em ...) and then define a css file giving them some style. Now, we have around 1 600 documents do work on, and I thought I could challenge myself a bit and automate all the dull work. I thought about the possibility of parsing all those pages with python, ripping of the navigations bars and just keeping the text and layout tags, and then applying class names to specific tags. The program would also have to remove the table where text is located in. And other difficulty is that I want to be able to keep tables that are actually used for tabular data and not positioning. So, I'm writing this to have your opinion on what tools I should use to do this and what technique I should use. From nyamatongwe+thunder at gmail.com Fri Jun 1 08:12:18 2007 From: nyamatongwe+thunder at gmail.com (Neil Hodgson) Date: Fri, 01 Jun 2007 12:12:18 GMT Subject: getmtime differs between Py2.5 and Py2.4 In-Reply-To: References: <463FA51D.1060600@v.loewis.de> <463fb305$0$326$e4fe514c@news.xs4all.nl> <1178585991.924458.154570@l77g2000hsb.googlegroups.com> <1hxrebv.5tn2pnql23q7N%aleax@mac.com> <46401FDC.4010705@v.loewis.de> Message-ID: Joe Salmeri: > I can see that you guys have already spent alot of time investigating this > but surely the results should match what Windows Explorer says or what the > dir command returns??? One problem I have seen is that Windows Explorer and its File Properties sheet sometimes cache time values. Even closing and reopening the properties can show the old value. dir should always read the times though. Neil From josiah.carlson at sbcglobal.net Mon Jun 11 12:20:37 2007 From: josiah.carlson at sbcglobal.net (Josiah Carlson) Date: Mon, 11 Jun 2007 09:20:37 -0700 Subject: memory efficient set/dictionary In-Reply-To: <1181555743.786214.102780@q66g2000hsg.googlegroups.com> References: <1181485676.481109.234980@c77g2000hse.googlegroups.com> <1181492122.508277.209500@n4g2000hsb.googlegroups.com> <1181555743.786214.102780@q66g2000hsg.googlegroups.com> Message-ID: koara wrote: >>> I would recommend you to use a database since it meets your >>> requirements (off-memory, fast, persistent). The bsdddb module >>> (berkeley db) even gives you a dictionary like interface. >>> http://www.python.org/doc/lib/module-bsddb.html >> Standard SQL databases can work for this, but generally your >> recommendation of using bsddb works very well for int -> int mappings. >> In particular, I would suggest using a btree, if only because I have had >> troubles in the past with colliding keys in the bsddb.hash (and recno is >> just a flat file, and will attempt to create a file i*(record size) to >> write to record number i . >> >> As an alternative, there are many search-engine known methods for >> mapping int -> [int, int, ...], which can be implemented as int -> int, >> where the second int is a pointer to an address on disk. Looking into a >> few of the open source search implementations may be worthwhile. > > Thanks guys! I will look into bsddb, hopefully this doesn't keep all > keys in memory, i couldn't find answer to that during my (very brief) > look into the documentation. No, bsddb does not keep all data in memory. > And how about the extra memory used for set/dict'ing of integers? Is > there a simple answer? A non-long integer for a 32 bit Python uses 12 bytes. A non-long integer for a 64 bit Python uses 24 bytes. Each entry in a dictionary for a 32 bit Python uses 12 bytes; 4 for the hash, 4 for the key pointer, 4 for the value pointer. Double that to 24 bytes each in the 64 bit Python (I don't know if the hash actually has its range increased, but if one doesn't double the size of the pointers, then you have alignment issues that can slow down dictionary access). Sets only have the hash and key pointers, so only use 8/16 bytes per entry. - Josiah From bacon.chao at gmail.com Fri Jun 29 05:45:25 2007 From: bacon.chao at gmail.com (bacon.chao at gmail.com) Date: Fri, 29 Jun 2007 09:45:25 -0000 Subject: socket on cygwin python In-Reply-To: References: <1182748882.617588.190230@c77g2000hse.googlegroups.com> Message-ID: <1183110325.924699.123000@w5g2000hsg.googlegroups.com> On Jun 26, 12:49 am, Jason Tishler wrote: > On Mon, Jun 25, 2007 at 01:53:18PM +0100, Michael Hoffman wrote: > > bacon.c... at gmail.com wrote: > > > I've installed cygwin with latest python 2.5.1, but it seems that the > > > socket lib file do NOT support IPv6(cygwin\lib\python2.5\lib-dynload > > > \_socket.dll), what can I do if I want to use IPv6? > > > I don't think Cygwin supports IPv6. > > That was my impression too and seems to be substantiated by the > following: > > http://win6.jp/Cygwin/index.html > > Jason > > -- > PGP/GPG Key:http://www.tishler.net/jason/pubkey.ascor key servers > Fingerprint: 7A73 1405 7F2B E669 C19D 8784 1AFD E4CC ECF4 8EF6 Got it! Thank you very much, Jason, both Michael. I've chosen to be a Linuxer not only to solve this. :) Ming From peccatte at club-internet.fr Wed Jun 20 14:37:06 2007 From: peccatte at club-internet.fr (Patrick Peccatte) Date: Wed, 20 Jun 2007 20:37:06 +0200 Subject: pictures database project ? Message-ID: <4679736d$0$21143$7a628cd7@news.club-internet.fr> Hi, Is anybody knows any pictures database project written in Python ? Search engine and true database needed (preferably MySQL) I am looking for something similar to "Gallery" (written in PHP), see http://gallery.menalto.com/ -- Patrick Peccatte www.softexperience.com From steve at holdenweb.com Thu Jun 28 22:17:54 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 28 Jun 2007 22:17:54 -0400 Subject: Python's "only one way to do it" philosophy isn't good? In-Reply-To: References: <1182750077.570603.160240@q69g2000hsb.googlegroups.com> <7xir9cbm0g.fsf@ruckus.brouhaha.com> <7xejjzmk7u.fsf@ruckus.brouhaha.com> <7xy7i7xjl5.fsf@ruckus.brouhaha.com> <5N0C7KBirhgGFwUp@woodrowhorsfall.plus.com> Message-ID: Douglas Alan wrote: > Steve Holden writes: > >> Douglas Woodrow wrote: > >>> On Wed, 27 Jun 2007 01:45:44, Douglas Alan wrote > >>>> A chaque son gout > >>> I apologise for this irrelevant interruption to the conversation, >>> but this isn't the first time you've written that. The word >>> "chaque" is not a pronoun. > >>> http://grammaire.reverso.net/index_alpha/Fiches/Fiche220.htm > >> Right, he probably means "Chaqu'un ? son gout" (roughly, each to his >> own taste). > > Actually, it's "chacun". And the "?" may precede the "chacun". > > |>oug http://everything2.com/?node_id=388997 is clearly not authoritative, as the "literal translation" about which it speaks is far from literal (it mistakes the preposition "?" (to) for "a", the present tense of the verb to have. I suppose the literal translation is "Each one to his own taste". It does offer some support to my theory, however. So I'll quote the damned thing anyway. "chacun" is an elision of the two words "Chaque" (each) and "un" (one), and use of those two words is at least equally correct, though where it stands in modern usage I must confess I have no idea. The word order you suggest would be less likely to be used by a peasant than a lawyer. Being a peasant, I naturally used the other wording. IANA linguist-ical-ly y'rs - steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From nguyenhuuthanh at gmail.com Sat Jun 23 03:01:26 2007 From: nguyenhuuthanh at gmail.com (Genie T) Date: Sat, 23 Jun 2007 07:01:26 -0000 Subject: newbie question about unicode In-Reply-To: References: <1182571819.128093.18980@i13g2000prf.googlegroups.com> Message-ID: <1182582086.551618.228370@i13g2000prf.googlegroups.com> On Jun 23, 12:04 pm, "Carsten Haese" wrote: > On Sat, 23 Jun 2007 04:10:19 -0000, Genie T wrote > > > Hi, > > > can anybody tell me whether these two expressions have the same > > meanings? > > > s = u'' > > s1 = s.encode('utf-8') > > > AND > > > s1 = unicode(s,'utf-8') > > Considering that one works and the other doesn't, no, they don't have the same > meaning. > > The unicode() function decodes a given byte string into a unicode object, but > you're giving it a unicode object. What are you actually trying to achieve? > > If you're just trying to get a handle on the topic, I recommend you readhttp://www.amk.ca/python/howto/unicode > > HTH, > > -- > Carsten Haesehttp://informixdb.sourceforge.net thanks for the link, i'm trying to understand more about this unicode handling :) From joe at incomps.com Wed Jun 6 20:02:48 2007 From: joe at incomps.com (Joe) Date: Wed, 6 Jun 2007 18:02:48 -0600 Subject: MySQL InterfaceError In-Reply-To: <163f0ce20706061650k5708926ck449c53bf0bb39a81@mail.gmail.com> References: <001e01c7a6f3$e687ed40$0f01a8c0@desktop9> <002901c7a6f4$f55e56a0$0f01a8c0@desktop9> <008e01c7a7a5$ddaf8ae0$0f01a8c0@desktop9> <163f0ce20706061650k5708926ck449c53bf0bb39a81@mail.gmail.com> Message-ID: <016a01c7a897$2fbd4650$0f01a8c0@desktop9> > Try passing the cursor and not the connection - Unfortunately this provided the same InterfaceError. It was one of the first options we had tried in correcting the situation. Is there any way to check on the status of a database connection (like an isOpen() method)? It appeared as though the connection (and cursor) would sporadically close upon passing between modules. Thanks! Jough From gregpinero at gmail.com Mon Jun 25 10:48:30 2007 From: gregpinero at gmail.com (gregpinero at gmail.com) Date: Mon, 25 Jun 2007 14:48:30 -0000 Subject: Chroot Jail Not Secure for Sandboxing Python? In-Reply-To: <467f55f7$0$20850$9b622d9e@news.freenet.de> References: <1182748892.916068.146780@p77g2000hsh.googlegroups.com> <467f55f7$0$20850$9b622d9e@news.freenet.de> Message-ID: <1182782910.811850.284350@u2g2000hsc.googlegroups.com> On Jun 25, 1:43 am, "Martin v. L?wis" wrote: > gregpin... at gmail.com schrieb: > > > This wiki page suggests using a chroot jail to sandbox Python, but > > wouldn't running something like this in your sandboxed Python instance > > still break you out of the chroot jail: > > > os.execle ('/usr/bin/python','-c','import os; os.execlp("/bin/sh")', > > {}) > > Depending on how the chroot jail is set up, this command might not > work - in the jail, /bin/sh might not exist. I followed up with my ISP. Here's the answer I got: The os.exec call prepends the chroot directory to the absolute path, but does NOT provide chroot for the child process. However, as long as the environment is maintained, which contains an LD_PRELOAD, the "chroot" will also be maintained. If LD_PRELOAD is removed or ignored, then the chroot is ineffective. Another way of saying it is that every process is responsible for providing and maintaining the chroot through the LD_PRELOAD variable. Those processes only maintain the chroot if that variable remains set. The only solution that would bypass this problem altogether would be a statically linked python. (is that possible?) It would have to be statically linked to a custom-modified glibc to provide the virtual chroot environment. -Greg From carsten at uniqsys.com Sun Jun 17 14:15:49 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Sun, 17 Jun 2007 14:15:49 -0400 Subject: sqlite3 bug?? In-Reply-To: <1182091411.108272.286280@o61g2000hsh.googlegroups.com> References: <46752230$0$31685$db0fefd9@news.zen.co.uk> <46753426$0$30325$fa0fcedb@news.zen.co.uk> <1182091411.108272.286280@o61g2000hsh.googlegroups.com> Message-ID: <1182104149.3162.11.camel@localhost.localdomain> On Sun, 2007-06-17 at 07:43 -0700, 7stud wrote: > Please report the whole docs as a bug. I imagine the author appreciates constructive criticism. This is not constructive criticism. In other words: Pointing out specific shortcomings and ways to correct them, such as what the OP is doing, is helpful. Calling the entire docs a bug is not helpful. -- Carsten Haese http://informixdb.sourceforge.net From jackie_python at yahoo.ca Fri Jun 15 09:39:30 2007 From: jackie_python at yahoo.ca (Jackie Wang) Date: Fri, 15 Jun 2007 09:39:30 -0400 (EDT) Subject: Output of html parsing Message-ID: <2959.61301.qm@web57503.mail.re1.yahoo.com> Hi, all, I want to get the information of the professors (name,title) from the following link: "http://www.economics.utoronto.ca/index.php/index/person/faculty/" Ideally, I'd like to have a output file where each line is one Prof, including his name and title. In practice, I use the CSV module. The following is my program: --------------- Program ---------------------------------------------------- import urllib,re,csv url = "http://www.economics.utoronto.ca/index.php/index/person/faculty/" sock = urllib.urlopen(url) htmlSource = sock.read() sock.close() namePattern = re.compile(r'class="name">(.*)') titlePattern = re.compile(r', (.*)\s*') name = namePattern.findall(htmlSource) title_temp = titlePattern.findall(htmlSource) title =[] for item in title_temp: item_new=" ".join(item.split()) #Suppress the spaces between 'title' and title.extend([item_new]) output =[] for i in range(len(name)): output.insert(i,[name[i],title[i]]) #Generate a list of [name, title] writer = csv.writer(open("professor.csv", "wb")) writer.writerows(output) #output CSV file -------------- End of Program ---------------------------------------------- My questions are: 1.The code above assume that each Prof has a tilte. If any one of them does not, the name and title will be mismatched. How to program to allow that title can be empty? 2.Is there any easier way to get the data I want other than using list? 3.Should I close the opened csv file("professor.csv")? How to close it? Thanks! Jackie --------------------------------- All new Yahoo! Mail - --------------------------------- Get a sneak peak at messages with a handy reading pane. -------------- next part -------------- An HTML attachment was scrubbed... URL: From steven at REMOVE.THIS.cybersource.com.au Fri Jun 22 02:30:46 2007 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 22 Jun 2007 06:30:46 GMT Subject: import mysteries References: Message-ID: On Thu, 21 Jun 2007 16:03:42 -0400, David Abrahams wrote: > I'm pretty comfortable with Python, but recently I'm constantly finding > mysterious issues with import. For example, looking at > > http://genshi.edgewall.org/browser/trunk/genshi/filters/transform.py > > the examples use the symbol 'HTML' but it's not defined locally, it's > not explicitly imported, and there's no import *. Yet doctest will test > this module and it passes with flying colors. It turns out HTML is > defined in genshi.input. How do I know that? I grepped for it. How > does it become available to this module? There are ways to bypass the import system. The most obvious would be to write directly to globals. >>> spanish_inquisition Traceback (most recent call last): File "", line 1, in ? NameError: name 'spanish_inquisition' is not defined >>> globals()['spanish_inquisition'] = "NOBODY expects the Spanish Inquisition!!!" >>> spanish_inquisition 'NOBODY expects the Spanish Inquisition!!!' > Another example: I was recently working on some code that did an import > from inside a class method. That import was failing. I moved the > import to the top of the file (at module scope) and it succeeded. I'm > fairly sure that nobody was monkeying around with sys.path in that case. > Can anyone think of a likely explanation? If it was a "from MODULE import *" then it will not work if it is nested in a function or class. That's by design. -- Steven. From jjl at pobox.com Thu Jun 21 18:53:31 2007 From: jjl at pobox.com (John J. Lee) Date: Thu, 21 Jun 2007 22:53:31 GMT Subject: Logger vs. Handler log levels References: <467ae7fc$0$63185$a726171b@news.hal-pc.org> Message-ID: <87k5twnclw.fsf@pobox.com> steveg at moregruel.net (Steve Greenland) writes: > Apparently I don't understand logging levels. The code: > > import logging, logging.handlers > > > logging.basicConfig(level=logging.WARNING) > > newlog = logging.handlers.TimedRotatingFileHandler( > filename='/home/steveg/logtest.log', > when="midnight") > newlog.setLevel(logging.INFO) > > logging.getLogger().addHandler(newlog) > > logging.info("Message from logtest") > logging.debug("Debug message from logtest") > > doesn't print on the console (as expected), but also doesn't add the > first message to the file. Changing the basicConfig() call to set the > level to 'level.DEBUG' shows both messages on the console, and only the > first in the file, which is what I did expect. Not sure why you'd expect to see console output regardless of the logger / handler issue -- INFO and DEBUG are lower in priority than WARNING, and you've set the (logger) level to WARNING with the logging.basicConfig() call (indicating you're only interested in things at least that serious, not mere INFOrmational messages). > I suspect my confusion is the distinction between "handler" and > "logger". It appears that the logger won't pass any messages lower than > its level to any of its handlers. If I read the docs, what I need is to > do is have the root logger left at NOTSET, but then there doesn't seem > to be any way to set the level on the default stream handler. Yup. > Have I diagnosed the problem correctly? Is the only (or at least, > correct) solution to ignore the default handler and create my own > console and file handlers, setting levels as desired? Yes, I think so. John From twisted0n3 at gmail.com Tue Jun 26 20:07:04 2007 From: twisted0n3 at gmail.com (Twisted) Date: Wed, 27 Jun 2007 00:07:04 -0000 Subject: The Modernization of Emacs: terminology buffer and keybinding In-Reply-To: References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182272495.990807.99110@a26g2000pre.googlegroups.com> <87tzt3ihev.fsf@kobe.laptop> <1182370216.961241.6960@n60g2000hse.googlegroups.com> <85zm2ufjpb.fsf@lola.goethe.zz> <1182372592.803332.288260@u2g2000hsc.googlegroups.com> <1182373919.262388.100740@c77g2000hse.googlegroups.com> <85r6o6fhkb.fsf@lola.goethe.zz> <1182375045.626510.188170@m36g2000hse.googlegroups.com> <1182546050.465987.115740@q19g2000prn.googlegroups.com> <871wg3k8c8.fsf@thalassa.lan.informatimago.com> <1182546979.295368.146110@q19g2000prn.googlegroups.com> <87wsxviqol.fsf@thalassa.lan.informatimago.com> <1182552172.406571.116390@i38g2000prf.googlegroups.com> Message-ID: <1182902824.736206.37010@m36g2000hse.googlegroups.com> On Jun 26, 10:52 am, Bjorn Borud wrote: > [Robert Uhl ] > | > | Agreed. Stallman got sidetracked by Scheme, which IMHO was a > | dead-end. > > too many people buying SICP and believing what they heard about it > being an important book. I too spent some time exploring Scheme, or > should I say, wasted some time, years ago, and nothing came of it > other than a profound irritation. these people seemed to be > completely disconnected from reality. > > Scheme, and thus Guile, might have been a viable path if these people > had only been practical instead of stubbornly insisting on being odd. Some people might say the same thing about emacs. A lot of unix tools even. "Stubbornly insisting on being odd" appears to be a particularly prevalent character flaw among the geeknoscenti. From no_spam at no_spam.com Thu Jun 28 20:05:02 2007 From: no_spam at no_spam.com (James Alan Farrell) Date: Thu, 28 Jun 2007 20:05:02 -0400 Subject: Looking for an interpreter that does not request internet access References: Message-ID: On Mon, 25 Jun 2007 20:41:59 -0500, Robert Kern wrote: >James Alan Farrell wrote: >> Hello, >> I recently installed new anti-virus software and was surprised the >> next time I brought up IDLE, that it was accessing the internet. >> >> I dislike software accessing the internet without telling me about it, >> especially because of my slow dial up connection (there is no option >> where I live), but also because I feel it unsafe. > >It is not accessing the internet. It is opening up a local socket connection to >communicate with a separate (but still local!) process for the interactive >interpreter. > >> Can anyone recommend an interpreter that does not access the internet >> when it starts (or when it is running, unless I specifically write a >> program that causes it to do so, so as a browser)? > >The regular interpreter works fine. At the risk of sounding clueless, what is "the regular interpreter"? I've now read several python books, and they all recommend IDLE. I've not yet tried unplugging the cable -- have other fish to fry at the moment, but will try it. From borud-news at borud.no Tue Jun 26 11:02:02 2007 From: borud-news at borud.no (Bjorn Borud) Date: 26 Jun 2007 17:02:02 +0200 Subject: The Modernization of Emacs: terminology buffer and keybinding References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182272495.990807.99110@a26g2000pre.googlegroups.com> <87tzt3ihev.fsf@kobe.laptop> <1182370216.961241.6960@n60g2000hse.googlegroups.com> <85zm2ufjpb.fsf@lola.goethe.zz> <1182372592.803332.288260@u2g2000hsc.googlegroups.com> <1182373919.262388.100740@c77g2000hse.googlegroups.com> <85r6o6fhkb.fsf@lola.goethe.zz> <1182375045.626510.188170@m36g2000hse.googlegroups.com> <85myyufgwj.fsf@lola.goethe.zz> <1182375528.985142.293900@q69g2000hsb.googlegroups.com> <1182545268.055596.228700@i38g2000prf.googlegroups.com> <1182661040.286559.150880@q75g2000hsh.googlegroups.com> Message-ID: [Twisted ] | On Jun 23, 2:04 am, Robert Uhl wrote: | > Of course, emacs doesn't take years of mastery. It takes 30, 40 | > minutes. | | I gave it twice that, and it failed to grow on me in that amount of | time. then it just wasn't meant to be. stick to Notepad. | If I haven't, it must be the case that finding this tutorial (or even | discovering that it exists) was nontrivial, or it wasn't built into | emacs, one or the other. when Emacs on my machine starts it says the following: Welcome to GNU Emacs, one component of a Linux-based GNU system. Get help C-h (Hold down CTRL and press h) Undo changes C-x u Exit Emacs C-x C-c Get a tutorial C-h t Use Info to read docs C-h i Ordering manuals C-h RET Activate menubar F10 or ESC ` or M-` (`C-' means use the CTRL key. `M-' means use the Meta (or Alt) key. If you have no Meta key, you may instead type ESC followed by the character.) if you haven't found the tutorial, you haven't really tried very hard. -Bj?rn From james.b.looney at lmco.com Wed Jun 20 11:28:44 2007 From: james.b.looney at lmco.com (Looney, James B) Date: Wed, 20 Jun 2007 09:28:44 -0600 Subject: DFW Pythoneers Meeting THIS Saturday In-Reply-To: <6a2ccd190706200535m2aff7a50r411bbf3cbeaaae25@mail.gmail.com> References: <1182325553.232470.205970@q75g2000hsh.googlegroups.com> <1182337167.504241.131530@m36g2000hse.googlegroups.com> <6a2ccd190706200535m2aff7a50r411bbf3cbeaaae25@mail.gmail.com> Message-ID: Short answer: DFW = Dallas-Fort Worth Longer answer: I'm not pointing fingers or making opinions, I just wanted to point out that after reading Jeff's original email (in its entirity), I found: Jeff wrote: > at the usual location of Nerdbooks.com bookstore in Richardson. For So, after looking at Nerdbooks.com, they're in Richardson, TX. http://maps.google.com/maps?f=q&hl=en&q=1681+Firman+Drive,+richardson,+t x&sll=37.0625,-95.677071&sspn=31.371289,59.765625&ie=UTF8&ll=32.876127,- 96.792297&spn=0.259504,0.466919&z=11&om=1 > By the way, I've been contacted by a developer at the Travelocity Dallas > office, who is looking for local Python developers with experience in Django > or Genshi. If you're interested, let me know and I can put you in touch. Otherwise, after reading to this point in his email (and not knowing what DFW was), I'd guess that they're near Dallas. > -----Original Message----- > Subject: Re: DFW Pythoneers Meeting THIS Saturday > > > Precisely what? You complained that the OP didn't provide > the location > > of the event, which he did. > > Well, where is DFW? > -- > From gagsl-py2 at yahoo.com.ar Thu Jun 7 14:44:10 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 07 Jun 2007 15:44:10 -0300 Subject: recursion error using setattr and getattr References: <676224240706070423s8dcf73foe45f56552ab7e1dc@mail.gmail.com> Message-ID: En Thu, 07 Jun 2007 08:23:48 -0300, Nathan Harmston escribi?: > I m trying to implement an object which contains lazy" variables. My > idea is to alter the getattr and the setattr methods. However I keep > on getting a recursion error. Instead of setattr/getattr, use a property, and you'll get much cleaner code. -- Gabriel Genellina From horpner at yahoo.com Wed Jun 13 14:22:54 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Wed, 13 Jun 2007 18:22:54 GMT Subject: Python's "only one way to do it" philosophy isn't good? References: <1181368143.874341.273140@r19g2000prf.googlegroups.com> <7xy7irxjom.fsf@ruckus.brouhaha.com> <466f0c2c$0$4157$ba624c82@nntp02.dk.telia.net> <46702229$0$4158$ba624c82@nntp02.dk.telia.net> Message-ID: On 2007-06-13, Anders J. Munch <2007 at jmunch.dk> wrote: > General tail-call optimisation is of course completely > out-of-bounds for Python, because it ruins tracebacks. Unlike > tail recursion, which could use recursion counters. Is it really ruined? To use a similar example: def foo(x): bar(x+1) def bar(x): if x > 10: raise ValueError else: foo(x+2) Today, when I call foo(4), I get something like: C:\WINNT\system32\cmd.exe /c python temp.py Traceback (most recent call last): File "temp.py", line 529, in foo(4) File "temp.py", line 521, in foo bar(x+1) File "temp.py", line 527, in bar foo(x+2) File "temp.py", line 521, in foo bar(x+1) File "temp.py", line 527, in bar foo(x+2) File "temp.py", line 521, in foo bar(x+1) File "temp.py", line 525, in bar raise ValueError ValueError shell returned 1 With tail-call optimization you'd get something like: C:\WINNT\system32\cmd.exe /c python temp.py Traceback (most recent call last): File "temp.py", line 529, in foo(4) File "temp.py", line 525, in bar raise ValueError ValueError shell returned 1 What makes the latter harder to work with? -- Neil Cerutti From jensthiede at gmail.com Fri Jun 15 23:24:08 2007 From: jensthiede at gmail.com (Jens Thiede) Date: Fri, 15 Jun 2007 20:24:08 -0700 Subject: Custom wxPython Widget Message-ID: <1181964248.743455.168290@n60g2000hse.googlegroups.com> What is the best source code to read? Any tips; suggestions? Thanks in advance Jens Thiede From gagsl-py2 at yahoo.com.ar Tue Jun 26 21:19:37 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 26 Jun 2007 22:19:37 -0300 Subject: Unbound Local error --??? References: Message-ID: En Tue, 26 Jun 2007 21:48:50 -0300, hari sirigibathina escribi?: > -Calling a method say aMethod() from another method where i mistakenly > initialised a variable with name same as the called method like aMethod = > 'string'. When i run this py script triggered "Unbound Local error". > can any one explain me whats going here ? curios to learn from my > mistake > :) A simple example: >>> def f(): ... x = a + 1 ... a = 3 ... >>> f() Traceback (most recent call last): File "", line 1, in ? File "", line 2, in f UnboundLocalError: local variable 'a' referenced before assignment That means: 1) Python knows that variable "a" is local (because you assign 3 to it later) 2) But you have not assigned anything to it yet. >>> def g(): ... x = a + 1 ... >>> g() Traceback (most recent call last): File "", line 1, in ? File "", line 2, in g NameError: global name 'a' is not defined This time, "a" is not local, and not found in the global namespace either. The message tells you that it was looking for a global variable, and could not find it. -- Gabriel Genellina From steve at REMOVE.THIS.cybersource.com.au Wed Jun 13 21:03:50 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Thu, 14 Jun 2007 11:03:50 +1000 Subject: one-time initialization of class members References: <1181772494.803499.266690@o11g2000prd.googlegroups.com> <1181778902.547599.147960@q19g2000prn.googlegroups.com> Message-ID: On Wed, 13 Jun 2007 23:55:02 +0000, James Turk wrote: > On Jun 13, 6:54 pm, Steven Bethard wrote: >> James Turk wrote: >> > Hi, >> >> > I have a situation where I have some class members that should only be >> > done once. Essentially my problem looks like this: >> >> > class Base(object): >> > dataset = None >> >> > def __init__(self, param): >> > if type(self).dataset is None: >> > # code to load dataset based on param, expensive >> >> > class ChildClass1(Base): >> > def __init__(self): >> > Base.__init__(self, data_params) >> >> > class AnotherChildClass(Base): >> > def __init__(self): >> > Base.__init__(self, other_data_params) >> >> > This seems to work, initialization is only done at the first creation >> > of either class. I was just wondering if this is the 'pythonic' way >> > to do this as my solution does feel a bit hackish. >> >> What should happen with code like:: >> >> ChildClass1('foo') >> ChildClass1('bar') >> >> The 'param' is different, but 'dataset' should only get set the first time? >> >> STeVe > > ChildClass doesn't take the parameter in it's constructor, it supplies > it for the BaseClass. Every ChildClass of the same type should use > the same dataset. Then each type of ChildClass should be a sub-class, and provide it's own dataset: class BaseClass: dataset = None # blah blah blah... class ChildClass1(BaseClass): dataset = SomethingUseful class ChildClass2(BaseClass): dataset = SomethingElse -- Steven. From see_website at mindprod.com.invalid Mon Jun 25 07:17:27 2007 From: see_website at mindprod.com.invalid (Roedy Green) Date: Mon, 25 Jun 2007 11:17:27 GMT Subject: Portable general timestamp format, not 2038-limited References: <1182544384.709759.235300@o11g2000prd.googlegroups.com> Message-ID: On Sun, 24 Jun 2007 18:14:08 -0700, rem642b at yahoo.com (Robert Maas, see http://tinyurl.com/uh3t) wrote, quoted or indirectly quoted someone who said : >- Stick to astronomical time, which is absolutely consistent but > which drifts from legal time? depends what you are measuring. IF you are doing astronomy, your advice would apply. If you are doing payrolls, you want effectively to pretend the leap seconds never happened, just as Java does. -- Roedy Green Canadian Mind Products The Java Glossary http://mindprod.com From mkb at incubus.de Thu Jun 21 16:41:34 2007 From: mkb at incubus.de (Matthias Buelow) Date: Thu, 21 Jun 2007 22:41:34 +0200 Subject: The Modernization of Emacs: terminology buffer and keybinding In-Reply-To: <1182456618.763414.219080@g4g2000hsf.googlegroups.com> References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182272495.990807.99110@a26g2000pre.googlegroups.com> <87tzt3ihev.fsf@kobe.laptop> <1182370216.961241.6960@n60g2000hse.googlegroups.com> <85zm2ufjpb.fsf@lola.goethe.zz> <1182372592.803332.288260@u2g2000hsc.googlegroups.com> <1182373919.262388.100740@c77g2000hse.googlegroups.com> <85r6o6fhkb.fsf@lola.goethe.zz> <1182375045.626510.188170@m36g2000hse.googlegroups.com> <1182453375.531950.141460@m36g2000hse.googlegroups.com> <1182456618.763414.219080@g4g2000hsf.googlegroups.com> Message-ID: <5e063mF35d3v6U1@mid.dfncis.de> Kaldrenon wrote: > I don't think anyone can make the argument that any (past or current) > graphics-based editor is as efficient when being used to its fullest > as a text-based editor. Actually, I think the argument can be made: ``We?ve done a cool $50 million of R & D on the Apple Human Interface. We discovered, among other things, two pertinent facts: * Test subjects consistently report that keyboarding is faster than mousing. * The stopwatch consistently proves mousing is faster than keyboarding.'' (from http://plan9.bell-labs.com/wiki/plan9/Mouse_vs._keyboard/index.html ) However, at least for me, heavy mousing is stressful to the wrist, so I prefer to keep my hands on the keyboard (even though I use a trackball, which greatly reduces the strain for me). I also think that while intuitive cursor positioning and text selection operations may be faster with a mouse, complex operations (like on the shell or complex editor commands) are impractical through a pure point+click interface. From JoeSalmeri at hotmail.com Sat Jun 2 21:45:46 2007 From: JoeSalmeri at hotmail.com (Joe Salmeri) Date: Sat, 2 Jun 2007 21:45:46 -0400 Subject: Python 2.5.1 broken os.stat module References: <466140A6.1090100@v.loewis.de> Message-ID: <-aOdnbFdroD_gP_bnZ2dnUVZ_uKknZ2d@comcast.com> > It's not clear whether it's an error, however, localtime() does > something different from what dir does. Hi Martin, First off thank you for spending your time to investigate this bug with me. Thanks for pointing out the issue with Windows XP caching the access timestamps, I was not aware of that. The reality is that I am most interested in the last write time because that is the timestamp that Windows displays when you issue a dir command (WITHOUT a /t option), what Windows Explorer displays in detail view, and what every other program I have found so far references. I re-reviewed all differences found by the program I posted for the Python\lib directory date comparison and if you eliminate access times all differences for created and last write that were reported were a difference of 1 hour. Based on a bunch of testing that I did and some references listed below I believe that you are CORRECT, Python 2.5.1 is reporting the correct times and Windows is reporting the times incorrectly. The short explaination of this issue is that the timestamp shown when you do a dir on a file that is on an NTFS volume changes by an hour when DST starts and also when DST ends, even though the file has NOT been modified!!! Note that this only happens if you have the setting turned on to automatically adjust for DST (this is the default in Windows). Even though Python 2.5.1 is correct this presents a NEW problem because it differs from what XP SP 2 (wrongly) reports. I am sure this will cause a lot of confusion for people as it already appears that others have stumbled on this difference. Here are some tests I did which show the problem that Windows has. Setup Test Environment Virtual machine XP SP2 Set TimeZone to GMT with automatically adjust for DST turned on Set Date and Time to 01/02/2007 12:00:00 AM Create file with notepad named joe.txt This establishes our baseline: joe.txt last written 01/02/2007 12:00 AM GMT Check what Windows, Python 2.4.2 and Python 2.5.1 Report dir /tc 01/02/2007 12:00 AM 14 joe.txt dir /tw 01/02/2007 12:00 AM 14 joe.txt Python 2.4.2 Creation Time: 01/02/2007 00:00:04 Last Write Time: 01/02/2007 00:00:08 Python 2.5.1 Creation Time: 01/02/2007 00:00:04 Last Write Time: 01/02/2007 00:00:08 Great so far everybody is in agreement Change Environment Set TimeZone to GMT-5:00 Eastern Time (US & Canada) (where I am located) DST still set to automatically adjust No changes to date and time at this point With these changes joe.txt should now report 01/01/2007 07:00 PM since I am 5 hours behind GMT Check what Windows, Python 2.4.2 and Python 2.5.1 Report dir /tc 01/01/2007 07:00 PM 14 joe.txt dir /tw 01/01/2007 07:00 PM 14 joe.txt Python 2.4.2 Creation Time: 01/01/2007 19:00:04 Last Write Time: 01/01/2007 19:00:08 Python 2.5.1 Creation Time: 01/01/2007 19:00:04 Last Write Time: 01/01/2007 19:00:08 Great so far everyone is still in agreement Change Environment Leave TimeZone set to GMT-5:00 Eastern Time (US & Canada) (where I am located) DST still set to automatically adjust Change date to todays date 06/02/2007 and time 02:00:00 PM This test simulates my machine moving in time forward from 01/1/2007 to 06/02/2007 with no changes being made on the computer. Imagine I turned it off on 01/02/2007 and went on a long vacation and just came home on 06/02/2007 and turned it back on. Check what Windows, Python 2.4.2 and Python 2.5.1 Report dir /tc 01/01/2007 08:00 PM 14 joe.txt dir /tw 01/01/2007 08:00 PM 14 joe.txt Python 2.4.2 Creation Time: 01/01/2007 20:00:04 Last Write Time: 01/01/2007 20:00:08 Python 2.5.1 Creation Time: 01/01/2007 19:00:04 Last Write Time: 01/01/2007 19:00:08 This is where the problem occurs. This file was originally created 01/02/2007 12:00 AM GMT which is the same locally as 01/01/2007 07:00 PM EST but now everything EXCEPT Python 2.51 is reporting that the file changed on 01/01/2007 08:00 PM EST Well that couldn't have happened since no changes were made (remember I was on vacation :-)). Everything was fine until our current date time enters DST. At that point the file now shows that it was last written an hour later. The last write timestamp for the file should not change or be affected because of the start/end of DST has occurred on my computer. To the end user it appears the file was modifed when in fact it was not. Python 2.5.1 is CORRECT Windows is WRONG (dir /t, Explorer) Python 2.4.2 is WRONG One Possible Work Around for the problem: Turn OFF the automatically adjust for DST setting NOTE: Turning this off causes issues with time sync. See details at the end. With it turned off the timestamps are all correct dir /tc 01/01/2007 07:00 PM 14 joe.txt dir /tw 01/01/2007 07:00 PM 14 joe.txt Python 2.4.2 Creation Time: 01/01/2007 19:00:04 Last Write Time: 01/01/2007 19:00:08 Python 2.5.1 Creation Time: 01/01/2007 19:00:04 Last Write Time: 01/01/2007 19:00:08 I was concered that since I had the automatically adjust DST setting turned on when I originally started with the time set to GMT 12:00 AM that it might have affected my results so I reran the tests. Setup Test Environment Virtual machine XP SP2 Set TimeZone to GMT WITHOUT automatically adjust for DST Set Date and Time to 01/02/2007 12:00:00 AM Create file with notepad named joe.txt This establishes our baseline: joe.txt last written 01/02/2007 12:00 AM Check what Windows, Python 2.4.2 and Python 2.5.1 Report dir /tc 01/02/2007 12:00 AM 16 joe.txt dir /tw 01/02/2007 12:00 AM 16 joe.txt Python 2.4.2 Creation Time: 01/02/2007 00:00:04 Last Write Time: 01/02/2007 00:00:09 Python 2.5.1 Creation Time: 01/02/2007 00:00:04 Last Write Time: 01/02/2007 00:00:09 Just like the first time everone is in agreement Change Environment Set TimeZone to GMT-5:00 Eastern Time (US & Canada) (where I am located) DST still NOT set to automatically adjust No changes to date and time at this point With these changes joe.txt should now report 01/01/2007 07:00 PM since I am 5 hours behind GMT Check what Windows, Python 2.4.2 and Python 2.5.1 Report dir /tc 01/01/2007 07:00 PM 16 joe.txt dir /tw 01/01/2007 07:00 PM 16 joe.txt Python 2.4.2 Creation Time: 01/01/2007 19:00:04 Last Write Time: 01/01/2007 19:00:09 Python 2.5.1 Creation Time: 01/01/2007 19:00:04 Last Write Time: 01/01/2007 19:00:09 Just like the first time everyone still in agreement Change Environment Leave TimeZone set to GMT-5:00 Eastern Time (US & Canada) (where I am located) DST still NOT set to automatically adjust Change date to todays date 06/02/2007 and time 02:00:00 PM Check what Windows, Python 2.4.2 and Python 2.5.1 Report dir /tc 01/01/2007 07:00 PM 16 joe.txt dir /tw 01/01/2007 07:00 PM 16 joe.txt Python 2.4.2 Creation Time: 01/01/2007 19:00:04 Last Write Time: 01/01/2007 19:00:09 Python 2.5.1 Creation Time: 01/01/2007 19:00:04 Last Write Time: 01/01/2007 19:00:09 Everyone still in agreement. This confirms that the bug is in Windows when the automatically adjust for DST setting is turned on. Windows should NOT be using the DST setting to adjust the file times. It makes it look like the files were modified when in fact they have not. If you turn it on after the last test then you get the following results which again prove that Python 2.5.1 is correct and that Windows and Python 2.4.2 are wrong. dir /tc 01/01/2007 08:00 PM 16 joe.txt dir /tw 01/01/2007 08:00 PM 16 joe.txt Python 2.4.2 Creation Time: 01/01/2007 20:00:04 Last Write Time: 01/01/2007 20:00:09 Python 2.5.1 Creation Time: 01/01/2007 19:00:04 Last Write Time: 01/01/2007 19:00:09 The real issue now is that even though Python 2.5.1 is correct it is confusing to someone that is trying to compare their results to what Windows reports. If you turn of automatically adjust DST and run the program I provided to compare the dates between windows and python in the other email message against the Python\Lib directory then all create dates and all write dates between Python and Windows compare. Access dates do not match but you have already explained why that can occur (caching). As shown above, one way to fix this is to turn OFF the automatically adjust for DST setting in Windows. The problem with turning it OFF is that if you have automatic time sync turned ON when the time sync occurs and automatically adjust for DST is turned OFF and it is DST your time will be an hour off after the sync :-(. Also any computers that are syncing their time with this computer that have automatically adjust for DST turned ON will have their sync'd times one hour off since this computer had automatically adjust for DST turned OFF. The following link goes into even greater detail as to the source of the problem in Windows: http://search.cpan.org/~shay/Win32-UTCFileTime-1.45/lib/Win32/UTCFileTime.pm Based on the above article it does not seem like Microsoft will be fixing this which leaves us stuck because Python and Windows are not reporting the same values when DST starts/ends and you have automatically adjust for DST turned ON. Having this difference between Python and Windows makes it difficult to write code that depends on those values being in sync. It makes me wonder if there should be an option in localtime to "fudge" the dates so that they match what Windows reports.... Thanks to all that assisted in investigating this. From no at spam.com Wed Jun 13 04:04:29 2007 From: no at spam.com (Chris) Date: Wed, 13 Jun 2007 10:04:29 +0200 Subject: userinteraction for a webspider In-Reply-To: References: <1492f$466be2e9$58422645$19939@news.usenext.de> Message-ID: <202f3$466fa4ff$58420195$12196@news.usenext.de> James Stroud schrieb: > > There are sweatshops in developing countries that provide this service. > > James But since this is for fun/convenience for me only Id rather not make anyone break asweat... Great advice, helpful too From Stebanoid at gmail.com Sun Jun 3 11:55:41 2007 From: Stebanoid at gmail.com (Stebanoid at gmail.com) Date: Sun, 03 Jun 2007 08:55:41 -0700 Subject: c[:]() In-Reply-To: References: <1180504190.055427.173610@h2g2000hsg.googlegroups.com> <1180504773.374529.161740@q66g2000hsg.googlegroups.com> <1180878080.630213.258230@q75g2000hsh.googlegroups.com> Message-ID: <1180886141.096451.68060@k79g2000hse.googlegroups.com> On 3 , 18:44, Marc 'BlackJack' Rintsch wrote: > In <1180878080.630213.258... at q75g2000hsh.googlegroups.com>, > > >bla-bla-bla > > it is easy to read and understandable. > > And has the same issue as a list comprehension if all you want is the side > effect of the calls: a useless temporary list full of `None`\s is build. > > Ciao, > Marc 'BlackJack' Rintsch functoins can return a values, and you get it. I don't think that it is bad side effect. When you write simple >>> def a(): print "From Russia with love." >>> a() you have side effect too - returning "None". From evan at yelp.com Thu Jun 21 01:33:06 2007 From: evan at yelp.com (Evan Klitzke) Date: Wed, 20 Jun 2007 22:33:06 -0700 Subject: PEP 3107 and stronger typing (note: probably a newbie question) In-Reply-To: <163f0ce20706202200y761bda4fpec35498f1d84f179@mail.gmail.com> References: <1182369568.941307.316260@p77g2000hsh.googlegroups.com> <5dtmtnF36t3pfU1@mid.uni-berlin.de> <163f0ce20706202200y761bda4fpec35498f1d84f179@mail.gmail.com> Message-ID: On 6/20/07, kaens wrote: > On 6/20/07, Diez B. Roggisch wrote: > > > That is exactly the problem - there is no "some more" static typing. > > There is static typing - or not. You can't have it "just a bit". > > Couldn't a language be made so that if you declared a variable like, say: > > string foo = "I'm a string" > > it would be a string, and always a string, and if you declared a variable like > > foo = "i'm a dynamic variable" > > it would be considered dynamic? > > This doesn't seem like it would be too hard to add in to a language > that already had dynamic typing (But then again, I am inexperienced - > although interested in - language design). > > It seems to me like this could be really useful, but I'm not aware of > any language implementing something like this. I think the main issue is that while you _could_ do that, the fact that the language allows dynamic variables essentially precludes the possibility of doing static checks for type issues (see Terry's post for a better explanation of the issue). So you are by and large not going to catch type errors until runtime anyway, and this is a feature that Python already provides (if you try to mix different types in an incompatible way you'll get a TypeError). I think that raising an exception is the correct way to deal with type errors in this context. So it's not that this issue is useless, but rather that it isn't useful enough to warrant someone implementing it. If there was a good implementation, and people really liked it and saw how great it was, I don't think there's any fundamental opposition to its inclusion in the language. But this hasn't happened yet. -- Evan Klitzke From per9000 at gmail.com Tue Jun 5 03:14:14 2007 From: per9000 at gmail.com (per9000) Date: Tue, 05 Jun 2007 00:14:14 -0700 Subject: magic names in python In-Reply-To: References: <1180939436.862957.127810@p77g2000hsh.googlegroups.com> <1180943167.241208.37080@q75g2000hsh.googlegroups.com> Message-ID: <1181027654.070887.10910@q66g2000hsg.googlegroups.com> On 4 Juni, 10:19, Marc 'BlackJack' Rintsch wrote: > > [...] > > Now I'm a little confused. What does this have to do with magic names? I > thought you are talking about names that start and end with two > underscores (`__magic__`)!? Indeed I am talking about two things at once - you are right. Since I have problems with both of these "features" I perhaps do not separate them very well. I received lots of nice links to __special__ names in python, thanks. When it comes to 'dive into python' this is like the fifth time I heard of it so I really have to get it soon. Still, I have problems with "magic" functions, similar to magic numbers: http://en.wikipedia.org/wiki/Magic_number_%28programming%29 f.x. calling all member-functions of a class to close files as illustrated in a previous post, or PyUnits magic "test*"-names: http://pyunit.sourceforge.net/pyunit.html#RUNNING_CMD (there are options here but I fell into the bear-trap of course) Guessing from your replies this is a general problem/issue/feature and as I understand it there is no special pythonic recommendations in this area, right? Also, I guess that use of magic numbers and magic should be documented and are thus discovered by RTFM'ing. Additional comments are welcome, or course. All your base are belong to us, Per -- Per Erik Strandberg home: www.pererikstrandberg.se work: www.incf.org also: www.spongswedencare.se From martin at see.sig.for.address Sun Jun 24 08:10:52 2007 From: martin at see.sig.for.address (Martin Gregorie) Date: Sun, 24 Jun 2007 13:10:52 +0100 Subject: The Modernization of Emacs: terminology buffer and keybinding In-Reply-To: <1182657564.912472.55570@g4g2000hsf.googlegroups.com> References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182272495.990807.99110@a26g2000pre.googlegroups.com> <87tzt3ihev.fsf@kobe.laptop> <1182370216.961241.6960@n60g2000hse.googlegroups.com> <85zm2ufjpb.fsf@lola.goethe.zz> <1182372592.803332.288260@u2g2000hsc.googlegroups.com> <1182373919.262388.100740@c77g2000hse.googlegroups.com> <85r6o6fhkb.fsf@lola.goethe.zz> <1182375045.626510.188170@m36g2000hse.googlegroups.com> <85myyufgwj.fsf@lola.goethe.zz> <1182375528.985142.293900@q69g2000hsb.googlegroups.com> <1182545268.055596.228700@i38g2000prf.googlegroups.com> <1182547318.325617.16370@o11g2000prd.googlegroups.com> <1182657564.912472.55570@g4g2000hsf.googlegroups.com> Message-ID: Twisted wrote: > On Jun 23, 10:36 am, Martin Gregorie > wrote: > > Actually, what I prefer in (2D and 3D) visual design apps is the > ability to snap to some kind of grid/existing vertices, and to zoom in > close. Then small imprecisions in mouse movement can be rendered > unimportant. > That might work for visual design apps, but it doesn't for CAD, where you may want to point to an arbitrary position with a (scaled) accuracy of microns. The fact remains that mechanical mice do jump when you click them, though optical mice are better in this respect. > The problem of course being the complete exclusion of type 1 users. > Totally untrue. They are the people that all the standard GUIs are designed for and some (e.g Mackintosh) are very fast to learn. The exclusion is down to the way that the purveyors of GUIs keep spreading bullshit about how any untrained person can use a computer and never mess it up or loose data. Thats not true and never can be: a computer is the most complex device the average person will own or use and is likely to retain that title for the foreseeable future. I grant you that type 2 users are rare, but I think flight simulators may fit this case when used for training. > One with a bog-standard UI but also a "console" or command prompt, > scripting language, and customizable bindings? > Not really. What's needed is a single interface that can be used by anybody from beginner to expert and that, in the case of an error, shows precisely where it got, what caused the action to fail to complete and that allows the user to continue from that point without having to undo/redo the bits that were successful. Its not easy, but it can be done. > ROM BASICs and QBasic (on any really ancient microcomputer, and old > pre-Windows PCs, respectively; the former came with printed manuals > and you could just run prepackaged software from disks very easily; > Hang on: you don't read manuals. You object to using tutorials and to buying books, so its a bit precious to claim this example. > * The word processor with the usual interface where I can define > logical styles, then change them in only one place and affect every > pre-existing occurrence retroactively. > Thats been in Word since DOS days and is part of OpenOffice. Its called a "style sheet". The only WPs I've used that didn't use them were Wordperfect, WordStar, DEC WPS+ and the Wang dedicated WP systems. All were horrid to varying degrees, with Wordperfect and Wordstar tying for worst. > * The word processor with the usual interface where I can also view an > underlying markup representation and hand-hack that, > You're thinking of Wordperfect and its 'Reveal Codes' function. That was the worst idea I've ever seen in a WP, matched only by the illogically arranged set of 12 function keys, each with 4 shifts. > and which likely has the capabilities of the first two as a direct > consequence of the implied architecture. > It didn't. 'Reveal codes' could only let you inspect the current document. Unfortunately it was essential to use it because some input sequences could completely mess up the formatting and the only way to recover was via 'Reveal codes'. The effect was similar to making a data entry clerk use a hex editor on a database to fix keyboarding errors. NOTE: I'm not talking about secretaries using WordPerfect. Those that used it hated it. I'm talking about the experience of IT professionals writing structured text, e.g. system specifications. > * The operating system where you can do powerful stuff with a command > line and a script or two, but can also get by without either. (Windows > fails the former. Linux fails the latter.) > Here you're talking about two different interfaces again. The nearest I've seen to good solutions at OS level were the CL interface provided by ICL's VME mainframes and IBM's AS/400 systems. The latter was particularly good, with a single unified text screen interface which provided help screens, menus and a command line. You could search for and find commands via a menu structure, and then use form filling to provide the arguments, with help available at any stage. If you were writing a script the entire menu and form filling system was available from within the text editor - but when you hit ENTER the completed command was written into your script instead of being executed. Both OS/400 and VME were very consistent in the way they assigned command names and argument keywords. In both OSen it was possible to think "if there's a command to do this it will be called BLAHBLAH", type the name, hit the command completion key and have the argument entry screen pop up ready to be filled in. BTW, in both OSen this capability applied to user-written scripts and programs as well as to the standard command set. Both could claim to be object oriented: the VME command language was derived from Algol-68, arguably the granddaddy of all OO programming languages. > * For that matter, the operating system whose GUI takes the concept > behind OLE to its logical conclusion, and lets the user separately > choose and configure their text editing, this-editing, that-editing, > whosit-viewing, > The AS/400 editor did exactly that. There was only one, but it swapped personality to match the task and was language-aware as well as application aware. It produced form-filling interfaces to help you write command scripts. If you were writing a program it gave language-specific prompts and could run syntax checks on each statement as it was entered. If you didn't want any of that, it would just quietly accept input like any other text editor. > The bog-standard alt, this, that sequences on Windows "come close"; > they do make the menus display, but otherwise they do exactly what you > want, and you can ignore the menus blinking around in your peripheral > vision. > No they don't: you can't easily string them together to act as a single command and the error diagnosis and reporting is remarkably poor. Same goes for Gnome, so I'm not particularly bashing Windows here. -- martin@ | Martin Gregorie gregorie. | Essex, UK org | From twisted0n3 at gmail.com Mon Jun 25 18:01:04 2007 From: twisted0n3 at gmail.com (Twisted) Date: Mon, 25 Jun 2007 22:01:04 -0000 Subject: The Modernization of Emacs: terminology buffer and keybinding In-Reply-To: References: <87tzt3ihev.fsf@kobe.laptop> <1182370216.961241.6960@n60g2000hse.googlegroups.com> <85zm2ufjpb.fsf@lola.goethe.zz> <1182372592.803332.288260@u2g2000hsc.googlegroups.com> <1182373919.262388.100740@c77g2000hse.googlegroups.com> <85r6o6fhkb.fsf@lola.goethe.zz> <1182375045.626510.188170@m36g2000hse.googlegroups.com> <85myyufgwj.fsf@lola.goethe.zz> <1182375528.985142.293900@q69g2000hsb.googlegroups.com> <1182545268.055596.228700@i38g2000prf.googlegroups.com> <1182547318.325617.16370@o11g2000prd.googlegroups.com> <1182657564.912472.55570@g4g2000hsf.googlegroups.com> <1182713541.449966.195970@o61g2000hsh.googlegroups.com> Message-ID: <1182808864.211161.155920@u2g2000hsc.googlegroups.com> On Jun 25, 8:40 am, Martin Gregorie wrote: > Twisted wrote: > > The manuals came with the computers, at no additional charge. It was a > > different time. This isn't going to be true of any separately- > > purchased book or user-made printout concerning emacs. Also, the > > manuals provided a basic introduction for the beginning user. A > > traditional-unix-tool providing anything resembling that would > > genuinely shock me. > > Oh, so manuals are OK and you'll read them if they are dead trees that > came in the same box as the software, but not if they're HOWTOs, online > documentation or O'Reilly books? I think I need to clarify. What I expect is that I can have the application and the documentation open side by side, a) without needing to use the application's own navigation methods to navigate to/ from or within the documentation given that that can create a catch-22, and b) without paying extra. If a printed manual comes with the thing, without paying extra, then it clearly qualifies as such documentation. If I have to print it myself it doesn't, because ink doesn't grow on trees. Paper does, but they still manage to charge money for that too. If I have to purchase the manual separately it likewise doesn't. So the options are: printed manual that ships with the software at no extra charge, or online documentation I can read "the normal way". Emacs in control of the console has neither. (Emacs relegated to a single terminal window on a graphical workstation may not have such a big problem.) Regardless, having to reach for the help every two minutes doesn't enamor me of an application unless there's a darn good reason for it, such as it's actually rocket science. 3D modeling I expect to be tricky at times. Text editing should be just-sit-down-crack-knuckles- and-do-it obviously. > > Oh, because the implementation (of "reveal codes" and of everything > > else) was awful, not because of any intrinsic flaw in the idea itself. > > If a word processor, which by definition is provides a WYSIWYG user > interface, can't produce perfectly formatted text by editing a > representation of the finished result then its a deeply flawed program > and not fit for purpose. First, I didn't claim the ideal WP was necessarily perfectly WYSIWYG. On the other hand, even so it might be that hand-hacking the underlying representation might in some cases be a faster way to achieve a particular goal than doing it "the WYSIWYG way". You'd still have a WYSIWYG preview available either way of course. > > Would you want to edit a Web page without being able to hand-hack the > > HTML? > > Of course not, but HTML isn't anything to do with WYSIWYG and any system > (Coldfusion, Front Page, HTML from Word) that pretends it is WYSIWG is > both useless and perpetrating a fraud. Your quiet change from discussing word processing to discussing WYSIWYG is interesting. Is that how you generally go about fighting your verbal battles, by quietly shifting the specific thing under debate to whatever would have made your opponent blatantly wrong IF they had been talking about that thing instead of what they really were? > > What happened to the guys that did all this stuff after it became > > obsolete? > > It isn't obsolete despite going back a looong way. The hardware and > software was originally developed as Future Series (intended S/360 > replacement), was canned in 1970 but resurfaced in the late 80s as > System/38. A second generation appeared as AS/400, was renamed to (I > think) Z-series and are now known as iSeries servers. Its good, reliable > kit and easy to work with if you don't mind programming in RPG. Programming in role-playing game? And I meant my roguelike-filesystem- interface suggestion at least partly in jest... Anyway, obsolete or merely obscure, it obviously failed to hit the big time since us ordinary joes are still mostly using various forms of Windoze and wishing for something more reliable and secure that didn't also have gratuitous user interface weirdnesses. > I know of no better "one size fits all" interface design than that > provided by the OS/400 operating system. Its still called that. Its a > pity the interface style hasn't been emulated by others. If it's so great, why hasn't it, and why hasn't OS/400 managed to escape from persistent obscurity? > It was standard with Win 3.1 and 3.11 and it was bloody useless. Most > people I know tried it once or twice before giving up and writing .BAT > files or putting up with RSI. The problem was that it recorded > keystrokes and mouse clicks. Even minor changes to the screen layout > made it fail and the macros couldn't be edited or parameterised nor made > to prompt for filenames, etc. In other words, the implementation was a dog. That doesn't refute the basic concept's validity. If it recorded mouse actions by noting the keyboard equivalents (e.g. recorded a file menu drop down and file open click as alt, f, o given that the application has the usual keybindings in the file menu), and provided ways for advanced users to edit them and such ... In response to the other postings of the last 24 hours or so I have just two things to say: 1. Regarding someone saying I had "no clue how to do things in Unix" when I noted that the inability to copy and paste graphics or other non-ascii data between applications caused awkwardness, I don't see any grounds there for an insulting response. If desktop environments do provide some mechanism suitable for generic clipboard actions (the basic X clipboard is clearly inadequate) then they do so unobviously, and probably all differently from one another. Being able to do serious work with graphics requires being able to move snippets of graphics around handily without all the mechanics of explicitly saving them all to various temporary files, and later remembering to delete the files. More generally, if a common Windows workflow isn't supported, then even if an alternative workflow is that is as effective and efficient it would take some getting used to. Interface-wise, the world has standardized on how Windoze (and the Mac) does things. Breaking such defacto standards makes software harder to use by the vast majority of likely new users. 2. Regarding these graphical derivatives (apparently plural) of emacs, has nobody considered that this means that Xah had already won before he'd even fired his shot? :P Someone obviously felt the need for a more usable emacs and delivered one. In that case it's a fait accompli. Criticisms leveled at original-emacs shouldn't bother users of the graphical versions regardless. The one complaint might be that both of us had out of date information and were fighting a war our side had already won years ago. :) Unless of course these are all klunky bolted-on GUIs of the sort all too common when porting unix software to Windows or the Mac or for use under X, which don't work quite right or are clearly poorly integrated with the application's internals...about which I currently have no information. And no, I'm not about to spend hours downloading half a gig of bloated who-knows-what just to find out, tyvm. :) From sean.farrow at seanfarrow.co.uk Fri Jun 8 09:48:52 2007 From: sean.farrow at seanfarrow.co.uk (Sean Farrow) Date: Fri, 8 Jun 2007 14:48:52 +0100 Subject: error when calling method of class Message-ID: Hi: I have defined a class in that class is a method defined as follows: def splitTime(n): seconds =float(n) I call the method in another procedure as follows: sefl.splitTime(200) the traceback states that splitTime takes one argument two given. why is this occuring? if I try calling it like: splitTime(200) I get a name resultion error saying that the global name splitTime is not defined. Any help apreciated. Sean. From faulkner891 at gmail.com Mon Jun 18 08:28:22 2007 From: faulkner891 at gmail.com (faulkner) Date: Mon, 18 Jun 2007 05:28:22 -0700 Subject: labeled break/continue In-Reply-To: References: Message-ID: <1182169702.019171.250880@p77g2000hsh.googlegroups.com> On Jun 18, 12:35 am, Matt Chisholm wrote: > Hi. I was wondering if there had ever been an official decision on > the idea of adding labeled break and continue functionality to Python. > > I've found a few places where the idea has come up, in the context of > named code blocks: > > http://groups.google.com/group/comp.lang.python/browse_thread/thread/... > > and in the context of discussing do/while loops and assignments in > conditionals: > > http://groups.google.com/group/comp.lang.python/browse_thread/thread/... > > Both of those discussions just kind of petered out or changed > direction without any conclusion. > > There's also this Python 2.6 which has a similar syntax (although > different semantics) to one of the syntaxes proposed in the first > discussion above: > > http://sourceforge.net/tracker/index.php?func=detail&aid=1714448&grou... > > I would be willing to help make a case and then write a PEP for > labeled break and continue, as long as the community or the BDFL > hasn't already decided against it. > > -matt > > P.S. My apologies about cross posting; python-ideas seems like a > better place to post this, but PEP 1 says to post to python-list. python-dev just mentioned that the BDFL vetoed it a while ago. they're writing a PEP just to document why it was vetoed. From carsten at uniqsys.com Sat Jun 16 21:50:19 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Sat, 16 Jun 2007 21:50:19 -0400 Subject: Function that returns a tuple In-Reply-To: <1182043826.790070.4420@u2g2000hsc.googlegroups.com> References: <1182043826.790070.4420@u2g2000hsc.googlegroups.com> Message-ID: <1182045019.3255.1.camel@localhost.localdomain> On Sat, 2007-06-16 at 18:30 -0700, Marcpp wrote: > Hi, I need to returns a tuple from a function (reads a database) > Any idea?. def f(): return (1,2) Somehow I have the feeling that there's more to your question than you're letting on... -- Carsten Haese http://informixdb.sourceforge.net From cptnwillard at gmail.com Wed Jun 13 08:01:18 2007 From: cptnwillard at gmail.com (cptnwillard at gmail.com) Date: Wed, 13 Jun 2007 05:01:18 -0700 Subject: Is there any way to catch expections when call python method in C++ In-Reply-To: <1181727704.631721.269650@g37g2000prf.googlegroups.com> References: <1181727704.631721.269650@g37g2000prf.googlegroups.com> Message-ID: <1181736078.033612.278390@n15g2000prd.googlegroups.com> One way is to create an intermediate python function, which returns a special value when an exception is caught. def ExceptionCatcher(FunctionToCall): def F(): try: FunctionToCall() except: return -1 return 0 return F Then instead of calling your function, you would call ExceptionCatcher(YourFunction). You can then check the return value in your C++ code. From lobais at gmail.com Wed Jun 6 08:11:01 2007 From: lobais at gmail.com (Thomas Dybdahl Ahle) Date: Wed, 06 Jun 2007 14:11:01 +0200 Subject: subprocess leaves child living References: <1181052375.551083.117390@p47g2000hsd.googlegroups.com> <874plmgogn.fsf@merkury.smsnet.pl> Message-ID: Den Tue, 05 Jun 2007 17:41:47 -0500 skrev Michael Bentley: > On Jun 5, 2007, at 5:13 PM, Michael Bentley wrote: > > >> On Jun 5, 2007, at 4:17 PM, Thomas Dybdahl Ahle wrote: >> >>> Den Tue, 05 Jun 2007 15:46:39 -0500 skrev Michael Bentley: >>> >>>> But actually *that* is an orphan process. When a parent process dies >>>> and the child continues to run, the child becomes an orphan and is >>>> adopted by init. Orphan processes can be cleaned up on most Unices >>>> with >>>> 'init q' (or something very similar). >>> >>> Is it not possible to tell python that this process should not be >>> adopted >>> by init, but die with its parrent? >>> Just like terminals seem to do it.. >> >> Well, the way you posed the original question: >> >>> from subprocess import Popen >>> popen = Popen(["ping", "google.com"]) from time import sleep >>> sleep(100) >> >> is really what adoption by init is designed to handle. Here you've >> created a child but have not waited for its return value. Like a good >> adoptive parent, init will wait(2) for the child. >> >> I think if you really looked into it you'd find that the terminal had >> called wait(2) before it was killed. Similarly, if you start a long- >> running subprocess in python and wait for it to return -- killing the >> parent will slaughter the child as well. > > I guess I should have verified my suspicions before speaking up -- I was > worng -- even if you are waiting for a return code, the child will > persist as a child of init. Bugger. I know that if you use forkpty, the child get slaughtered, but using the subprocess module just seems much easier than forking. From http Sat Jun 16 23:07:35 2007 From: http (Paul Rubin) Date: 16 Jun 2007 20:07:35 -0700 Subject: Python's "only one way to do it" philosophy isn't good? References: <1181368143.874341.273140@r19g2000prf.googlegroups.com> <1hzrsp4.7vjuav1aegg0tN%aleax@mac.com> <7SSci.35627$G23.1695@newsreading01.news.tds.net> <7xejkb23fe.fsf@ruckus.brouhaha.com> <6dXci.35643$G23.6531@newsreading01.news.tds.net> Message-ID: <7xr6obmg7c.fsf@ruckus.brouhaha.com> Neil Cerutti writes: > I don't know that much about ML. I know is does a really nice job > of generic containers, as does C++. But can it 'foo' any type as > easily as C++? > > template T foo(T); I don't know enough C++ to understand what the above means exactly, but I think the answer is approximately "yes". I actually don't know ML either, so I'm thinking in terms of Haskell types which are similar. From twisted0n3 at gmail.com Sun Jun 10 00:09:18 2007 From: twisted0n3 at gmail.com (Twisted) Date: Sun, 10 Jun 2007 04:09:18 -0000 Subject: The Concepts and Confusions of Prefix, Infix, Postfix and Fully Functional Notations In-Reply-To: <0uHai.176367$nh4.13819@newsfe20.lga> References: <1179936917.652372.24780@q69g2000hsb.googlegroups.com> <1180508453.226022.44230@q19g2000prn.googlegroups.com> <1181335574.107472.229370@x35g2000prf.googlegroups.com> <1181358616.792797.97720@k79g2000hse.googlegroups.com> <1181414625.121073.203940@g4g2000hsf.googlegroups.com> <0uHai.176367$nh4.13819@newsfe20.lga> Message-ID: <1181448558.120521.63250@g4g2000hsf.googlegroups.com> On Jun 9, 8:21 pm, "BCB" wrote: > "Paul McGuire" wrote in message > > news:1181414625.121073.203940 at g4g2000hsf.googlegroups.com... > > > On Jun 9, 6:49 am, Lew wrote: > >> > In particular, Perl code looks more like line > >> > noise than like code from any known programming language. ;)) > > >> Hmm - I know of APL and SNOBOL. > > >> -- > >> Lew > > > TECO editor commands. I don't have direct experience with TECO, but > > I've heard that a common diversion was to type random characters on > > the command line, and see what the editor would do. > > > -- Paul > > J > > http://www.jsoftware.com/ Oh come on! Toy languages (such as any set of editor commands) and joke languages (ala Intercal) don't count, even if they are technically Turing-complete. ;) Nor does anything that was designed for the every-character-at-a- premium punch-card era, particularly if it is, or rhymes with, "COBOL". Those have excuses, like it's a joke or it's a constrained environment. Perl, unfortunately, has no such excuses. If there were such a thing as "embedded Perl", I'd have to hesitate here, but since there isn't... From cowie.rob at gmail.com Tue Jun 19 12:16:59 2007 From: cowie.rob at gmail.com (Rob Cowie) Date: Tue, 19 Jun 2007 09:16:59 -0700 Subject: easy_install from svn Message-ID: <1182269819.795671.43860@k79g2000hse.googlegroups.com> Hi all, I currently use easy_install to install packages from a custom, locally hosted package_index. The index consists of a single html doc with a list of package names and urls. All works well. I would like to get a little more sophisticated and install a package from subversion. My package is structured as described in the setuptools docs. Simply pointing the url in my package index to svn://my/repo/package/trunk works, but I would like - and I get the impression it is possible - to be able to specify a revision number, or a tag and have that version installed. Is it simply a case of appending a fragment to the url? Would anyone be so kind as to provide a working example? cheers, Rob Cowie From s.mientki at id.umcn.nl Fri Jun 8 03:14:46 2007 From: s.mientki at id.umcn.nl (stef) Date: Fri, 08 Jun 2007 09:14:46 +0200 Subject: wxPython / Dabo demo shell ? Message-ID: <4646a$466901e6$83aef404$30670@news2.tudelft.nl> hello, I was impressed by the demo shell of wxPython, and a few days ago (finally getting Dabo to work), I saw Dabo uses the same demo shell. Is there any more information available about this shell, because it seems a very nice / good way to show (many) demos, in an organized way to newbies. thanks, Stef mientki From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Mon Jun 25 16:12:36 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Mon, 25 Jun 2007 22:12:36 +0200 Subject: Chroot Jail Not Secure for Sandboxing Python? References: <1182748892.916068.146780@p77g2000hsh.googlegroups.com> <467f55f7$0$20850$9b622d9e@news.freenet.de> <1182782910.811850.284350@u2g2000hsc.googlegroups.com> Message-ID: <5ealtkF37mjlvU2@mid.individual.net> gregpinero at gmail.com wrote: > I followed up with my ISP. Here's the answer I got: > > The os.exec call prepends the chroot directory to the absolute > path, but does NOT provide chroot for the child process. That sounds like rubbish to me. If it worked like that, chrooting servers would be virtually useless. Which OS is the ISP using? Tell him to do "man 2 chroot" and read it. | NAME | chroot - change root directory | | SYNOPSIS | #include | | int chroot(const char *path); | | DESCRIPTION | chroot() changes the root directory to that specified | in path. This directory will be used for pathnames | beginning with /. The root directory is inherited by all | children of the current process. [...] Regards, Bj?rn -- BOFH excuse #282: High altitude condensation from U.S.A.F prototype aircraft has contaminated the primary subnet mask. Turn off your computer for 9 days to avoid damaging it. From chowroc.z at gmail.com Thu Jun 21 23:18:47 2007 From: chowroc.z at gmail.com (Roc Zhou) Date: Fri, 22 Jun 2007 03:18:47 -0000 Subject: __repr__ affected after __getattr__ overloaded? Message-ID: <1182482327.459479.88440@i13g2000prf.googlegroups.com> Now I have to design a class that overload __getattr__, but after that, I found the __repr__ have been affected. This is a simple example model: #!/usr/bin/env python class test: def __init__(self): self.x = 1 def __getattr__(self, attr_name): try: return self.__dict__[attr_name] except KeyError: self.__dict__[attr_name] = 'inexistent' return self.__dict__[attr_name] t = test() print t.x print t.y print type(t) T = t print T.x print t So far, I still want the "print t" return "", but when run, the result is: sh$ python test.py 1 inexistent 1 Traceback (most recent call last): File "testtree.py", line 23, in ? print t TypeError: 'str' object is not callable I also tried to overload __repr__, but no effect: #!/usr/bin/env python class test: def __init__(self): self.x = 1 def __getattr__(self, attr_name): try: return self.__dict__[attr_name] except KeyError: self.__dict__[attr_name] = 'inexistent' return self.__dict__[attr_name] def __repr__(self): return 'test.__repr__' t = test() print t.x print t.y print type(t) T = t print T.x print t Still raise TypeError Exception: Traceback (most recent call last): File "testtree.py", line 23, in ? print t TypeError: 'str' object is not callable So why? Thanks From justin.mailinglists at gmail.com Sun Jun 24 21:20:05 2007 From: justin.mailinglists at gmail.com (Justin Ezequiel) Date: Mon, 25 Jun 2007 01:20:05 -0000 Subject: something similar to shutil.copytree that can overwrite? In-Reply-To: <1182517654.784333.55840@a26g2000pre.googlegroups.com> References: <1182331815.865344.190700@u2g2000hsc.googlegroups.com> <1182336006.442871.287590@a26g2000pre.googlegroups.com> <1182423939.466780.322230@c77g2000hse.googlegroups.com> <1182476040.395213.280320@d30g2000prg.googlegroups.com> <1182517654.784333.55840@a26g2000pre.googlegroups.com> Message-ID: <1182734405.739294.298640@z28g2000prd.googlegroups.com> On Jun 22, 9:07 pm, Ben Sizer wrote: > That's the easy bit to fix; what about overwriting existing files > instead of copying them? Do I have to explicitly check for them and > delete them? It seems like there are several different copy functions > in the module and it's not clear what each of them do. What's the > difference between copy, copyfile, and copy2? Why do the docs imply > that they overwrite existing files when copytree skips existing > files? > > -- > Ben Sizer copytree does not skip existing files if will overwrite said files I just missed the makedirs call at the start the failed makedirs call will cause the copytree function to exit completely thus you do not get your files updated but with the if exists check, your files should get overwritten From Leo.Kislov at gmail.com Fri Jun 8 05:24:42 2007 From: Leo.Kislov at gmail.com (Leo Kislov) Date: Fri, 08 Jun 2007 02:24:42 -0700 Subject: How to wrap a Japanese text in Python In-Reply-To: <1181218336.318399.59910@w5g2000hsg.googlegroups.com> References: <1181218336.318399.59910@w5g2000hsg.googlegroups.com> Message-ID: <1181294682.827135.306850@n15g2000prd.googlegroups.com> On Jun 7, 5:12 am, prashantkisanpatil at gmail.com wrote: > Hi All, > > I am trying to wrap a japanese text in Python, by the following code. > > if len(message) > 54: > message = message.decode("UTF8") > strlist = textwrap.wrap(message,54) > > After this I am wirting it to you a CAD Software window. While > displaying in this window some Japanese characters at the end of the > line & some at the begining of the line are not displayed at all. > Meaning the text wrapping is not happening correctly. > > Can any body please help me out in resolving this problem. First of all you should move message.decode('utf-8') call out of "if" and you don't need "if" anyway because if the line is less than 54 textwrap won't touch it: message = message.decode('utf-8') strlist = textwrap.wrap(message, 54) I don't know Japanese but the following example *seems* to work fine for me: # -*- coding: utf-8 -*- sample=u""" """ import textwrap for line in textwrap.wrap(sample, 6): print line -------------------------------- Result: Can you post a short example that clearly demonstrates the problem? -- Leo From newsgroups at nospam.demon.co.uk Fri Jun 1 04:52:48 2007 From: newsgroups at nospam.demon.co.uk (Douglas Woodrow) Date: Fri, 1 Jun 2007 09:52:48 +0100 Subject: c[:]() References: Message-ID: On Thu, 31 May 2007 18:42:05, Warren Stringer wrote >They were copied from working code. Copied *badly*? Yes. Running python via: > Windows -> start -> run -> python >doesn't allow cut and paste Hi Warren, Actually you can copy and paste from a Windows cmd/command shell: right-click the title-bar of the window, select "Edit" from the pop-up menu, then "Mark" from the sub-menu to copy whatever you want to select into the Windows clipboard. HTH, -- Doug Woodrow From gagsl-py2 at yahoo.com.ar Fri Jun 22 01:10:29 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 22 Jun 2007 02:10:29 -0300 Subject: subprocess.popen question References: <1182353267.200998.43900@w5g2000hsg.googlegroups.com> <1182380572.235876.113160@n2g2000hse.googlegroups.com> <1182389286.706352.64780@o61g2000hsh.googlegroups.com> <1182485136.821993.315710@o11g2000prd.googlegroups.com> Message-ID: En Fri, 22 Jun 2007 01:05:36 -0300, Eric_Dexter at msn.com escribi?: >> >> >> cmd = ["gawk", "-f", "altertime.awk", "-v", "time_offset=4", "-v", >> >> >> "outfile=testdat.sco", "i1.sco"] >> >> >> output = subprocess.Popen(cmd, >> >> stdout=subprocess.PIPE).communicate()[0] >> >> >> lines = output.splitlines() >> >> >> for line in lines: >> >> >> print line >> >> >> > C:\dex_tracker\pipe1.py >> >> > Traceback (most recent call last): >> >> > File "C:\dex_tracker\pipe1.py", line 14, in >> >> > last_line = subprocess.Popen([cmd], >> >> > stdout=subprocess.PIPE).communicate()[0] >> >> > File "C:\Python25\lib\subprocess.py", line 593, in __init__ >> >> > errread, errwrite) >> >> > File "C:\Python25\lib\subprocess.py", line 793, in _execute_child >> >> > startupinfo) >> >> > WindowsError: [Error 2] The system cannot find the file specified >> >> > Script terminated. >> >> >> > I can write it out as a batch file and then run it but that is a >> messy >> >> > hack.. >> >> >> If cmd is a list of arguments, like the example above, you should use >> >> subprocess.Popen(cmd,...) (like the example above, too). >> >> > I had cut and pasted the example in to get that error... could it be >> > a problem with ms windows??? (I am at a library computer befour work >> > so that ended my testing) >> >> Note the call to subprocess.Popen- is the first argument [cmd] or cmd? >> What do you get with print repr(cmd)? >> Do you have gawk installed on that machine too? > > gawk is installed.. I do fine when I just call gawk I get all the > options to use with it but the minute I try to use the options with it > I have problems. I have done it with batch files but then I would > have to write out a batch file and then run the batch file. seems > like more work than I should have to do to use options with a command > line program.. I have done this in other cases with os.startfile and > other cases and would like to fix it. Ok, but please check *what* are the arguments to Popen. If cmd is a *list* as shown on the first quoted line on this message, you should call subprocess.Popen(cmd, ...) as shown on the third line on this message, but your traceback shows that you are using Popen([cmd], ...) Can you see the difference? -- Gabriel Genellina From tleeuwenburg at gmail.com Thu Jun 21 02:00:35 2007 From: tleeuwenburg at gmail.com (tleeuwenburg at gmail.com) Date: Thu, 21 Jun 2007 06:00:35 -0000 Subject: Python live environment on web-site? In-Reply-To: <46794396.442103@news.netcologne.de> References: <46794396.442103@news.netcologne.de> Message-ID: <1182405635.091199.180950@i13g2000prf.googlegroups.com> On Jun 21, 1:18 am, Thomas.Len... at netcologne.de (Thomas Lenarz) wrote: > Hi all, > > I was wondering if there was a python-live-environment available on a > public web-site similar to the ruby-live-tutorial on > > http://tryruby.hobix.com/ > > I would prefer something which allows to paste small scripts into a > text-field, to run them on the server, and to be able to read the > produced output of the script. > > I searched using google but didn't come across such a site. However, I > imagine there must be at least one.... > > Thanks for any hint, > > Thomas Crunchy. From jstroud at mbi.ucla.edu Wed Jun 6 07:10:43 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Wed, 06 Jun 2007 04:10:43 -0700 Subject: Determinant of Large Matrix Message-ID: Hello All, I'm using numpy to calculate determinants of matrices that look like this (13x13): [[ 0. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1.] [ 1. 0. 1. 4. 1. 9. 4. 4. 1. 1. 4. 9. 4. 9.] [ 1. 1. 0. 1. 4. 4. 9. 9. 4. 4. 1. 4. 1. 4.] [ 1. 4. 1. 0. 9. 1. 4. 4. 9. 1. 4. 1. 4. 1.] [ 1. 1. 4. 9. 0. 4. 4. 4. 1. 4. 1. 9. 4. 9.] [ 1. 9. 4. 1. 4. 0. 4. 4. 9. 4. 1. 1. 4. 1.] [ 1. 4. 9. 4. 4. 4. 0. 1. 1. 1. 9. 1. 9. 4.] [ 1. 4. 9. 4. 4. 4. 1. 0. 4. 1. 9. 4. 4. 1.] [ 1. 1. 4. 9. 1. 9. 1. 4. 0. 4. 4. 4. 4. 9.] [ 1. 1. 4. 1. 4. 4. 1. 1. 4. 0. 9. 4. 9. 4.] [ 1. 4. 1. 4. 1. 1. 9. 9. 4. 9. 0. 4. 1. 4.] [ 1. 9. 4. 1. 9. 1. 1. 4. 4. 4. 4. 0. 4. 1.] [ 1. 4. 1. 4. 4. 4. 9. 4. 4. 9. 1. 4. 0. 1.] [ 1. 9. 4. 1. 9. 1. 4. 1. 9. 4. 4. 1. 1. 0.]] For this matrix, I'm getting this with numpy: 2774532095.9999971 But I have a feeling I'm exceeding the capacity of floats here. Does anyone have an idea for how to treat this? Is it absurd to think I could get a determinant of this matrix? Is there a python package that could help me? Many thanks for any answers. James From twisted0n3 at gmail.com Wed Jun 20 17:36:28 2007 From: twisted0n3 at gmail.com (Twisted) Date: Wed, 20 Jun 2007 21:36:28 -0000 Subject: The Modernization of Emacs: terminology buffer and keybinding In-Reply-To: <5dtk4tF34jrimU1@mid.dfncis.de> References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182272495.990807.99110@a26g2000pre.googlegroups.com> <87tzt3ihev.fsf@kobe.laptop> <1182370216.961241.6960@n60g2000hse.googlegroups.com> <85zm2ufjpb.fsf@lola.goethe.zz> <1182372592.803332.288260@u2g2000hsc.googlegroups.com> <5dtk4tF34jrimU1@mid.dfncis.de> Message-ID: <1182375388.814275.227380@n2g2000hse.googlegroups.com> On Jun 20, 5:22 pm, Matthias Buelow wrote: > Twisted wrote: > > That's a joke, right? I tried it a time or two. Every time it was > > rapidly apparent that doing anything non-trivial would require > > consulting a cheat sheet. The printed-out kind, since navigating to > > the help and back without already having the help displayed and open > > to the command reference was also non-trivial. > > Ah, yes.. we live in a time where no-one seems to have the patience to > read documentation anymore. Maybe that's why there is such a scarcity of > good documentation with many "modern" software packages. Emacs does have documentation. The problem is you have to already know a load of emacs navigation oddities^Wkeyboard commands to get to and use it. Also, basic tasks should not require consulting the documentation, unless the application genre is new to the user. Basic tasks requiring the uninitiated to consult the documentation is okay in 3D modeling apps, given the "uninitiated" have used none before. Basic tasks requiring the uninitiated to consult the documentation is absolutely ludicrous in a text editor. I count "consulting the documentation" as one of those basic tasks, along with the fundamental editing, saving, loading, and searching functionality (including, of course, "searching the documentation"). > ``I abhor a system designed for the "user", if that word is a coded > pejorative meaning "stupid and unsophisticated".'' Yeah, and I abhor the elitist systems that are designed with the philosophy that anyone who hasn't mastered years of arcane memorization and training in just that one idiosyncratic system is / ipso facto/ "stupid and unsophisticated". Most of us 6 and a half billion people have better uses for our time, such as buckling in and being promptly productive, once we're out of high school or college, and fully three and a quarter of us are at least as smart as average, and so /ipso facto/ *not* "stupid and unsophisticated". From bruno.42.desthuilliers at wtf.websiteburo.oops.com Fri Jun 15 12:58:11 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Fri, 15 Jun 2007 18:58:11 +0200 Subject: dynamically generated runtime methods & reflection In-Reply-To: <1hzqn43.3l62fu518knjN%aleax@mac.com> References: <467277fc$0$21230$426a74cc@news.free.fr> <1hzqn43.3l62fu518knjN%aleax@mac.com> Message-ID: <4672c515$0$24458$426a34cc@news.free.fr> Alex Martelli a ?crit : > Bruno Desthuilliers > wrote: > >> Josiah Carlson a ?crit : >> (snip) >>> Well, the particular operation is typically called 'currying a >>> function', >> >> it's not 'currying' but 'partial application'. >> >> Currying is somehow the reverse of partial : it's a way of building a >> multiple-args function from single-args functions. >> > > Wikipedia says > >"currying or Sch?nfinkelisation[1] " cf below... > "is the technique of > transforming a function that takes multiple arguments into a function > that takes a single argument" The definition commonly agreed upon (in the FP world at least) is that currying is the process that "build" ("emulate", whatever...) multiple-args functions in a context that only supports single-arg functions (ie: ML, Haskell), so that (using Python syntax): f(x, y, z) would really be in fact (and under the hood): f(x)(y)(z) where f(x) returns a function closing over(x) and taking y, itself returning a function closing over x and y and taking z... Talking about this: """ currying (...) reduces multiple-argument functions to single-argument functions only (Schoenfinkel, 1924) """ http://srfi.schemers.org/srfi-26/mail-archive/msg00015.html So while *very closely* related to partial application, it's not exactly the same thing. FWIW, you can also have a look here: http://www.python.org/dev/peps/pep-0309/#motivation > -- and FWIW I agree with Wikipedia in this > case; I don't - and I'm not the only one: http://lambda-the-ultimate.org/node/2266 """ I had mistakenly learned that curry was a form of generalized partial application from the paper : Function Currying in Scheme by Jeffrey A. Meunier and the Wikipedia entry (I should have known better), however I was mildly reprimanded for making this novice mistake in a recent paper submission to ICFP """ > the reverse (going from single-arg to multiple-args) Note that I didn't say "going from", but "building". The context is a functional language where there's *no* such thing as "multiple args" functions. Re-reading, I can agree that my choice of words may have been a bit poor, specially wrt/ the word "reverse". What I meant here was that partial application is used in the context of multiple-args function to 'build' a function taking n-x arguments from a function taking n arguments, while currying is used in the context of single-arg functions to "emulate" multiple-args functions. > would be > "uncurrying", though I don't think I've ever used that term myself. > > functools.partial's name may be more precise (because it can, e.g., go > from a function taking 3 arguments to one taking 2 -- not just from N > down to 1) > > but your 'pedantic' remark seems pedantically wrong:-). I certainly won't pretend knowing more about CS that you do, but given the definition of currying in pep-0309 - which exactly matches the definition I first learned when toying with Haskell -, I maintain my pedantic remark until proven wrong - which BTW should not be overly difficult if it happened to be the case !-) As a last word, the original version of pep-0309 was named "curry", and has been corrected since: """ It isn't function currying, but partial application. Hence the name is now proposed to be partial(). """ http://www.python.org/dev/peps/pep-0309/#feedback-from-comp-lang-python-and-python-dev From puluanau at gmail.com Mon Jun 25 16:04:35 2007 From: puluanau at gmail.com (Pulu) Date: Mon, 25 Jun 2007 13:04:35 -0700 Subject: Python SVN down? In-Reply-To: <1182799060.612115.75490@n60g2000hse.googlegroups.com> References: <1182799060.612115.75490@n60g2000hse.googlegroups.com> Message-ID: <1182801875.115579.59930@z28g2000prd.googlegroups.com> Can confirm the same behavior from locations in California and Arizona. The machine responds to pings but sends resets on any connection to tcp port 80... Asked in IRC, no response. On Jun 25, 12:17 pm, "gregpin... at gmail.com" wrote: > Going to this URL:http://svn.python.org/view/ > > It gives me an error: > Unable to connect > Firefox can't establish a connection to the server at svn.python.org. > > And using SVN as so: > > $ svn checkouthttp://svn.python.org/projects/python/trunk/~/ > python_work/ > svn: PROPFIND request failed on '/projects/python/trunk' > svn: PROPFIND of '/projects/python/trunk': could not connect to server > (http://svn.python.org) > > Gives me the above error. > > Any ideas? I didn't see an announcement about this anywhere. > > -Greg From half.italian at gmail.com Wed Jun 20 03:15:40 2007 From: half.italian at gmail.com (half.italian at gmail.com) Date: Wed, 20 Jun 2007 00:15:40 -0700 Subject: Windows XMLRPC Service In-Reply-To: References: <1182137125.879556.319030@g37g2000prf.googlegroups.com> <1182235519.964013.146800@a26g2000pre.googlegroups.com> <1182275830.571891.278580@n15g2000prd.googlegroups.com> Message-ID: <1182323740.867038.297050@i38g2000prf.googlegroups.com> On Jun 19, 12:32 pm, "Gabriel Genellina" wrote: > En Tue, 19 Jun 2007 14:57:10 -0300, escribi?: > > >> > #win32event.WAIT_TIMEOUT = 2 --- This just makes the loop > >> > never execute because > >> > # the WaitFor... part always returns 258 > > >> WAIT_TIMEOUT is 258. How do you see it is 2? > >> py> import win32event > >> py> win32event.WAIT_TIMEOUT > >> 258 > > > I meant here that *if* I set the WAIT_TIMEOUT to 2, then I see that > > behavior. > > Ah, ok! I should have stated clearly that WAIT_TIMEOUT is a Windows > predefined constant, not your desired timeout value. > > > Thank you again Gabriel. I'll post back with something complete. > > Yes, please, a working example would be nice for future readers... > > -- > Gabriel Genellina For posterity... import sys import win32serviceutil import win32service import win32event import win32evtlogutil import servicemanager import SocketServer, socket from SimpleXMLRPCServer import SimpleXMLRPCServer,SimpleXMLRPCRequestHandler # Threaded mix-in class AsyncXMLRPCServer(SocketServer.ThreadingMixIn,SimpleXMLRPCServer): pass import XMLRPC_funcs # module containing the functions wrapped in a class class XMLRPCservice(win32serviceutil.ServiceFramework): _svc_name_ = "PythonXMLRPC" _svc_display_name_ = "PythonXMLRPC" _svc_description_ = "Multi-threaded Python XMLRPC Server" def __init__(self, args): # set the timeout so the service can stop...Otherwise it hangs forever socket.setdefaulttimeout(15) win32evtlogutil.AddSourceToRegistry(self._svc_display_name_, sys.executable, "Application") win32serviceutil.ServiceFramework.__init__(self, args) # Create an event which we will use to wait on. self.hWaitStop = win32event.CreateEvent(None, 0, 0, None) localhost = socket.gethostbyname(socket.gethostname()) self.server = AsyncXMLRPCServer((localhost, 8000), SimpleXMLRPCRequestHandler) def SvcStop(self): self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) #send the stop event win32event.SetEvent(self.hWaitStop) def SvcDoRun(self): # log a start msg servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE, servicemanager.PYS_SERVICE_STARTED, (self._svc_name_, ' (%s)' % self._svc_name_)) self.server.register_instance(XMLRPC_funcs.XMLRPC_funcs()) # handle requests until the stop event is received while win32event.WaitForSingleObject(self.hWaitStop, 0) == win32event.WAIT_TIMEOUT: self.server.handle_request() # log a stopped msg win32evtlogutil.ReportEvent(self._svc_name_, servicemanager.PYS_SERVICE_STOPPED, 0, servicemanager.EVENTLOG_INFORMATION_TYPE, (self._svc_name_,"")) if __name__ == '__main__': win32serviceutil.HandleCommandLine(XMLRPCservice) From notbob at nothome.com Thu Jun 21 12:26:59 2007 From: notbob at nothome.com (notbob) Date: Thu, 21 Jun 2007 11:26:59 -0500 Subject: The Modernization of Emacs: terminology buffer and keybinding References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182272495.990807.99110@a26g2000pre.googlegroups.com> <87tzt3ihev.fsf@kobe.laptop> <1182370216.961241.6960@n60g2000hse.googlegroups.com> <85zm2ufjpb.fsf@lola.goethe.zz> <1182372592.803332.288260@u2g2000hsc.googlegroups.com> Message-ID: ["Followup-To:" header set to comp.emacs.] > If you'd spent half an hour using the tutorial (helpfully displayed > right there when you start emacs), you could have saved three and a half > hours of wasted time. And you'd now be using an actual text editor, > which is often helpful. Your statement is obviously based on your assumption everyone has as good a memory as you. Unfortunately, this is not always the case. I came to emacs as a geezer with a less than sterling short term memory. I got about 8 keystrokes into the tutorial before I was lost. I finally had to start a cheat sheet. It's also a PIA to read a tutorial and practice in another window until you know how to open/close/juggle said windows. I never did get much from emacs' tutorial. It also took me awhile to train my pinkies to reach for that until-now-unused Ctrl key. No, using emacs is not trivial. It's a learned skill that requires some effort. More for some than others. In emacs', defense, it's a helluva lot more intuitive than vi, which is a nightmare straight from Hell! nb From steve at REMOVE.THIS.cybersource.com.au Sat Jun 23 21:06:54 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sun, 24 Jun 2007 11:06:54 +1000 Subject: Python's "only one way to do it" philosophy isn't good? References: <1181368143.874341.273140@r19g2000prf.googlegroups.com> <7x3b0nmkk6.fsf@ruckus.brouhaha.com> Message-ID: On Sat, 23 Jun 2007 14:56:35 -0400, Douglas Alan wrote: >> How long did it take you to write the macros, and use them, compared >> to running Pylint or Pychecker or equivalent? > > An hour? Who cares? You write it once and then you have it for the > rest of your life. You put it in a widely available library, and then > *every* programmer also has it for the rest of their lives. The > amortized cost: $0.00. The value: priceless. Really? Where do I download this macro? How do I find out about it? How many Lisp programmers are using it now? How does your glib response jib with your earlier claims that the weakness of Lisp/Scheme is the lack of good libraries? Googling for ' "Douglas Allen" download lisp OR scheme ' wasn't very promising. If you have made your macros available to others, they don't seem to be very well-known. In fairness, the various Python lints/checkers aren't part of the standard library either, but they are well-know "standards". >> But if you really want declarations, you can have them. > >>>>> import variables >>>>> variables.declare(x=1, y=2.5, z=[1, 2, 4]) >>>>> variables.x = None >>>>> variables.w = 0 >> Traceback (most recent call last): >> File "", line 1, in >> File "variables.py", line 15, in __setattr__ >> raise self.DeclarationError("Variable '%s' not declared" % name) >> variables.DeclarationError: Variable 'w' not declared > > Thanks, but that's just too syntactically ugly and verbose for me to > use. "Syntactically ugly"? "Verbose"? Compare yours with mine: let x = 0 let y = 1 let z = 2 set x = 99 (Looks like BASIC, circa 1979.) variables.declare(x=0, y=1, z=2) variables.x = 99 (Standard Python syntax.) I don't think having two easily confused names, let and set, is an advantage, but if you don't like the word "declare" you could change it to "let", or change the name of the module to "set" (although that runs the risk of confusing it with sets). Because this uses perfectly stock-standard Python syntax, you could even do this, so you type fewer characters: v = variables v.x = 99 and it would Just Work. > Not only that, but my fellow Python programmers would be sure to > come and shoot me if I were to code that way. *shrug* They'd shoot you if you used "let x = 0" too. > One of the reasons that I want to use Python is because I like reading > and writing code that is easy to read and looks good. I don't want to > bend it to my will at the expense of ugly looking code. But the "ugly looking code" is stock-standard Python syntax. module.function(keyword=value) module.attribute = value is precisely the standard Python syntax you describe as "easy to read and looks good" one moment. I don't believe you that you find it "ugly looking code" -- if you did, you wouldn't be using Python. -- Steven. From mclaugb at nospm.yahoo.com Tue Jun 19 09:19:43 2007 From: mclaugb at nospm.yahoo.com (mclaugb) Date: Tue, 19 Jun 2007 14:19:43 +0100 Subject: very simple shared dll with ctypes References: Message-ID: Assigining restype and argtypes works! "Thomas Heller" wrote in message news:mailman.9228.1182256599.32031.python-list at python.org... > mclaugb schrieb: >> I have created a simple windows small_dll.dll exporting a function that >> does >> a computation using C and C++ classes which i wish to call from Python. >> I >> have read lots of ctypes documentation but I still dont quite understand >> how >> to call the function. >> >> As a test, I have written a much simpler mathematical function below to >> try >> to get it to work from Python. >> >> I am trying to call this from python by: >> >>>>from ctypes import * >>>>print cdll.small_dll.adder(c_double(5.343534),c_double(3.4432)) >>>>2223968 >> >> Can someone give me a few tips to get going! > > You should assign the .restype and the .argtypes attributes to your > function. > That gives the the proper result, and you don't have to pack the arguments > into > c_double yourself. > >> The DLL declaration is below. >> >> #include >> #if defined(_MSC_VER) >> #define DLL extern "C" __declspec(dllexport) >> #else >> #define DLL >> #endif >> >> DLL double adder(double a, double b){ >> double c; >> c=a+b; >> return c; >> } >> > > from ctypes import * > adder = cdll.small_dll.adder > adder.restype = c_double > adder.argtypes = c_double, c_double > > print adder(5.343534, 3.4432) > > > Thomas > From marcpp at gmail.com Sun Jun 24 11:02:58 2007 From: marcpp at gmail.com (Marcpp) Date: Sun, 24 Jun 2007 08:02:58 -0700 Subject: WX call a pywx program from a program, and return values Message-ID: <1182697378.006060.178900@n2g2000hse.googlegroups.com> I need to call a pywx program(1) from an wxpy program(2) and return a value to program(2). Any example to do it? From karthik.kriz at gmail.com Mon Jun 25 05:54:03 2007 From: karthik.kriz at gmail.com (Karthik Krishnamurthy) Date: Mon, 25 Jun 2007 15:24:03 +0530 Subject: multiple python versions of a 3rd party application/libarary Message-ID: <299163c50706250254s56cb11b6nee9ec7e1c718aab4@mail.gmail.com> hi, I maintain applications/libraries which I upgrade often at a different location. For example if I maintain mercurial at /opt/sfw/mercurial/0.9.3 I have PYTHONPATH set to /opt/sfw/mercurial/0.9.3/lib/python2.4/site-packages. How can I get python to look into python2.4 and python2.4/site-packages automatically (assuming it is 2.4) and likewise for 2.5. That way I can keep them under the same directory. /kk -------------- next part -------------- An HTML attachment was scrubbed... URL: From aahz at pythoncraft.com Wed Jun 27 17:13:50 2007 From: aahz at pythoncraft.com (Aahz) Date: 27 Jun 2007 14:13:50 -0700 Subject: equality & comparison by default (was Re: Too many 'self' in python.That's a big flaw in this language.) References: <1182942154.185461.89620@e9g2000prf.googlegroups.com> <1i0cy8z.z94q5d1dxgexxN%aleax@mac.com> Message-ID: In article <1i0cy8z.z94q5d1dxgexxN%aleax at mac.com>, Alex Martelli wrote: > >In Python 3000, ordering comparisons will not exist by default (sigh, a >modest loss of practicality on the altar of purity -- ah well, saw it >coming, ever since complex numbers lost ordering comparisons), but >equality and hashing should remain just like now (yay!). While emotionally I agree with you, in practice I have come to agree with the POV that allowing default ordering comparisons between disjoint types causes subtle bugs that are more difficult to fix than the small amount of boilerplate needed to force comparisons when desired. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "as long as we like the same operating system, things are cool." --piranha From basti.wiesner at gmx.net Sun Jun 17 14:32:19 2007 From: basti.wiesner at gmx.net (Sebastian Wiesner) Date: Sun, 17 Jun 2007 20:32:19 +0200 Subject: sqlite3 bug?? In-Reply-To: <1182104149.3162.11.camel@localhost.localdomain> References: <46752230$0$31685$db0fefd9@news.zen.co.uk> <1182091411.108272.286280@o61g2000hsh.googlegroups.com> <1182104149.3162.11.camel@localhost.localdomain> Message-ID: <200706172032.24354.basti.wiesner@gmx.net> [ Carsten Haese ] > On Sun, 2007-06-17 at 07:43 -0700, 7stud wrote: > > Please report the whole docs as a bug. > > Calling the entire docs a bug is not helpful. ... unless he also comes up with the "bugfix". ;) -- Freedom is always the freedom of dissenters. (Rosa Luxemburg) -------------- 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 Graham.Dumpleton at gmail.com Mon Jun 25 20:29:48 2007 From: Graham.Dumpleton at gmail.com (Graham Dumpleton) Date: Tue, 26 Jun 2007 00:29:48 -0000 Subject: server wide variables In-Reply-To: <1182785365.877473.298170@q75g2000hsh.googlegroups.com> References: <1182785365.877473.298170@q75g2000hsh.googlegroups.com> Message-ID: <1182817788.562497.44430@z28g2000prd.googlegroups.com> On Jun 26, 1:29 am, Jay Sonmez wrote: > I want to be able to save some server variables as long as Apache runs > on the server (mod_python). > > How is that possible in Python? It depends on whether you expect all Apache child processes for that server to be able to access the data and for the data to be able to survive the killing off and start up of individual Apache child processes. For background on some of the issues read: http://www.dscpl.com.au/wiki/ModPython/Articles/TheProcessInterpreterModel Saving data in os.environ is not recommended even if they have to survive just within the context of that specific interpreter within that process, as os.environ access and update is not thread protected and Apache child processes may be multithreaded. So, read that referenced document and then perhaps explain you expectations a bit better. Graham From tony.theodore at gmail.com Tue Jun 26 06:12:26 2007 From: tony.theodore at gmail.com (tony.theodore at gmail.com) Date: Tue, 26 Jun 2007 03:12:26 -0700 Subject: PEP 3107 and stronger typing (note: probably a newbie question) In-Reply-To: References: Message-ID: <1182852746.056954.209720@i38g2000prf.googlegroups.com> On Jun 21, 4:53 am, Stephen R Laniel wrote: > Before I ask anything, let me note that this is surely an > old question that has inspired its share of flame wars; I'm > new to Python, but not new to how Internet discussions work. > So if there's a canonical thread or web page that documents > the whole battle, feel free to point me to it. > > Reading [1], I wonder: why isn't the compiler making better > use of (purely optional) type labeling? Why not make a compiler > directive so that > > a) it will check the types of all my arguments and return > values, and maybe even > b) do some type inference up the call stack? > You might like to look at traits http://code.enthought.com/traits/ From basti.wiesner at gmx.net Sat Jun 30 10:27:50 2007 From: basti.wiesner at gmx.net (Sebastian Wiesner) Date: Sat, 30 Jun 2007 16:27:50 +0200 Subject: linecache and comparison with input In-Reply-To: References: Message-ID: <200706301627.55988.basti.wiesner@gmx.net> [ Ross Hetherington ] > #!/usr/bin/env python > > import random > import sys > import linecache > > rnd = random.randint(1,3) > line = linecache.getline('testfile', rnd) > > print line Try print repr(line) ... > > gss = raw_input('Enter line: ',) and print repr(gss) ;) > if gss == line: > print 'yes' > sys.exit() > else: > print 'no' > Then you will see, that getline returns the line *including the newline character*, while raw_input does not. Use line.strip('\n') to remove trailing newline characters from the return value of getline. -- Freedom is always the freedom of dissenters. (Rosa Luxemburg) -------------- 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 csselo at gmail.com Tue Jun 19 10:35:55 2007 From: csselo at gmail.com (Libertarian) Date: Tue, 19 Jun 2007 07:35:55 -0700 Subject: jedit - auto code completetion Message-ID: <1182263755.913509.152330@n60g2000hse.googlegroups.com> Hi Does it have a plug-in for python code completetion ? thks From blmblm at myrealbox.com Wed Jun 27 15:24:38 2007 From: blmblm at myrealbox.com (blmblm at myrealbox.com) Date: 27 Jun 2007 19:24:38 GMT Subject: The Modernization of Emacs: terminology buffer and keybinding References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <87bqf7fwmg.fsf@telesippa.clsnet.nl> <1182553682.197778.138500@g37g2000prf.googlegroups.com> <87r6nzc9nu.fsf@mail.eng.it> Message-ID: <5efrrmF37rfioU1@mid.individual.net> In article <87r6nzc9nu.fsf at mail.eng.it>, Gian Uberto Lauri wrote: > >>>>> "n" == nebulous99 writes: > > n> On Jun 22, 6:32 pm, Cor Gest wrote: > >> > HOW IN THE BLOODY HELL IS IT SUPPOSED TO OCCUR TO SOMEONE TO > >> ENTER > THEM, GIVEN THAT THEY HAVE TO DO SO TO REACH THE HELP THAT > >> WOULD TELL > THEM THOSE ARE THE KEYS TO REACH THE HELP?! > >> > >> What's your problem ? > >> > >> Ofcourse a mere program-consumer would not look what was being > >> installed on his/her system in the first place ... So after some > >> trivial perusing what was installed and where : WOW Look, MA ! > >> .... it's all there! > >> > >> lpr /usr/local/share/emacs/21.3/etc/refcard.ps or your > >> install-dir........^ ^ or your > >> version.............................^ > > n> So now we're expected to go on a filesystem fishing expedition > n> instead of just hit F1? One small step (backwards) for a man; one > n> giant leap (backwards) for mankind. :P > > Waring, possible ID TEN T detected! > > There's a program called find, not this intuitive but worth learning > > It could solve the problem from the root with something like > > find / -name refcard.ps -exec lpr {} \; 2> /dev/null Let's not make this any worse than it has to be .... If I wanted to find files that might have documentation on emacs, I wouldn't look for filename refcard.ps; I'd try either locate emacs (Linux only AFAIK, won't find recently-added files because it searches against a database usually rebuilt once a day) or find / -name "*emacs*" You are so right that "find" is worth learning, but I'm not sure it's a tool I'd have mentioned in this particular discussion, because it *does* take a bit of learning. I wasn't surprised at all that you got the reply you did. :-)? And as you mention downthread, any time you use "find" to execute a command that might be costly (in terms of paper and ink in this case), it's smart to first do a dry run to be sure the files it's going to operate on are the ones you meant. Whether "find" is better or worse than the GUI-based thing Windows provides for searching for files .... I guess this is really not the time or place to rant about the puppy, is it? (Yes, I know you can make the animated character go away, something I discovered just in time to avoid -- well, I'm not sure, but it wouldn't have been good.) [ snip ] -- B. L. Massingill ObDisclaimer: I don't speak for my employers; they return the favor. From __peter__ at web.de Thu Jun 14 12:43:44 2007 From: __peter__ at web.de (Peter Otten) Date: Thu, 14 Jun 2007 18:43:44 +0200 Subject: Method much slower than function? References: <1181781612.939800.238890@q19g2000prn.googlegroups.com> <1181799961.148499.32210@o11g2000prd.googlegroups.com> Message-ID: Peter Otten wrote: > Leo Kislov wrote: > >> On Jun 13, 5:40 pm, ido... at gmail.com wrote: >>> Hi all, >>> >>> I am running Python 2.5 on Feisty Ubuntu. I came across some code that >>> is substantially slower when in a method than in a function. >>> >>> >>> cProfile.run("bar.readgenome(open('cb_foo'))") >>> >>> 20004 function calls in 10.214 CPU seconds >> >>> >>> cProfile.run("z=r.readgenome(open('cb_foo'))") >>> >>> 20004 function calls in 0.041 CPU seconds >>> >> >> I suspect open files are cached so the second reader >> picks up where the first one left: at the of the file. >> The second call doesn't do any text processing at all. >> >> -- Leo > > Indeed, the effect of attribute access is much smaller than what the OP is > seeing: I have to take that back > $ cat iadd.py > class A(object): > def add_attr(self): > self.x = 0 > for i in xrange(100000): > self.x += 1 > def add_local(self): > x = 0 > for i in xrange(100000): > x += 1 > > add_local = A().add_local > add_attr = A().add_attr > $ python2.5 -m timeit -s 'from iadd import add_local' 'add_local()' > 10 loops, best of 3: 21.6 msec per loop > $ python2.5 -m timeit -s 'from iadd import add_attr' 'add_attr()' > 10 loops, best of 3: 52.2 msec per loop Iddo, adding integers is not a good model for the effect you are seeing. Caching, while happening on the OS-level isn't, either. As already mentioned in this thread there is a special optimization for some_string += another_string in the Python C-source. This optimization works by mutating on the C-level the string that is immutable on the Python-level, and is limited to cases where there are no other names referencing some_string. The statement self.s += t is executed internally as tmp = self.s [1] tmp += t [2] self.s = tmp [3] where tmp is not visible from the Python level. Unfortunately after [1] there are two references to the string in question (tmp and self.s) so the optimization cannot kick in. Peter From tedlandis at gmail.com Thu Jun 14 13:37:36 2007 From: tedlandis at gmail.com (Ted) Date: Thu, 14 Jun 2007 17:37:36 -0000 Subject: OS X install confusion In-Reply-To: <6b03b$46717b5e$4275d90a$18801@FUSE.NET> References: <1hzp0kw.4i0y5i1cqnlwoN%johnmfisher@comcast.net> <6b03b$46717b5e$4275d90a$18801@FUSE.NET> Message-ID: <1181842656.810802.24810@x35g2000prf.googlegroups.com> On Jun 14, 1:31 pm, Kevin Walzer wrote: > John Fisher wrote: > > Hi Groupies, > > > I have an Intel Macbook running OS X 10.4. > > > It came installed with Python 2.3.5. I have since installed MacPython > > with version 2.4.4, cool. > > > When I open a bash terminal session and type python, it brings up > > version 2.3.5. If I type IDLE it brings up version 2.4.4. > > > My question: what do I have to do to get it to bring up 2.4.4 with the > > "python" command? > > > Thanks for bringing light to my ignorance. > > > JF > > Sounds like a path problem. Apple's system Python is installed in > /usr/bin. Your installation is probably in /usr/local/bin. Edit your > profile or use the full path. > > -- > Kevin Walzer > Code by Kevinhttp://www.codebykevin.com The default python on tiger (2.3.5) is sym-linked to /usr/bin/python and /usr/bin/pythonw. I found it easier to relink to the new installation path. This also leaves /usr/bin/python23 and /usr/bin/pythonw23 still linked to the original version if you want to quickly check something. Cheers, Ted From bruno.42.desthuilliers at wtf.websiteburo.oops.com Wed Jun 6 07:59:09 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Wed, 06 Jun 2007 13:59:09 +0200 Subject: *Naming Conventions* In-Reply-To: <1181057170.894940.320890@o5g2000hsb.googlegroups.com> References: <1180909218.939713.112010@q69g2000hsb.googlegroups.com> <1180990280.960271.235550@h2g2000hsg.googlegroups.com> <1181057170.894940.320890@o5g2000hsb.googlegroups.com> Message-ID: <4666a180$0$19740$426a34cc@news.free.fr> Ninereeds a ?crit : > Google Groups appears to have thrown away my original reply, so sorry > if this appears twice... > > On Jun 4, 9:51 pm, "bruno.desthuilli... at gmail.com" > wrote: > >> 'i' and 'j' are the canonical names for for loops indices in languages >> that don't support proper iteration over a sequence. Using them for >> the iteration variable of a Python for loop (which is really a >> 'foreach' loop) would be at best confusing. > > Without wanting to start a religious war, I disagree. > > In practice, I believe most programmers associate those short names > with pretty much any loop > > variable, irrespective of data type, based primarily on the simple > fact that it's looping > > over a set of values whose meaning is obvious from context. That > declaration is made after > > decades of working with other peoples code as well as my own. The fact that a bad practice is a common practice is by no mean an excuse for promoting this bad practice. FWIW, Python as a very strong philosophy when it comes to readability, and I think it's the first time I see such a naming horror in Python. > > Anyway, why should 'indexes' always be numeric... Because that's part of the commonly admitted definition in the context ? In a dict, it's named a 'key', not an index. And the idiomatic shortcut is 'k', not 'i'. (snip) >> since the use of 'self' is mandatoy. > > That is true, making 'm' prefixes pointless in Python, but that's what > comes from working > > with many different language. Ah, the good old 'I can write basic in any language' syndrom... > You don't always keep them neatly > compartmentalised in your > > head. Habits can be very strong, and there is not always any strong > reason to try to break > them. I do not agree here, but that's another point. The problem is that you are advertising a totally non-pythonic convention on c.l.py. Your post will be archived for years, and some newbie may find it and follow your bad advises. Please keep such advises for where they are appropriate. > Which is why you will still occasionally see 'm' prefixes in > Python code. Never seen such a thing in 7 years of Python programming, and believe me I've read a *lot* of Python code. >> 1/ parameters names *are* local > > As they are in C and C++. The relation between the name and the named object are somewhat different in Python. >> 2/ pythonic methods and functions tends to be short, so you usually >> know which names are params. > > Well written functions and methods in any language tend to be short, For a somewhat different definition of "short". A "short" C functions is commonly tens of lines long - which, by Python standards, starts to become a "too long" function. >> Python has a pretty good support for computed attributes (look for >> 'property'), so you don't need explicit getters/setters. > > I may not use Python as my first and only language, but I have been > using it since version > > 1.4 Then you beat me !-) (started with 1.5.2) > and I am perfectly aware of properties in Python, as I am in other > languages. I am aware, > > for example, that they are relatively new additions to the language, > that they are not used > > in a lot of code, and that you still need named getter and setter > functions to redirect the > > property access to even if these names are only referred to in the > property definition. class SomeClass(object): @apply def some_property(): def fget(self): return self._somevalue def fset(self, newvalue): self._somevalue = newvalue return property(**locals()) Yes, true, the getter and the setter are named. But here, you don't even have to worry a millisecond about how to name them. > All of which is mostly besides the point. More and more programmers > are multilingual these > days, So am I. > and scripting languages such as Python are more likely second > languages than first. 'second' by usage frequency or by learning order ? > Having a hard rule that conventions from one language should never > leak into another, "never" ? Python stole almost anything - naming convention included - from other languages. It's not a matter of "purity", it's a matter of filtering what makes sens and what doesn't. > are common in many languages. Thorsten was having difficulty in > finding distinct names, and I > described a common naming convention that is often useful for this. I > don't think I was wrong > to do that. See my comments above. If these conventions are totally alien to Python (and have already been abandonned/rejected by people with similar background as yours - strange enough, a lot of people here are C, C++ or Java coders too), then as far as I'm concerned, yes, you are wrong to advertise them here. Call me a purist if you want... (and please don't take my remarks as a personal offense - it's just that I happen to be have *very* strong opinions on some points). From bbxx789_05ss at yahoo.com Sun Jun 3 02:25:49 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: Sat, 02 Jun 2007 23:25:49 -0700 Subject: How to control the creation of an instance? In-Reply-To: <1180851453.441872.107890@k79g2000hse.googlegroups.com> References: <1180851453.441872.107890@k79g2000hse.googlegroups.com> Message-ID: <1180851949.266727.272980@q69g2000hsb.googlegroups.com> On Jun 3, 12:17 am, 7stud wrote: > On Jun 2, 10:31 pm, lialie wrote: > > > > > Hi, > > > suppose i have a free_object list[Sample1, Smaple2....]. when create a > > new object sample(*args, **kwds), if free_object_list isn't empty, just > > pop one from free_object_list instead of creating a new instance. > > > any way to do this? > > > I do some work as follows: > > > class Sample(object): > > used_object = [] > > free_object = [] > > > def __init__(self, *args, **kwds): > > pass > > > def __new__(self, *args, **kwds): > > if Sample.free_object: > > obj = Sample.free_object.pop(0) > > else: > > obj = object.__new__(Sample, *args, **kwds) > > Sample.used_object.append(obj) > > return obj > > > ######## still get a new instance :( > > > def Release(self): > > Sample.used_object.remove(self) > > Sample.free_object.append(self) > > return True > > This seems to work for me: > > import collections > > class Sample(object): > > free_objects = collections.deque() > used_objects = [] > > def __new__(cls, *args, **kwds): > if not Sample.free_objects: > temp = object.__new__(Sample, args, kwds) > Sample.used_objects.append(temp) > return temp > else: > return Sample.free_objects.popleft() > > def __init__(self, *args, **kwds): > self.args = args > self.kwds = kwds > > def release(self): > Sample.used_objects.remove(self) > Sample.free_objects.append(self) > > s1 = Sample(10, name="Bob") > print s1 > print s1.args > print s1.kwds > > s2 = Sample("red", name="Bill") > print s2 > print s2.args > print s2.kwds > > s1.release() > s3 = Sample("blue", name="Tim") > print s3 > print s3.args > print s3.kwds Oops. This line: > temp = object.__new__(Sample, args, kwds) should be: temp = object.__new__(cls, args, kwds) although it would seem that cls is always going to be Sample, so I'm not sure what practical difference that makes. From __peter__ at web.de Mon Jun 4 03:41:23 2007 From: __peter__ at web.de (Peter Otten) Date: Mon, 04 Jun 2007 09:41:23 +0200 Subject: int vs long References: <1180839659.196587.194200@p77g2000hsh.googlegroups.com> <7xr6otiv4l.fsf@ruckus.brouhaha.com> <1180895701.813483.326780@k79g2000hse.googlegroups.com> <7xabvgj33p.fsf@ruckus.brouhaha.com> <1hz4uas.7jeyyu192pb8tN%aleax@mac.com> Message-ID: Marc 'BlackJack' Rintsch wrote: > In <1hz4uas.7jeyyu192pb8tN%aleax at mac.com>, Alex Martelli wrote: > >> Paul Rubin wrote: >> >>> Dan Bishop writes: >>> > If you ever do, it's trivial to write your own enumerate(): >>> > def enumerate(seq): >>> > index = 0 >>> > for item in seq: >>> > yield (index, item) >>> > index += 1 >>> >>> That's a heck of a lot slower than the builtin, and if you're running it >>> often enough for sys.maxint to be an issue, you may care about the >>> speed. >> >> Perhaps itertools.izip(itertools.count(), seq) might be faster (haven't >> timed it, but itertools tends to be quite fast). This approach is indeed much faster than the hand-crafted generator (10 vs 240% slowdown on my machine compared to the builtin) > I think correct is more important than fast. `itertools.count()` has the > same issues that `enumerate()`: > >>>> from itertools import count >>>> from sys import maxint >>>> c = count(maxint) >>>> c.next() > 2147483647 >>>> c.next() > -2147483648 > > What I find most disturbing here, is that it happens silently. I would > have expected an exception instead of the surprise. This is fixed in Python2.5: >>> from itertools import count >>> import sys >>> c = count(sys.maxint) >>> c.next(), c.next() (2147483647, 2147483648L) Peter From hg at nospam.org Sat Jun 16 11:33:39 2007 From: hg at nospam.org (hg) Date: Sat, 16 Jun 2007 10:33:39 -0500 Subject: Looking for a wxPython GUI builder References: Message-ID: Dick Moores wrote: > How about SPE? > > Any others? > > And which ones do people > actually use? Commercial or Freeware. > > Thanks, > > Dick Moores I use wxDesigner: http://www.roebling.de/ hg From aleax at mac.com Thu Jun 28 01:53:25 2007 From: aleax at mac.com (Alex Martelli) Date: Wed, 27 Jun 2007 22:53:25 -0700 Subject: PEP 3107 and stronger typing (note: probably a newbie question) References: <1182369568.941307.316260@p77g2000hsh.googlegroups.com> <5dveb4F360un0U1@mid.individual.net> <467a9209$0$22165$426a74cc@news.free.fr> <1182858785.886469.93060@n60g2000hse.googlegroups.com> <46824d8d$0$2324$426a74cc@news.free.fr> <46826e38$0$2818$426a74cc@news.free.fr> Message-ID: <1i0e1i4.uu1b912brmm8N%aleax@mac.com> John Nagle wrote: > PEP 3107 is static typing without enforcement, which is not a good thing. Wrong: PEP3107 is a syntax for adding arbitrary metadata annotations (so that said annotations don't get squished where they don't belong, such as decorators or docstrings, as they used to be in 2.*). The PEP itself offers a good example that should be vastly sufficient to destroy the "is static typing" notion: def compile(source: "something compilable", filename: "where the compilable thing comes from", mode: "is this a single statement or a suite?"): how do you get from that example to "PEP 3107 is static typing"? What an absurd, illogical leap. Here, it's being used to provide "per-argument docstrings" which a pydoc-like system could access as compile.func_annotation['source'] and the like, and format as it likes best. Type annotations (not necessarily for checking -- third party libraries are free to provide completely different semantics, such as adaptation) is another possible use, and Pythonistas' creativity may well supply many, many others. Alex From sjmachin at lexicon.net Sun Jun 10 06:40:24 2007 From: sjmachin at lexicon.net (John Machin) Date: Sun, 10 Jun 2007 20:40:24 +1000 Subject: read xml file from compressed file using gzip In-Reply-To: <1181470082.977493.62960@a26g2000pre.googlegroups.com> References: <1181278784.312152.99910@r19g2000prf.googlegroups.com> <466AE729.8070602@web.de> <1181452004.347078.241840@q19g2000prn.googlegroups.com> <466BC7CC.1080709@lexicon.net> <1181470082.977493.62960@a26g2000pre.googlegroups.com> Message-ID: <466BD518.7020006@lexicon.net> On 10/06/2007 8:08 PM, flebber wrote: > > Thanks that was so helpful to see how to do it. I have read a lot but > it wasn't sinking in, and sometimes its better to learn by doing. IMHO it's always better to learn by: read some, try it out, read some, ... > Some > of the books I have read just seem to go from theory to theory with > the occasional example ( which is meant to show us how good the author > is rather than help us). Well, that's the wrong sort of book for learning a language. You need one with little exercises on each page, plus a couple of bigger ones per chapter. It helps to get used to looking things up in the manual. Compare the description in the manual with what's in the book. > > For the record > >>>> ## working on region in file /usr/tmp/python-F_C5sr.py... > ['mimetype', 'maindata.xml'] > File Name > Modified Size > mimetype 2007-05-27 > 20:36:20 17 > maindata.xml 2007-05-27 > 20:36:20 10795 >>>> print len(xml_string) > 10795 >>>> for line in xml_string: > print line > ... ... > < > ? > x > m > l > > v > e > r > s > i.....(etc ...it went for a while) Yup. At a rough guess, I'd say it printed 10795 lines. So now you've learned by doing it what for x in a_string: does :-) I hope you've also learned that "xml_string" was a good name and "line" wasn't quite so good. > > and > >>>> lines = xml_string.splitlines() Have you looked up splitlines in the manual? >>>> print len(lines) > 387 >>>> print len(lines[0]) > 38 >>>> for line in lines: > ... print line > File "", line 2 > print line > ^ > IndentationError: expected an indented block >>>> for line in lines: > print line > After you fixed your indentation error, did it look like what you expected to find? Cheers, John From nick at craig-wood.com Mon Jun 18 18:30:04 2007 From: nick at craig-wood.com (Nick Craig-Wood) Date: Mon, 18 Jun 2007 17:30:04 -0500 Subject: avoid script running twice References: <4676AB35.7060500@chamonix.reportlab.co.uk> <9afea2ac0706181248l6bdd1606x2a3916609f6d4c14@mail.gmail.com> Message-ID: Jeff McNeil wrote: > I've got a rather large log processing job here that has the same > requirement. I process and sort Apache logs from an 8-way cluster. I > sort and calculate statistics in 15-minute batch jobs. Only one copy > should run at once. > > I open a file and lock it via something like this: > > import fcntl > > fhandle = file("ourlockfile.txt", "w") > > try: > fcntl.lockf(fhandle.fileno(), fcntl.LOCK_EX|fcntl.LOCK_NB) > except IOError, e: > if e.errno == errno.EAGAIN: > print >>sys.stderr, "exiting, another copy currently running" > else: > raise > > I've got it wrapped in a 'FileBasedLock' class that quacks like Lock > objects in the threading module. That is the traditional unix locking method. Note that it may not work if you are writing the lock file to an NFS mount! Traditionally you write your os.pid() to the file also. You can then send a signal to the running copy, detect stale lock files etc. -- Nick Craig-Wood -- http://www.craig-wood.com/nick From michele.simionato at gmail.com Sat Jun 23 11:58:26 2007 From: michele.simionato at gmail.com (Michele Simionato) Date: Sat, 23 Jun 2007 15:58:26 -0000 Subject: Python plain-text database or library that supports joins? In-Reply-To: <1182532691.182581.110940@m37g2000prh.googlegroups.com> References: <1182532691.182581.110940@m37g2000prh.googlegroups.com> Message-ID: <1182614306.671745.269500@u2g2000hsc.googlegroups.com> On Jun 22, 7:18 pm, felciano wrote: > Hello -- > > Is there a convention, library or Pythonic idiom for performing > lightweight relational operations on flatfiles? I frequently find > myself writing code to do simple SQL-like operations between flat > files, such as appending columns from one file to another, linked > through a common id. For example, take a list of addresses and append > a 'district' field by looking up a congressional district from a > second file that maps zip codes to districts. Have you looked at itools? http://www.ikaaro.org/itools#itools.csv HTH, Michele Simionato From tjreedy at udel.edu Wed Jun 20 23:22:49 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 20 Jun 2007 23:22:49 -0400 Subject: PEP 3107 and stronger typing (note: probably a newbie question) References: <20070620185337.GA22299@slaniel-laptop.itasoftware.com> Message-ID: "Stephen R Laniel" wrote in message news:20070620185337.GA22299 at slaniel-laptop.itasoftware.com... || Reading [1], I wonder: why isn't the compiler making better | use of (purely optional) type labeling? Why not make a compiler | directive so that | | a) it will check the types of all my arguments and return | values, and maybe even | b) do some type inference up the call stack? | | E.g., | | def( Class1 arg1, Class2 arg2, ..., ClassN argN ): | someStuff() | | would check the types of the arguments, whereas | | def( arg1, arg2, ..., argN): | someStuff() | | would not? I.e., if I *want* strong static | type-checking, why shouldn't I be able to get it? 1. Type checking arguments at compile time requires that the types of arguments be known at compile time. Since arguments often are either names or expressions using names, this would require that names be typed and that all assigments to names be type-checked. In other words, static typing pretty much all the way. 2. Python has multiple implementations. Any requirement such as this would be a requirement on all. It is possible that there will be some implementation that does something of what you want while the others continue as they are. Or that there will be third-party add-ons (like psyco today). 3. There are multiple possible uses of type annotations: documentation, speed, error checking, and maybe others yet to be thought of. Mandating any particular use would be a burden to anyone only interested in other uses. As an old-timer, I also do not initially see the point of annotation with no (required) effect. But then I realized point 3 above. I believe that the statement you interpreted as 'forbidding' static typing was Guido's promise that annotations will *not* be a step towards turning Python into something else -- a staticly typed language. That is important to the many people who use Python *because* it is dynamically and not statically typed and who consider that a net benefit. Terry Jan Reedy From Allen.Chenal at gmail.com Mon Jun 11 23:09:30 2007 From: Allen.Chenal at gmail.com (Allen) Date: Mon, 11 Jun 2007 20:09:30 -0700 Subject: Set PyObject value from C extension Message-ID: <1181617770.268753.70660@j4g2000prf.googlegroups.com> I have the PyObject pointers, and want to set different type of values to them. For example, INT8 nValue1 = 0; INT16 nValue2 = 1; FLOAT32 fValue = 1.0f; PyObject* var1 <= nValue1 PyObject* var2 <= nValue2 PyObject* var3 <= nValue3 How to do it? Regards, Allen Chen From mail at microcorp.co.za Sat Jun 2 04:20:51 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Sat, 2 Jun 2007 10:20:51 +0200 Subject: Python Pop Quiz References: <1180751587.951837.191480@h2g2000hsg.googlegroups.com> Message-ID: <012901c7a4ef$4482a4a0$03000080@hendrik> wrote: > 7. How many Z80 assembly language programmers does it take to equal > one Python guru? About one tenth of an assembly language programmer? I suppose it depends on how you define "equal". As for the bar room people - they are all people clinging to weird belief systems... - Hendrik From john at datavoiceint.com Wed Jun 13 16:45:34 2007 From: john at datavoiceint.com (HMS Surprise) Date: Wed, 13 Jun 2007 13:45:34 -0700 Subject: Goto In-Reply-To: References: <1181762459.749538.151730@z28g2000prd.googlegroups.com> Message-ID: <1181767534.367790.277080@x35g2000prf.googlegroups.com> Thanks folks! jh From steve at REMOVE.THIS.cybersource.com.au Sat Jun 23 22:55:44 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sun, 24 Jun 2007 12:55:44 +1000 Subject: is this a valid import sequence ? References: <4f97$467c254d$d443bb3a$9522@news.speedlinq.nl> <137qo1egg4v1k04@corp.supernews.com> <1i0694u.1n6evsntoei0wN%aleax@mac.com> Message-ID: On Sat, 23 Jun 2007 17:51:17 -0700, Alex Martelli wrote: > Steven D'Aprano wrote: > >> On Sat, 23 Jun 2007 11:03:03 -0700, Scott David Daniels wrote: >> >> > The global statement in Write_LCD_Data is completely unnecessary. The >> > only time you need "global" is if you want to reassociate the global >> > name to another object (such as LCD = LCD + 1 or whatever). >> >> That's technically true, but declaring it with global makes the code >> self-documenting and therefore easier to read. >> >> It's never _wrong_ to use the global statement, even if it is strictly >> unnecessary for the Python compiler. > > So, repeat that global statement ninetyseven times -- that's not > "wrong", either, in exactly the same sense in which it's not "wrong" to > have it once -- the Python compiler will not complain. And by repeating > it over and over you make it less likely that a reader could miss it, so > it's even more "self-documenting" and "easier to read", right? No, repeating it ninety-seven times doesn't make it easier to read, it makes it *harder* to read, and I'm sure I don't need to explain why. > "Perfection is reached, not when there is no longer anything to > add, but when there is no longer anything to take away", as Antoine de > Saint-Exupery wrote. That's debatable. Why does Python have decorators when there was already a perfectly usable syntax for setting a method to function(method)? And let's not even mention x += 1 etc. > Since that global statement is utterly useless > (it's impossible to read and understand any substantial amount of Python > code without realizing that accessing a variable not locally assigned > means you're accessing a global, so the "self-documenting" character > claimed for that redundancy is quite fallacious), Sure, in the *specific* example given, the body of the function was so short that it would be a pretty poor developer who didn't know it was a global. But in a more substantial function, one using lots of variables, it might not be clear which were global and which weren't unless you studied the code, line-by-line. > it IS perfectly > suitable to take away, and so it's at least a serious imperfection. It > violates Occam's Razor, by multiplying entities (specifically > statements) without necessity. It's just about as bad as sticking a > semicolon at the end of every statement (to make it "self-documenting" > that the statement ends there), parentheses around the conditions in if > and while statements and the argument in return statements (to make it > "self-documenting" where those expressions start and end), and a few > other less common ways to waste pixels, screen space, readers' attention > spans, and everybody's time. I'm not going to defend *any* of those practices. But I don't think explicitly stating that a name is global, even when strictly unnecessary, is in the same category. In practice, I wouldn't do so for a function that was as short as the one the Original Poster used. But consider also something like this: def func(): x, y = 1, 2 z = x + y # lots more code doing many things here # some of which involve w return z + w Let's pretend that there is sufficient code in there that it isn't obvious at a glance that w is a global, okay? There's a off-by-one error in the code, which we fix: def func(): x, y = 1, 2 z = x + y # lots more code doing many things here # some of which involve w w = w + 1 return z + w "UnboundLocalError". Oops. Now, I cheerfully admit that this scenario is contrived. Some people might even argue that it is good for newbies to run into this error sooner rather than later, but for those who don't think so, defensively inserting a global statement might help prevent the issue from coming up. I'm a big believer in letting newbies walk before running. I'd rather see beginner programmers over-use global than under-use it. You're welcome to disagree, but since UnboundLocalError seems to be one of the more perplexing errors newbies suffer from, I think it is better for them to avoid it until they've got a little more experience. -- Steven. From doug at alum.mit.edu Tue Jun 19 13:38:28 2007 From: doug at alum.mit.edu (Douglas Alan) Date: Tue, 19 Jun 2007 13:38:28 -0400 Subject: Python's "only one way to do it" philosophy isn't good? References: <1181368143.874341.273140@r19g2000prf.googlegroups.com> Message-ID: "Terry Reedy" writes: > The main point of my original post was that the quoted slam at Python was > based on a misquote of Tim Peters But it wasn't based on a "misquote of Tim Peters"; it was based on an *exact* quotation of Tim Peters. > and a mischaracterization of Python I find Sussman's criticism not to be a mischaracterization at all: I and others have previous mentioned in this very forum our desire to have (in an ideal world) a good syntax extension facility for Python, and when we've done so, we've been thoroughly pounced upon by prominent members of the Python community as just not understanding the true "Weltanschauung" of Python. This despite the fact that I have been happily and productively programming in Python for more than a decade, and the fact that Guido himself has at times mentioned that he's been idly considering the idea of a syntax extension facility. The reason given for why macros wouldn't gel with Python's Weltanschauung has typically been the "only one obvious way" koan, or some variant of it. > and that it was out-of-place in the quoted discussion of physics > methods and that it added nothing to that discussion and should > better have been omitted. *All of this has nothing to do with > Scheme.* I'm not sure what you're getting at. Gerry Sussman has a philosophy of language design that is different from Python's (at least as it is commonly expressed around here), and he was using an analogy to help illuminate what his differences are. His analogy is completely clear to me, and, I in fact agree with it. I love Python, but I think the "only one obvious way" philosophy may do more harm than good. It is certainly used, in my experience, at times, to attempt to squelch intelligent debate. > At the end, I added as a *side note* the irony that the purported author > was the co-developer of Scheme, another 'minimalist algorithm > language Sussman's statements are not ironic because Scheme is a language that is designed to be extended by the end-user (even syntactically), while keeping the core language minimal. This is a rather different design philosophy from that of Python. > (Wikipedia's characterization) with more uniform syntax than Python and > like Python, also with one preferred way to scan sequences (based on my > memory of Scheme use in the original SICP, co-authored by the same > purported quote author, and also confirmed by Wikipedia). There is no one preferred way to scan sequences in Scheme. In fact, if you were to take SICP at MIT, as I did when I was a freshman, you would find that many of the problem sets would require you to solve a problem in several different ways, so you would learn that there are typically a number of different reasonable ways to approach a problem. E.g., one of the first problem sets would have you implement something both iteratively and recursively. I recall another problem set where we had to find the way out of a maze first using a depth-first search and then using a breadth-first search. > | [Steele quote deleted] > | Do you now see how Scheme's syntax extension mechanism is relevant? > No. This just partly explains why Scheme gets away with being > minimalist. I explicitly referred to the core language as delivered > and as used in SICP. I suggest that you haven't yet grokked the Weltanschauung of Scheme. Scheme aficionados would not typically insist that a proposed language feature is not good because it violates anything like an "only one obvious way" rule. Rather they would argue that if it can be implemented as fuctions and/or macros, then it *should* be implemented that way, rather than polluting the core language. The new facility should then be included in a library. |>oug From bj_666 at gmx.net Wed Jun 27 03:57:58 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Wed, 27 Jun 2007 09:57:58 +0200 Subject: XML from SQL result References: Message-ID: In , Marcin St?pnicki wrote: > Anyway: I've got the SQL query which returns: > > col1 | col2 | col3 > -----+------+----- > a | a10 | b20 > a | a10 | b30 > a | a20 | b30 > > I need to generate the following: > > > > > > > > > > > > > Using Elementree it's not a problem when returned data is "flat", not > hierarchical. However, that's not the case. > > Questions: > > 1) (I'll ask that on PostgreSQL group too) I use PostgreSQL. I understand > that in order to achieve what I want directly from RDBMS I need SQL/XML > language support which will be included in 8.3 which is not yet available. That question sounds more like a statement. :-) > 3) I can generate series of select queries based on previous queries, but > I can't imagine there isn't a better solution. If the data can be queried sorted like shown above, should be possible to iterate over it and use `itertools.groupby` and `elementtree.SimpleXMLWriter.XMLWriter` to generate the XML on the fly: import sys from itertools import groupby from operator import itemgetter from elementtree.SimpleXMLWriter import XMLWriter first, second, third = map(itemgetter, xrange(3)) def main(): data = (('a', 'a10', 'b20'), ('a', 'a10', 'b30'), ('a', 'a20', 'b30')) writer = XMLWriter(sys.stdout) writer.start('document') for value, rows in groupby(data, first): writer.start('tag1', col1=value) for value, rows in groupby(rows, second): writer.start('tag2', col2=value) for value in imap(third, rows): writer.element('tag3', col3=value) writer.end('tag2') writer.end('tag1') writer.end('document') Ciao, Marc 'BlackJack' Rintsch From len-l at telus.net Tue Jun 19 18:22:09 2007 From: len-l at telus.net (Lenard Lindstrom) Date: Tue, 19 Jun 2007 22:22:09 GMT Subject: determine 32 or 64 bit architecture with python 2.2 In-Reply-To: <1182263518.734695.327620@w5g2000hsg.googlegroups.com> References: <1182251830.835902.78210@n2g2000hse.googlegroups.com> <1182256124.727593.93360@z28g2000prd.googlegroups.com> <1182263518.734695.327620@w5g2000hsg.googlegroups.com> Message-ID: David Rushby wrote: > On Jun 19, 4:28 pm, John Machin wrote: >> On Jun 19, 9:17 pm, Kai Rosenthal wrote: >> >>> Hello, >>> how can I determine the architecture (32 or 64bit) with python 2.2 on >>> Windows or Unix (AIX, Solaris) OS, without the modul platform? >>> Thanks for your hints, Kai >> What happens when you fire up a 64-bit Python and type >> import sys; sys.maxint >> at it? > > That's not suitable, because of the differences between LP64 and LLP64 > (http://en.wikipedia.org/wiki/64-bit#64-bit_data_models ). > > Try > python -c "import struct; print struct.calcsize('P')" > instead. That calculates the size of a pointer. > How about: tuple.__itemsize__ since each tuple item is a pointer. -- Lenard Lindstrom From aneesh.goel.rbtx at gmail.com Mon Jun 11 20:58:05 2007 From: aneesh.goel.rbtx at gmail.com (aneesh.goel.rbtx at gmail.com) Date: Mon, 11 Jun 2007 17:58:05 -0700 Subject: pyExcelerator and multiple worksheets Message-ID: <1181609885.434543.194560@i13g2000prf.googlegroups.com> I'm using pyExcelerator to take a folder of CSV files and create Excel workbooks for all of them, then generate an Excel workbook with the data from all of them. Everything up until here works great; next, I make a second worksheet on the last workbook which has summary details regarding the previous worksheet. Here I run into a problem. The Excel form AVERAGE(Data!E5:E3053) where Data is the name of the worksheet being referenced (Summary is the name of the worksheet where the formula is entered) isn't recognized when I call Formula(). Currently I'm just writing the string =AVERAGE(Data!E5:E3053) into the cell, but this doesn't get automatically evaluated; there are multiple instances of this formatting in use and when used with a larger source folder, evaluating each cell by hand becomes a significant problem. Without any documentation for pyExcelerator I turned to the examples provided, but none of them seemed to use cross-worksheet formulas. Does anybody know how to fix this, or alternatively know a different package I could use? I found xlrd but as that is read-only it doesn't seem to solve the problem, unless there's some insane and creative way to use xlrd and pyExcelerator together to solve this. Thanks in advance! --Aneesh From sjmachin at lexicon.net Fri Jun 22 08:59:36 2007 From: sjmachin at lexicon.net (John Machin) Date: Fri, 22 Jun 2007 05:59:36 -0700 Subject: Packing a simple dictionary into a string - extending struct? In-Reply-To: <467B7585.5040801@pytex.org> References: <467B7585.5040801@pytex.org> Message-ID: <1182517176.444776.251800@i13g2000prf.googlegroups.com> On Jun 22, 5:08 pm, Jonathan Fine wrote: > Jonathan Fine wrote: > > Thank you for this suggestion. The growing adoption of JSON in Ajax > > programming is a strong argument for my using it in my application, although > > I think I'd prefer something a little more binary. > > > So it looks like I'll be using JSON. > > Well, I tried. But I came across two problems (see below). > > First, there's bloat. For binary byte data, one average one > character becomes just over 4. > > Second, there's the inconvenience. I can't simple take a > sequence of bytes and encode them using JSON. I have to > turn them into Unicode first. And I guess there's a similar > problem at the other end. > > So I'm going with me own solution:http://mathtran.cvs.sourceforge.net/mathtran/py/bytedict.py?revision=... > def unpack(bytes, unpack_entry=unpack_entry): '''Return dictionary gotten by unpacking supplied bytes. Both keys and values in the returned dictionary are byte-strings. ''' bytedict = {} ptr = 0 while 1: key, val, ptr = unpack_entry(bytes, ptr) bytedict[key] = val if ptr == len(bytes): break # That's beautiful code -- as pretty as a cane-toad. # Well-behaved too, a very elegant response to unpack(pack({})) # Try this: blen = len(bytes) while ptr < blen: key, val, ptr = unpack_entry(bytes, ptr) bytedict[key] = val return bytedict HTH, John From martin at v.loewis.de Fri Jun 22 00:36:10 2007 From: martin at v.loewis.de (=?UTF-8?B?Ik1hcnRpbiB2LiBMw7Z3aXMi?=) Date: Fri, 22 Jun 2007 06:36:10 +0200 Subject: Changing the names of python keywords and functions In-Reply-To: <87abusx3iz.fsf@benfinney.id.au> References: <1182452862.872909.206780@u2g2000hsc.googlegroups.com> <467ad90c$0$22151$9b622d9e@news.freenet.de> <87abusx3iz.fsf@benfinney.id.au> Message-ID: <467b51bb$0$23295$9b622d9e@news.freenet.de> >>> "<> OS"- (THIS IS MY IMAGINARY EXAMPLE OF KEYWORD), >>> my program must write this code in some user file, but my >>> program must read this command like: "import os".How >>> can I do something like that?? >> The keywords are listed in Grammar/Grammar. You need to edit >> this file, then recompile. > > To clarify, are you suggesting changing the source code of the Python > implementation and recompiling it? Correct. > If the keywords are changed in the Python executable, won't that break > the import of any Python module written for the standard keywords -- > such as many of those in the standard library? Most certainly, yes. > My understanding of the original poster's requirement was that the > keywords should be additional to, not replacement for, the existing > Python keywords. So he should make them additional in the grammar, too. It is entirely beyond me *why* the OP wants to do that, but changing the compiler would be the proper way of implementing that change. Regards, Martin From grflanagan at yahoo.co.uk Mon Jun 4 07:52:34 2007 From: grflanagan at yahoo.co.uk (Gerard Flanagan) Date: Mon, 04 Jun 2007 04:52:34 -0700 Subject: How to do this with groupby (or otherwise)? (Was: iterblocks cookbook example) In-Reply-To: <1180817235.383984.73520@n15g2000prd.googlegroups.com> References: <1180817235.383984.73520@n15g2000prd.googlegroups.com> Message-ID: <1180957954.635705.320340@p47g2000hsd.googlegroups.com> On Jun 2, 10:47 pm, Raymond Hettinger wrote: > On Jun 2, 10:19 am, Steve Howell wrote: > > > George Sakkis produced the following cookbook recipe, > > which addresses a common problem that comes up on this > > mailing list: > > ISTM, this is a common mailing list problem because it is fun > to solve, not because people actually need it on a day-to-day basis. > > In that spirit, it would be fun to compare several different > approaches to the same problem using re.finditer, itertools.groupby, > or the tokenize module. To get the ball rolling, here is one variant: > > from itertools import groupby > > def blocks(s, start, end): > def classify(c, ingroup=[0], delim={start:2, end:3}): > result = delim.get(c, ingroup[0]) > ingroup[0] = result in (1, 2) > return result > return [tuple(g) for k, g in groupby(s, classify) if k == 1] > > print blocks('the brown jumped', start='<', end='>') > > One observation is that groupby() is an enormously flexible tool. > Given a well crafted key= function, it makes short work of almost > any data partitioning problem. > Can anyone suggest a function that will split text by paragraphs, but NOT if the paragraphs are contained within a [quote]...[/quote] construct. In other words, the following text should yield 3 blocks not 6: TEXT = ''' Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Pellentesque dolor quam, dignissim ornare, porta et, auctor eu, leo. Phasellus malesuada metus id magna. [quote] Only when flight shall soar not for its own sake only up into heaven's lonely silence, and be no more merely the lightly profiling, proudly successful tool, playmate of winds, beguiling time there, careless and cool: only when some pure Whither outweighs boyish insistence on the achieved machine will who has journeyed thither be, in that fading distance, all that his flight has been. [/quote] Integer urna nulla, tempus sit amet, ultrices interdum, rhoncus eget, ipsum. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. ''' Other info: * don't worry about nesting * the [quote] and [/quote] musn't be stripped. Gerard From jarausch at skynet.be Tue Jun 19 09:01:36 2007 From: jarausch at skynet.be (Helmut Jarausch) Date: Tue, 19 Jun 2007 15:01:36 +0200 Subject: File processing - is Python suitable? In-Reply-To: <1182255317.327241.196330@n2g2000hse.googlegroups.com> References: <1182255317.327241.196330@n2g2000hse.googlegroups.com> Message-ID: <4677D3B0.2030706@skynet.be> ferrad wrote: > I have not used Python before, but believe it may be what I need. > > I have large text files containing text, numbers, and junk. I want to > delete large chunks process other bits, etc, much like I'd do in an > editor, but want to do it automatically. I have a set of generic > rules that my fingers follow to process these files, which all follow > a similar template. > > Question: can I translate these types of rules into programmatical > constructs that Python can use to process these files? Can Python do > the trick? I think that's one of the great strength of Python. Just some pointers http://gnosis.cx/TPiP/ http://www.egenix.com/products/python/mxBase/mxTextTools/ -- Helmut Jarausch Lehrstuhl fuer Numerische Mathematik RWTH - Aachen University D 52056 Aachen, Germany From gagsl-py2 at yahoo.com.ar Mon Jun 18 05:16:01 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 18 Jun 2007 06:16:01 -0300 Subject: Windows XMLRPC Service References: <1182137125.879556.319030@g37g2000prf.googlegroups.com> Message-ID: En Mon, 18 Jun 2007 00:25:25 -0300, escribi?: > I'm trying to serve up a simple XMLRPC server as a windows service. I > got it to run properly, I'm just not sure how to stop it properly. > Most of the documentation/examples I found for this was from forums, > so I'd love some links to relevant info also. Here's what I > have...taken from the cookbook with the xmlrpc server added: > > def __init__(self, args): > win32serviceutil.ServiceFramework.__init__(self, args) > # Create an event which we will use to wait on. > # The "service stop" request will set this event. > self.hWaitStop = win32event.CreateEvent(None, 0, 0, None) > > def SvcStop(self): > # Before we do anything, tell the SCM we are starting the stop > process. > self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) > > # quit the xmlrpc sever > self.server.quit() What is quit()? As the server may be processing a request I'd move any finalization code below, after exiting the while loop. > > # And set my event. > win32event.SetEvent(self.hWaitStop) > > def SvcDoRun(self): > # Serve up the XMLRPC forever > self.server = > SimpleXMLRPCServer.SimpleXMLRPCServer(("10.0.1.6", 8000)) > self.server.register_instance(MyClass()) > self.server.serve_forever() > > win32event.WaitForSingleObject(self.hWaitStop) The simplest solution is to replace serve_forever with a loop waiting on hWaitStop: while WaitForSingleObject(self.hWaitStop, 0)==WAIT_TIMEOUT: self.server.handle_request() Set the socket timeout to a reasonable value (you'll have to wait that time before exiting). Also, a ThreadingTCPServer may be better if you expect more than a request at a time. If you search past messages you may find other ways. -- Gabriel Genellina From twisted0n3 at gmail.com Mon Jun 11 22:53:54 2007 From: twisted0n3 at gmail.com (Twisted) Date: Tue, 12 Jun 2007 02:53:54 -0000 Subject: The Concepts and Confusions of Prefix, Infix, Postfix and Fully Functional Notations In-Reply-To: References: <1179936917.652372.24780@q69g2000hsb.googlegroups.com> <1180508453.226022.44230@q19g2000prn.googlegroups.com> <1181335574.107472.229370@x35g2000prf.googlegroups.com> <1181358616.792797.97720@k79g2000hse.googlegroups.com> <1181414625.121073.203940@g4g2000hsf.googlegroups.com> <0uHai.176367$nh4.13819@newsfe20.lga> <1181448558.120521.63250@g4g2000hsf.googlegroups.com> <0G_ai.1970$xg4.809@trnddc08> <1181525392.369255.138460@h2g2000hsg.googlegroups.com> <1181545345.788665.191690@q66g2000hsg.googlegroups.com> Message-ID: <1181616834.331070.179540@i38g2000prf.googlegroups.com> On Jun 11, 8:57 pm, Patricia Shanahan wrote: > I wrote a Perl script to process logic analyzer traces for some hardware > engineers. While I was out of the office, they found they needed to > process a new record type. They didn't want to delay their work until I > got back, and one of the EEs knew Perl, so he modified my script. > > The change was done correctly. It not only worked. Except for a couple > of comments calling my attention to the changes, it looked as though > the new record type had always been there. *blinks* Hallelujah! It's a miracle! Praise be the Lord! This must surely be a sign... a sign of the End Times. :P From gagsl-py2 at yahoo.com.ar Mon Jun 11 23:57:04 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 12 Jun 2007 00:57:04 -0300 Subject: Multiline lamba implementation in python. References: <1b0ce1b60706112002i761dc295x9ba9c4f589c41db1@mail.gmail.com> Message-ID: En Tue, 12 Jun 2007 00:02:37 -0300, Josh Gilbert escribi?: > I don't expect multiline lambdas to be added to Python. I'm not so sure > that > that's a bad thing. Regardless, isn't it possible to write your own > implementation of multiline lambdas as functions? Wouldn't that be a > win-win > for everyone? If you want to "implement multiline lambdas as functions"... why don't you use a plain old function? -- Gabriel Genellina From kf9150 at gmail.com Thu Jun 21 15:24:09 2007 From: kf9150 at gmail.com (kf9150 at gmail.com) Date: Thu, 21 Jun 2007 19:24:09 -0000 Subject: sqlite newbie questions Message-ID: <1182453849.251898.127630@d30g2000prg.googlegroups.com> Hello, I have a sqlite database table which has a table named "Transmittal". Before inserting a new record into the database, i'd like to perform some checking. How do i select all records with certain value (say "Smith") for a column (say "Last_Name")? Knowing almost nothing about SQL, i just selected everything and process the returned list. cur.execute('select * from Transmittal') records = cur.fetchall() Also, how do i delete records with certain value for centain column. I was thining of something like cur.execute('delete * from Transmittal where Last_Name=?', "Smith") but the syntax it's not correct. Thanks for your help. kelie From __peter__ at web.de Tue Jun 19 09:54:46 2007 From: __peter__ at web.de (Peter Otten) Date: Tue, 19 Jun 2007 15:54:46 +0200 Subject: File processing - is Python suitable? References: <1182255317.327241.196330@n2g2000hse.googlegroups.com> Message-ID: ferrad wrote: > I have not used Python before, but believe it may be what I need. > > I have large text files containing text, numbers, and junk. I want to > delete large chunks process other bits, etc, much like I'd do in an > editor, but want to do it automatically. I have a set of generic > rules that my fingers follow to process these files, which all follow > a similar template. > > Question: can I translate these types of rules into programmatical > constructs that Python can use to process these files? Can Python do > the trick? Yes, and if you are a non-programmer, the entry barrier for Python is as low as it can get. However, what a programming language treats as a rule is much stricter than what a human being might expect. For example, appending an 's' to the first word in a sentence is "easy" in Python, changing the subject's numerus to plural is "hard". Both are doable, but the less technical your rules are the harder they become to translate. You often have to compromise either by proofreading the results of any automated processing, or by having your program ask a human operator in the cases it can't decide upon. I recommend that you play around a bit in the interactive interpreter to get a feel for the kind of operations that are easily available on strings. Then write the processing rules into a script, and always start your conversion from the original data (of which you you have a backup in some locker), not some intermediate output. That way you can try processing without losing information in the data or about the process -- until you find the results acceptable. Make backups of your script, too, before you are trying something new. Peter From kyosohma at gmail.com Tue Jun 12 09:38:04 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Tue, 12 Jun 2007 06:38:04 -0700 Subject: Excel file interface for Python 2.3? In-Reply-To: References: Message-ID: <1181655484.742933.261800@j4g2000prf.googlegroups.com> On Jun 12, 8:01 am, "Hamilton, William " wrote: > I'm in need of a module that will let me create Excel workbooks from within > Python. Something like PyExcelerator, but it needs to work with Python 2.3. > (A third-party limitation that I have no control over.) Can anyone point me > to what I need? All my searches keep leading back to PyExcelerator. > > -- > -Bill Hamilton You can also use COM if you're on Windows, via PyWin32. Hammond's book talks about it a little here: http://www.oreilly.com/catalog/pythonwin32/chapter/ch12.html I also saw some information about this in Core Python Programming by Chun. Example code follows: import win32com.client as win32 def excel(): app = 'Excel' xl = win32.gencache.EnsureDispatch('%s.Application' % app) ss = xl.Workbooks.Add() sh = ss.ActiveSheet xl.Visible = True sleep(1) sh.Cells(1,1).Value = 'Python-to-%s Demo' % app sleep(1) for i in RANGE: sh.Cells(i,1).Value = 'Line %d' % i sleep(1) sh.Cells(i+2,1).Value = "Th-th-th-that's all folks!" ss.Close(False) xl.Application.Quit() Admittedly, COM is kind of confusing. But it's there if you need it. Mike From exarkun at divmod.com Fri Jun 8 17:12:46 2007 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Fri, 8 Jun 2007 17:12:46 -0400 Subject: How to use TLS lite In-Reply-To: <114037.93309.qm@web54507.mail.re2.yahoo.com> Message-ID: <20070608211246.30678.124985054.divmod.quotient.12810@ohm> On Sat, 9 Jun 2007 05:58:41 +1000 (EST), Mr SZ wrote: >I'm using tls lite to send mail using gmail's smtp.This is what I've done: > >from tlslite.api import * >import tlslite.integration.SMTP_TLS >connection= tlslite.integration.SMTP_TLS.SMTP_TLS('smtp.gmail.com',587) >connection.set_debuglevel(1) >msg = "Subject:Testing \n Hello" >connection.starttls('emailid at gmail.com','password') >connection.sendmail("from at gmail.com","to at gmail.com",msg) > >In return this is what I get: > >wiki at wiki-desktop:~/Desktop$ python smtp2.py >send: 'STARTTLS\r\n' >reply: '503 5.5.1 EHLO/HELO first m75sm2193378wrm\r\n' >reply: retcode (503); Msg: 5.5.1 EHLO/HELO first m75sm2193378wrm >send: 'ehlo [127.0.1.1]\r\n' >reply: '250-mx.google.com at your service, [59.93.118.190]\r\n' >reply: '250-SIZE 28311552\r\n' >reply: '250-8BITMIME\r\n' >reply: '250-STARTTLS\r\n' >reply: '250 ENHANCEDSTATUSCODES\r\n' >reply: retcode (250); Msg: mx.google.com at your service, [59.93.118.190] >SIZE 28311552 >8BITMIME >STARTTLS >ENHANCEDSTATUSCODES >send: 'mail FROM: size=23\r\n' >reply: '530 5.7.0 Must issue a STARTTLS command first m75sm2193378wrm\r\n' >reply: retcode (530); Msg: 5.7.0 Must issue a STARTTLS command first m75sm2193378wrm >send: 'rset\r\n' >reply: '250 2.1.0 Flushed m75sm2193378wrm\r\n' >reply: retcode (250); Msg: 2.1.0 Flushed m75sm2193378wrm >Traceback (most recent call last): > File "smtp2.py", line 7, in > connection.sendmail("email at gmail.com","to at gmail.com",msg) > File "/usr/lib/python2.5/smtplib.py", line 684, in sendmail > raise SMTPSenderRefused(code, resp, from_addr) >smtplib.SMTPSenderRefused: (530, '5.7.0 Must issue a STARTTLS command first m75sm2193378wrm', 'email at gmail.com') > >Where am I going wrong? > Notice that in response to the STARTTLS you sent, you received this response: 503 5.5.1 EHLO/HELO first m75sm2193378wrm The command was rejected and ignored and TLS was not initiated. You need to send the STARTTLS later. Jean-Paul From ladynikon at gmail.com Mon Jun 25 16:59:59 2007 From: ladynikon at gmail.com (Danyelle Gragsone) Date: Mon, 25 Jun 2007 16:59:59 -0400 Subject: Installing python under the linux In-Reply-To: <1182802267.969628.156960@o61g2000hsh.googlegroups.com> References: <1182800785.231113.199750@n2g2000hse.googlegroups.com> <1182802267.969628.156960@o61g2000hsh.googlegroups.com> Message-ID: <59f9c5160706251359g37b6536anf19b3475ec84951a@mail.gmail.com> Hi, Yeah .. if its ubuntu then you have python already installed. I would suggest that you start reading the documentation on your distro. How did you get your distro if you don't know what it is? That concerns me a bit. Ubuntu has alot of documentation as well as a help channel on irc. irc.freenode.net #ubuntu. You can pull up alot of documentation by just typing "ubuntu documentation" or "ubuntu guides" in google. good luck! Danyelle On 6/25/07, vedrandekovic at v-programs.com wrote: > > Danyelle Gragsone je napisao/la: > > Greetings, > > > > Python is usally already installed on most distros. In a terminal > > window type "python" to see if something happens. Also please provide > > what distro you are running. > > > > Danyelle > > > > On 6/25/07, vedrandekovic at v-programs.com wrote: > > > Hello, > > > > > > I have problem with installing Python on the Linux platform.Can you > > > tell me step by step how can I install > > > python on linux ( please detailed ) , because I don't know anything > > > about linux and I really don't understand > > > python documentation about installing python on linux. > > > > > > > > > > > > Thanks!!! > > > > > > -- > > > http://mail.python.org/mailman/listinfo/python-list > > > > > Helo, > > Probably my distro is "ubuntu" <--- I don't what is it, and ' want > install/build python from source > > -- > http://mail.python.org/mailman/listinfo/python-list > From rpdooling at gmail.com Thu Jun 7 13:33:27 2007 From: rpdooling at gmail.com (BartlebyScrivener) Date: Thu, 07 Jun 2007 17:33:27 -0000 Subject: MySQL InterfaceError In-Reply-To: References: <001e01c7a6f3$e687ed40$0f01a8c0@desktop9> <002901c7a6f4$f55e56a0$0f01a8c0@desktop9> <008e01c7a7a5$ddaf8ae0$0f01a8c0@desktop9> <163f0ce20706061650k5708926ck449c53bf0bb39a81@mail.gmail.com> <016a01c7a897$2fbd4650$0f01a8c0@desktop9> <163f0ce20706062024o556038f5te71ddacfc64c473e@mail.gmail.com> Message-ID: <1181237607.017080.303990@o5g2000hsb.googlegroups.com> On Jun 7, 10:09 am, "Joe" wrote: > > And, yes, printing the error message returns absolutely nothing. The tuple > following InterfaceError is both the error code and message. Unfortunately, > it will only give me (0, '') which isn't much help. > I'm on Google groups and can't see the first part of your original message, so don't know what query you are using. But I get that interface error when I attempt to interpolate values from something other than a tuple. E.g. SELECT item from table where item like %s If you try to use a string, say, instead of a string in a tuple, you'll get an interface error. That's the only time I've gotten it. rd > Thanks again! > > Jough From wildemar at freakmail.de Fri Jun 1 17:27:58 2007 From: wildemar at freakmail.de (Wildemar Wildenburger) Date: Fri, 01 Jun 2007 23:27:58 +0200 Subject: Observer-Pattern by (simple) decorator Message-ID: <46608F5E.9010904@freakmail.de> Hello folks :) This has got to be an FAQ, but somehow I can't seem to find an answer that I understand ... I thought: I'll just write a decorator that lets me react to method calls easily (the ever so popular observer-pattern). I've looked at some recepies, but I just don't get them (I'm feeling kinda dumb today, sorry). What I'd *like* to do is this: def observable(func): # magic code class SomeActor(object): @observable def meth(self, foo): print foo def callback(instance): print "Yippie, I've been called on", instance instance.bar = True sa = SomeActor() sa.meth.add_callback(callback) # now this sa.meth("I'm the boring old argument") # I would like to result in this >>> I'm the boring old argument >>> Yippie, I've been called on <__main__.SomeActor object at 0xb7e8b40c> # or so This is more complicated than expected mainly for two reasons: * I can't find a way to pass the proper 'instance' argument to callback, that is, I don't know how to retrieve the instance that meth() was called on, because the observable decorator only gets the *function* object but not the *method*. (I hope this was clear enough) * Also, I don't see how I could add the add_callback() method to the meth object. That doesn't seem possible. I can add it to meth's function object just fine in the definition of observable, but I thats not what I really want. This is probably just a cosmetic issue because I don't like the idea of calling sa.meth.im_func.add_callback(callback). Any ideas? Would be great. /W From a-alpha at otenet.gr Mon Jun 11 00:52:24 2007 From: a-alpha at otenet.gr (D - A - T - I - N - G) Date: Mon, 11 Jun 2007 07:52:24 +0300 Subject: Sharon Stone - Anna Kournikova Lindsay lohan Message-ID: Sharon Stone - Anna Kournikova Lindsay lohan ------------------------ search engines + cams ------------------------ www.alphasearch.gr www.alphasearch.ru -------------- next part -------------- An HTML attachment was scrubbed... URL: From horpner at yahoo.com Tue Jun 5 09:00:15 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Tue, 05 Jun 2007 13:00:15 GMT Subject: *Naming Conventions* References: <1180909218.939713.112010@q69g2000hsb.googlegroups.com> <1180990280.960271.235550@h2g2000hsg.googlegroups.com> Message-ID: On 2007-06-04, Michael Hoffman wrote: > Wildemar Wildenburger wrote: >> While that is true, I guess it is commonplace to use i, j, k >> and n (maybe others) in constructs like >> >> for i in range(len(data)): >> do_stuff(data[i]) >> >> Or should the good python hacker do that differently? Hope not >> ;). > > Well, yes, I would do: > > for item in data: > do_stuff(item) > > or, if using enumerate: > > for item_index, item in enumerate(data): > do_stuff(item_index, item) > > I agree with Bruno that i and j should be used only for > indices, but I'm usually less terse than that. I find i and j preferable to overly generic terms like "item." -- Neil Cerutti From bruno.42.desthuilliers at wtf.websiteburo.oops.com Wed Jun 20 03:24:09 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Wed, 20 Jun 2007 09:24:09 +0200 Subject: static python classes ? In-Reply-To: <1182257803.087704.3210@q75g2000hsh.googlegroups.com> References: <1182254405.901790.189190@p77g2000hsh.googlegroups.com> <1182255355.491845.44770@i13g2000prf.googlegroups.com> <1182257803.087704.3210@q75g2000hsh.googlegroups.com> Message-ID: <4678d60e$0$2425$426a74cc@news.free.fr> Tom Gur a ?crit : >> Look for @staticmethod inhttp://docs.python.org/lib/built-in-funcs.html >> >> Example: >> class C: >> @staticmethod >> def f(arg1, arg2, ...): ... > > > Oops, sorry for the confusion - I've actually meant a static method, > and Gerald's answer works fine. FWIW, staticmethods in Python are of very restricted use - we have modules and functions for this. And you may be interested in classmethods (methods that takes the class object instead of the instance as first argument). As a last word : trying to write Java in Python wis certainly not the best option. Better to learn to write Python. http://dirtsimple.org/2004/12/python-is-not-java.html From steve at REMOVE.THIS.cybersource.com.au Sun Jun 10 11:29:05 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Mon, 11 Jun 2007 01:29:05 +1000 Subject: memory efficient set/dictionary References: <1181485676.481109.234980@c77g2000hse.googlegroups.com> Message-ID: On Sun, 10 Jun 2007 07:27:56 -0700, koara wrote: > What is the best to go about using a large set (or dictionary) that > doesn't fit into main memory? What is Python's (2.5 let's say) > overhead for storing int in the set, and how much for storing int -> > int mapping in the dict? How do you know it won't fit in main memory if you don't know the overhead? A guess? You've tried it and your computer crashed? > Please recommend a module that allows persistent set/dict storage + > fast query that best fits my problem, Usually I love guessing what people's problems are before making a recommendation, but I'm feeling whimsical so I think I'll ask first. What is the problem you are trying to solve? How many keys do you have? Can you group them in some way, e.g. alphabetically? Do you need to search on random keys, or can you queue them and do them in the order of your choice? > and as lightweight as possible. > For queries, the hit ratio is about 10%. Fast updates would be nice, > but i can rewrite the algo so that the data is static, so update speed > is not critical. > > Or am i better off not using Python here? Cheers. -- Steven. From kay.schluehr at gmx.net Sat Jun 23 09:15:53 2007 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Sat, 23 Jun 2007 06:15:53 -0700 Subject: PEP 3107 and stronger typing (note: probably a newbie question) In-Reply-To: References: <1182448413.966430.299590@m36g2000hse.googlegroups.com> Message-ID: <1182604553.091782.312730@g4g2000hsf.googlegroups.com> On 22 Jun., 08:46, John Nagle wrote: > PEP 3107 seems to add negative value to the language. The > ability to add arbitrary attributes to parameters which can then > be interpreted by some external library yet to be defined is > a "l33t feature", one that's more cute than useful. Type-based > dispatching is cute, but not really essential to Python. I guess you refer to the generic functions PEP. Otherwise type based dispatching is what Psyco does implicitely by caching variants of natively compiled code blocks that can be considered as anonymous functions. But then Psyco has to perform continous measurements and either select a precompiled block if an appropriate signature has been found or return code to the bytecode interpreter for further evaluation. This scheme is an example for type directed evaluation that does not interfere with Pythons default semantics. Personally I appreciate having more control over expressions by means of annotations. I also do think it's valuable for component adaptions. So far I fail to see why it shall harm Python or having any impact on its flexibility. Being "unusal" is not an argument neither are vague apprehensions that Python will be locked into a poor type system with rigid default semantics. Kay From skip at pobox.com Fri Jun 8 14:17:02 2007 From: skip at pobox.com (skip at pobox.com) Date: Fri, 8 Jun 2007 13:17:02 -0500 Subject: Pyrex problem with cdef'd attribute In-Reply-To: <1181325223.819835.115600@a26g2000pre.googlegroups.com> References: <1181325223.819835.115600@a26g2000pre.googlegroups.com> Message-ID: <18025.40222.835520.881935@montanaro.dyndns.org> >> I'm using Pyrex 0.9.5.1a. I have this simple Pyrex module: Klaas> You might get more help on the pyrex list. Thanks. On the Pyrex website it says that questions are welcome here as well. I was hoping to avoid yet another mailing list subscription. ;-) Klaas> Yes, since you didn't cdef the class, it is essentially python Klaas> code. Python code cannot assign to a cdef class attribute that Klaas> is not of type 'object' So, if I cdef the Bar subclass I should be okay? I'll play around a bit more and if I continue to confuse myself will subscribe to the pyrex mailing list (or at least use the somewhat clunky gmane.org interface). Skip From tijs_news at bluescraper.nl Fri Jun 1 08:19:43 2007 From: tijs_news at bluescraper.nl (Tijs) Date: Fri, 01 Jun 2007 14:19:43 +0200 Subject: file reading by record separator (not line by line) References: Message-ID: <46600edf$0$323$e4fe514c@news.xs4all.nl> Steve Howell wrote: > Do you have any free time on your hands? Nope. I think Python is a programmer's language, not a whack-something-together script language for text processing (although it is used that way). Any decent programmer has no need of this construct, since the time to lookup how to use it is larger than the time to implement the specialized version for the task at hand. -- Regards, Tijs From http Tue Jun 26 00:08:05 2007 From: http (Paul Rubin) Date: 25 Jun 2007 21:08:05 -0700 Subject: Python's "only one way to do it" philosophy isn't good? References: <7x3b0nmkk6.fsf@ruckus.brouhaha.com> <1182750077.570603.160240@q69g2000hsb.googlegroups.com> <7xir9cbm0g.fsf@ruckus.brouhaha.com> Message-ID: <7xejjzmk7u.fsf@ruckus.brouhaha.com> Douglas Alan writes: > I will certainly admit that Lisp programmers at the time were (and > likely still are) much more enamored of mapping functions than of > iterators. Mapping functions certainly get the job done as elegantly > as iterators most of the time, although I would agree that they are > not quite so general. In the Maclisp era functions like mapcar worked on lists, and generated equally long lists in memory. It was sort of before my time but I have the impression that Maclisp was completely dynamically scoped and as such, it couldn't cleanly make anything like generators (since it had no way to make lexical closures). > Scheme, on, the other hand, at least by idiom, has computation > "streams", and streams are equivalent to iterators. No not really, they (in SICP) are at best more like class instances with a method that mutates some state. There's nothing like a yield statement in the idiom. You could do it with call/cc but SICP just uses ordinary closures to implement streams. > The canonical way to do this in Lisp would be something like: > (mapcar (lambda (x) (blah x)) xs) At least you could spare our eyesight by writing that as (mapcar #'blah xs) ;-). The point is that mapcar (as the name implies) advances down a list using cdr, i.e. it only operates on lists, not general iterators or streams or whatever. > > x = xs[key] > > I'm not sure what you are asserting? That Common Lisp doesn't have > hash tables? That's certainly not the case. Or that it doesn't > provide standard generic functions for accessing them The latter. Of course there are getf/setf, but those are necessarily macros. > A language like Python, which is defined by its implementation, > rather than by a standard, can move much more quickly. This debate > though is really one more of what is the best model for language > definition, rather than one on what the ideal language is like. Python is not Perl and it has in principle always been defined by its reference manual, though until fairly recently it's fostered a style of relying on various ugly CPython artifacts like the reference counting GC. Lisp accumulated a lot of cruft over the decades and it kept some baggage that it really could have done without. I don't think Python's designers learned nearly as much from Lisp as they could have, and Python has suffered because of it. Lisp still has an awesome beauty in both the CL and Scheme incarnations. But it's like listening to Elvis music--even if it can still get you dancing, at the end of the day it's still a reflection of a bygone culture. From jstroud at mbi.ucla.edu Fri Jun 29 14:08:00 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Fri, 29 Jun 2007 11:08:00 -0700 Subject: Voluntary Abstract Base Classes In-Reply-To: References: Message-ID: Daniel Nogradi wrote: > Hi list, > > Well, the short question is: what are they? I've read Guido's python > 3000 status report on > http://www.artima.com/weblogs/viewpost.jsp?thread=208549 where he > mentions ABC's but don't quite understand what the whole story is > about. > > Anyone has good use cases? > > Daniel My interpretation of his description is that this is a way to check for quack likes a duck behavior. Say I want a function to check if something behaves like a slice, but don't want to resort to checking for explicit inheritence, I might now have to do something like (factoring out the checking): def is_slice_like(candidate): for att in 'start', 'stop', 'step', 'indices': if not hasattr(candidate, att): return False return True def doit(anarg): if not is_slice_like(anarg): raise Exception, 'Must give something like a slice.' do_rest_of_it() However, with an ABC, you could define what it means to be slice-like by defining a slice-like ABC (e.g. SliceLike) and then virtually inheriting from this ABC: # assuming abstract inheritence syntax is the same as regular class MySlice(SliceLike): # etc. def doit(anarg): if not issubclass(anarg.__class__, SliceLike): raise Exception, 'Must give something SliceLike.' def main(): anarg = MySlice(1,2,3) doit(anarg) With ABCs, the concept of slice-like is more formalized and transparent than the attribute checking done in is_slice_like and is far more flexible than explicit type checking. The concept seems to be borrowed from Java interfaces. But I'm ready to be corrected on my interpretation. James From hiroc13 at gmail.com Fri Jun 29 05:29:17 2007 From: hiroc13 at gmail.com (hiroc13) Date: Fri, 29 Jun 2007 02:29:17 -0700 Subject: Python & MySQL problem with input to table..! In-Reply-To: <1183106949.790378.309910@g37g2000prf.googlegroups.com> References: <1183105583.922597.72930@n2g2000hse.googlegroups.com> <1183106949.790378.309910@g37g2000prf.googlegroups.com> Message-ID: <1183109357.498032.42160@n60g2000hse.googlegroups.com> Thanks!!!! It is working! From google0 at lazytwinacres.net Mon Jun 11 22:58:12 2007 From: google0 at lazytwinacres.net (google0 at lazytwinacres.net) Date: Mon, 11 Jun 2007 19:58:12 -0700 Subject: Anyone using TestNG Message-ID: <1181617092.302517.265650@d30g2000prg.googlegroups.com> Is anyone porting TestNG to Python, or using it with Python any other way (maybe via Jython?)? Thanks, --dang From yueping.lu at gmail.com Fri Jun 1 14:12:49 2007 From: yueping.lu at gmail.com (YuePing Lu) Date: Fri, 1 Jun 2007 14:12:49 -0400 Subject: Python 2.3 ODBC Datetime limitations Message-ID: <33cd6d8d0706011112w554ee6darea56f0977e9e3216@mail.gmail.com> Hello, Has any of you ever used Python odbc to retrieve data from a relational DB? I encountered a problem where it can't handle datetime *earlier than **1969*, and *later than **2040*. It just returned some garbage strings when I call str(my_date_object). When I call strptime to convert the value I got ValueError exception: # Table records for record in self._records: columns = [] for i in range(len(self._description)): if self._description[i][1]=='DATE': strDate=str(record[i]) try: #convert the date format to be mm/dd/yyyy: oDate=time.strptime(strDate) #convert to struct_time object strfDate=time.strftime("%m/%d/%Y", oDate) columns.append(strfDate) except ValueError, msg: raise "Date converstion error", msg ... Any other solutions that you've heard? Thanks very much in advance, -------------- next part -------------- An HTML attachment was scrubbed... URL: From doug at alum.mit.edu Fri Jun 15 17:05:27 2007 From: doug at alum.mit.edu (Douglas Alan) Date: Fri, 15 Jun 2007 17:05:27 -0400 Subject: Python's "only one way to do it" philosophy isn't good? References: <1181368143.874341.273140@r19g2000prf.googlegroups.com> Message-ID: "Terry Reedy" writes: > Here's the situation. Python is making inroads at MIT, Scheme home turf. > The co-developer of Scheme, while writing about some other subject, tosses > in an off-the-wall slam against Python. Someone asks what we here think. > I think that the comment is a crock and the slam better directed, for > instance, at Scheme itself. Hence 'he should look in a mirror'. You are ignoring the fact that Scheme has a powerful syntax extension mechanism (i.e., hygenic macros), which means that anyone in the world can basically extend Scheme to include practically any language feature they might like it to have. |>oug From horpner at yahoo.com Tue Jun 19 10:35:33 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Tue, 19 Jun 2007 14:35:33 GMT Subject: Python IDE References: <1182249585.535675.143460@m36g2000hse.googlegroups.com> <1182259143.375798.283620@k79g2000hse.googlegroups.com> <5dq3n9F359hp0U1@mid.individual.net> Message-ID: On 2007-06-19, Bjoern Schliessmann wrote: > BartlebyScrivener wrote: >> VIM > > *clap-clap* > > BTW, are there tutorials on the more arcane vim functions that > come in handy with Python? One thing to do is to look in your vim ftplugin directory and read python.vim. Unfortunately, the current version contains no documention, so it's harder to figure out what you get than it ought to be. -- Neil Cerutti From antroy at gmail.com Thu Jun 21 05:23:14 2007 From: antroy at gmail.com (Ant) Date: Thu, 21 Jun 2007 02:23:14 -0700 Subject: Can python access windows clipboard In-Reply-To: <1182416346.377857.103540@z28g2000prd.googlegroups.com> References: <1182416346.377857.103540@z28g2000prd.googlegroups.com> Message-ID: <1182417794.755107.280400@q69g2000hsb.googlegroups.com> On Jun 21, 9:59 am, MaHL wrote: > Can I use python to copy something(like a string) to the clipboard, so > that I can paste it somewhere else. Is there a way to do this? The following requires Mark Hammond's win32all package (http:// sourceforge.net/projects/pywin32/): import win32clipboard, win32con, random text = "Some text to stick on the clipboard" win32clipboard.OpenClipboard() win32clipboard.SetClipboardData(win32con.CF_TEXT, text) win32clipboard.CloseClipboard() -- Ant... http://antroy.blogspot.com/ From horpner at yahoo.com Mon Jun 18 11:23:30 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Mon, 18 Jun 2007 15:23:30 GMT Subject: Parsing HTML, extracting text and changing attributes. References: <1182175239.122827.4150@g4g2000hsf.googlegroups.com> Message-ID: On 2007-06-18, sebzzz at gmail.com wrote: > I work at this company and we are re-building our website: http://caslt.org/. > The new website will be built by an external firm (I could do it > myself, but since I'm just the summer student worker...). Anyways, to > help them, they first asked me to copy all the text from all the pages > of the site (and there is a lot!) to word documents. I found the idea > pretty stupid since style would have to be applied from scratch anyway > since we don't want to get neither old html code behind nor Microsoft > Word BS code. > > I proposed to take each page and making a copy with only the text, and > with class names for the textual elements (h1, h1, p, strong, em ...) > and then define a css file giving them some style. > > Now, we have around 1 600 documents do work on, and I thought I could > challenge myself a bit and automate all the dull work. I thought about > the possibility of parsing all those pages with python, ripping of the > navigations bars and just keeping the text and layout tags, and then > applying class names to specific tags. The program would also have to > remove the table where text is located in. And other difficulty is > that I want to be able to keep tables that are actually used for > tabular data and not positioning. > > So, I'm writing this to have your opinion on what tools I > should use to do this and what technique I should use. You could get good results, and save yourself some effort, using links or lynx with the command line options to dump page text to a file. Python would still be needed to automate calling links or lynx on all your documents. -- Neil Cerutti From bj_666 at gmx.net Tue Jun 19 04:03:11 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Tue, 19 Jun 2007 10:03:11 +0200 Subject: Rotating a picture References: <1182238895.646197.270090@k79g2000hse.googlegroups.com> Message-ID: In <1182238895.646197.270090 at k79g2000hse.googlegroups.com>, Tom Gur wrote: > I'm trying to build a small spaceship battle game as an exercise, > using pygame. > How can I rotate the gif file of my ship by X degrees ? You shouldn't do this with the PyGame functions, the quality is poor. Either use a paint program to pre-generate rotated images or the python imaging library (PIL) to create them in the game. Either way you should use an RGB format instead of a format with a palette to have better anti aliasing, and always rotate from the original image as each rotation introduces some loss of quality and detail. Ciao, Marc 'BlackJack' Rintsch From martin at v.loewis.de Wed Jun 20 01:14:02 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Wed, 20 Jun 2007 07:14:02 +0200 Subject: determine 32 or 64 bit architecture with python 2.2 In-Reply-To: <1182263518.734695.327620@w5g2000hsg.googlegroups.com> References: <1182251830.835902.78210@n2g2000hse.googlegroups.com> <1182256124.727593.93360@z28g2000prd.googlegroups.com> <1182263518.734695.327620@w5g2000hsg.googlegroups.com> Message-ID: <4678B79A.9060108@v.loewis.de> >> What happens when you fire up a 64-bit Python and type >> import sys; sys.maxint >> at it? > > That's not suitable, because of the differences between LP64 and LLP64 > (http://en.wikipedia.org/wiki/64-bit#64-bit_data_models ). For the systems that the OP mentioned, sys.maxint is just fine: AIX and Solaris both use LP64, and Windows is 32-bit only for Python 2.2. Regards, Martin From blmblm at myrealbox.com Sat Jun 23 20:50:44 2007 From: blmblm at myrealbox.com (blmblm at myrealbox.com) Date: 24 Jun 2007 00:50:44 GMT Subject: The Modernization of Emacs: terminology buffer and keybinding References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182272495.990807.99110@a26g2000pre.googlegroups.com> <87tzt3ihev.fsf@kobe.laptop> Message-ID: <5e5tf4F30n9e0U1@mid.individual.net> In article , Bjorn Borud wrote: > [Giorgos Keramidas ] > | > | Educating the user to avoid confusion in this and other cases of made > | up, 'user-friendly' descriptions is not a good enough answer. > > there are two types of "user friendly". there's "user friendly" and > then there is "beginner friendly" which is often mislabeled. the > latter is more important for applications which are to be used > casually. like utilities you only use once or twice per year -- those > need to be "beginner friendly". Maybe this is an okay point at which to mention one of my favorite bits of commentary on this subject. It's an interview with Leslie Lamport (originator of LaTeX, among other things) in which he talks about the needs of beginners versus the needs of experts, and how the latter are often neglected: http://research.microsoft.com/users/lamport/pubs/lamport-latex-interview.pdf (Yes, he works (worked? but this seems current) for Microsoft. Astonishing.) Asked whether whether LaTeX is hard to use, he replies "It's easy to use -- if you're one of the 2% of the population who thinks logically and can read an instruction manual. [otherwise not]" > for applications you are likely to use for prolonged periods of time > (like programming, video editing, music production etc), it does not > make sense to optimize for "beginner friendly". at least not at the > cost of making the application less "user friendly". > > applications you spend a lot of time using are worth an investment in > learning how to use them. what creates friction in an application you > know reasonably well is when common tasks are fiddly. for instance, > while menus are often good for casual use and lower the initial > threshold for absolute beginners, depending heavily on menu navigation > becomes too fiddly if you are performing a certain task 2-3 times per > minute. it is not _user_ friendly. Sing it, brother. (I'm a vim fan myself, but my thinking is that these days emacs and vi(m) people should be banding together against a common enemy rather than carrying on the fine old tradition of arguing with each other. We have in common a preference, maybe, for learning one editor really well and using it for everything.) -- B. L. Massingill ObDisclaimer: I don't speak for my employers; they return the favor. From paul at boddie.org.uk Fri Jun 22 13:39:47 2007 From: paul at boddie.org.uk (Paul Boddie) Date: Fri, 22 Jun 2007 10:39:47 -0700 Subject: PEP 3107 and stronger typing (note: probably a newbie question) In-Reply-To: <87tzt0tgol.fsf@benfinney.id.au> References: <1182448413.966430.299590@m36g2000hse.googlegroups.com> <7xhcp0fom4.fsf@ruckus.brouhaha.com> <87tzt0tgol.fsf@benfinney.id.au> Message-ID: <1182533987.715191.159850@m36g2000hse.googlegroups.com> On 22 Jun, 12:41, Ben Finney wrote: > > I think it's great that we're going to get Python 3.0 soon, and that > Python 4.0 proposals will benefit from a long period of familiarity > with widely-deployed PyPy :-) I'm not going to name and shame anyone, but here's part of a genuine docstring from a program I downloaded not so long ago: It was tested for python 4.0. It certainly doesn't work for python versions earlier than 3.3. If I need to speculate about future Python versions, I know who to ask. ;-) Paul P.S. I agree with the sentiment that the annotations feature of Python 3000 seems like a lot of baggage. Aside from some benefits around writing C/C++/Java wrappers, it's the lowest common denominator type annotation dialect that dare not be known as such, resulting from a lack of consensus about what such a dialect should really do, haunted by a justified fear of restrictive side-effects imposed by a more ambitious dialect (eg. stuff you get in functional languages) on dynamically-typed code. I don't think the language should be modified in ways that only provide partial, speculative answers to certain problems when there's plenty of related activity going on elsewhere that's likely to provide more complete, proven answers to those problems. From gagsl-py2 at yahoo.com.ar Wed Jun 20 14:46:03 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 20 Jun 2007 15:46:03 -0300 Subject: subprocess.popen question References: <1182353267.200998.43900@w5g2000hsg.googlegroups.com> Message-ID: En Wed, 20 Jun 2007 12:27:47 -0300, Eric_Dexter at msn.com escribi?: > I am trying to modify a programming example and I am coming up with > two problems... first is that I can't seem to pass along the > arguments to the external command (I have been able to do that with > the old module and cmd is the command I wish to try) all the output > seems to be returned as one line (at least when I run the program in > spe). > > import subprocess > from os import system > cmd = """gawk -f altertime.awk -v time_offset=4 -v > outfile="testdat.sco" "i1.sco" """ > #subprocess.Popen. > last_line = subprocess.Popen(['gawk.exe'], > stdout=subprocess.PIPE).communicate()[0] You build what appears to be the desired command line, but execute gawk.exe instead. Better split the arguments beforehand: cmd = ["gawk", "-f", "altertime.awk", "-v", "time_offset=4", "-v", "outfile=testdat.sco", "i1.sco"] Now, what do you want to do with the output? Printing it line by line? output = subprocess.Popen(cmd, stdout=subprocess.PIPE).communicate()[0] lines = output.splitlines() for line in lines: print line -- Gabriel Genellina From rubbishemail at web.de Mon Jun 18 10:50:24 2007 From: rubbishemail at web.de (rubbishemail at web.de) Date: Mon, 18 Jun 2007 07:50:24 -0700 Subject: copy locked files Message-ID: <1182178224.486883.203330@q75g2000hsh.googlegroups.com> Hello, do you know of any way to copy locked / opened files under win xp? I know there is something like "Volume Shadow Copy" but I don't know how to use it. Maybe someone already has a python solution? Many thanks Daniel From george.sakkis at gmail.com Mon Jun 25 01:01:55 2007 From: george.sakkis at gmail.com (George Sakkis) Date: Mon, 25 Jun 2007 05:01:55 -0000 Subject: Inferring initial locals() In-Reply-To: <137ube28i1f0o9d@corp.supernews.com> References: <1182451904.703471.141000@n60g2000hse.googlegroups.com> <1182458574.630461.121290@o61g2000hsh.googlegroups.com> <1182461716.016181.18730@k79g2000hse.googlegroups.com> <137ube28i1f0o9d@corp.supernews.com> Message-ID: <1182747715.681011.165800@c77g2000hse.googlegroups.com> On Jun 24, 10:52 pm, Scott David Daniels wrote: > So, what should your code do about this: > > def someFunction(a, b, c=43, d=14, f=12): > print locals() > > import functools > > a_funct = functools.partial(someFunction, d=13, c=5) > b_funct = functools.partial(a_funct, 14, d=12) > localsProber(b_funct) Didn't get too far :) Traceback (most recent call last): File "locprobe.py", line 54, in localsProber(b_funct) File "locprobe.py", line 9, in localsProber args, varargs, varkw, defaults = inspect.getargspec(callable) File "C:\Python25\lib\inspect.py", line 728, in getargspec raise TypeError('arg is not a Python function') TypeError: arg is not a Python function > My point is simply: > Introspection code is often written with a fixed idea of what other > programmers write. The others don't use introspection, the others > don't use higher order functions to build functions, .... Fair enough, especially since not even the standard inspect module handles functools.partial objects. Perhaps things will improve after 2.6 with PEP 362 (Function Signature Object) in place. What you claim about introspection code though I think holds for code in general. There are quite often edge cases which the programmer doesn't anticipate or care to handle. A tool that covers X% of real- world use cases for some large X and documents the known limitations for the rest 100-X is fine with me (e.g. the current lambda). George From carsten at uniqsys.com Fri Jun 1 11:55:54 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Fri, 01 Jun 2007 11:55:54 -0400 Subject: MySQLdb insert fails on one table In-Reply-To: References: Message-ID: <1180713354.3376.64.camel@dot.uniqsys.com> On Fri, 2007-06-01 at 11:48 -0400, Sells, Fred wrote: > INSERT INTO valid_individuals (fname,lname,alias,email) VALUES (%s,%s,%s,%s) > [['xxxx', 'yyyy', 'zzzzz', 'aaaaaa']] > > this function works fine for several other tables, but on this one I get no > errors and there is nothing in the table. If I run the equivalent insert on > the command line, it's just fine. This usually indicates that the table is transaction-aware (e.g. storage mechanism InnoDB versus MyISAM) and you're not committing your transaction, so the transaction gets rolled back when your connection is closed. HTH, -- Carsten Haese http://informixdb.sourceforge.net From gagsl-py2 at yahoo.com.ar Wed Jun 13 02:40:13 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 13 Jun 2007 03:40:13 -0300 Subject: Multiline lamba implementation in python. References: <1b0ce1b60706112002i761dc295x9ba9c4f589c41db1@mail.gmail.com> <1b0ce1b60706121648id58bee1mc0c184bf67271262@mail.gmail.com> Message-ID: En Tue, 12 Jun 2007 20:48:41 -0300, Josh Gilbert escribi?: > Guido doesn't want multiline lambdas, that's a really good reason not to > add > them. They are, on the other hand, very useful at times. Even if he did > add > multiline lambdas it's not certain that he would allow statements in > them, > currently they're expression only. The beauty of my suggestion is that But you already have "multiline" lambdas right now in that sense, no need to add anything. I think you were talking about lambdas *with* statements inside. bin = lambda x:((x&8 and '*' or '_') + (x&4 and '*' or '_') + (x&2 and '*' or '_') + (x&1 and '*' or '_')) -- Gabriel Genellina From pydecker at gmail.com Thu Jun 21 10:14:35 2007 From: pydecker at gmail.com (Peter Decker) Date: Thu, 21 Jun 2007 10:14:35 -0400 Subject: PEP 3107 and stronger typing (note: probably a newbie question) In-Reply-To: <5dveb4F360un0U1@mid.individual.net> References: <1182369568.941307.316260@p77g2000hsh.googlegroups.com> <5dveb4F360un0U1@mid.individual.net> Message-ID: On 6/21/07, Bjoern Schliessmann wrote: > Stephen R Laniel wrote: > > On Wed, Jun 20, 2007 at 12:59:28PM -0700, > > bruno.desthuilliers at gmail.com wrote: > > >> Then you should use another language. > > > > This is what I meant about knowing how Internet discussions > > go. > > I agree. I also notice that (rather newbie-) OPs with not-so-simple > questions are easily offended by technical answers. I'd love to > know why. Oh, c'mon. The OP was asking for an explanation, and got an indignant response. There is a world of difference between explaining *why* Python is the way it is, and getting the equivalent of a 4-year-old's "Because!" as a reply. To someone who admits that he is largely unfamiliar with the language, it would seem obvious that Python is "lacking" something that is important in other languages. An explanation as to why this would be Bad Thing for Python would be a helful response. -- # p.d. From ljelmore at verizon.spammenot.net Sun Jun 10 18:11:08 2007 From: ljelmore at verizon.spammenot.net (Larry Elmore) Date: Sun, 10 Jun 2007 22:11:08 GMT Subject: The Concepts and Confusions of Prefix, Infix, Postfix and Fully Functional Notations In-Reply-To: <1181448558.120521.63250@g4g2000hsf.googlegroups.com> References: <1179936917.652372.24780@q69g2000hsb.googlegroups.com> <1180508453.226022.44230@q19g2000prn.googlegroups.com> <1181335574.107472.229370@x35g2000prf.googlegroups.com> <1181358616.792797.97720@k79g2000hse.googlegroups.com> <1181414625.121073.203940@g4g2000hsf.googlegroups.com> <0uHai.176367$nh4.13819@newsfe20.lga> <1181448558.120521.63250@g4g2000hsf.googlegroups.com> Message-ID: <0G_ai.1970$xg4.809@trnddc08> Twisted wrote: > On Jun 9, 8:21 pm, "BCB" wrote: >> "Paul McGuire" wrote in message >> >> news:1181414625.121073.203940 at g4g2000hsf.googlegroups.com... >> >>> On Jun 9, 6:49 am, Lew wrote: >>>>> In particular, Perl code looks more like line >>>>> noise than like code from any known programming language. ;)) >>>> Hmm - I know of APL and SNOBOL. >>>> -- >>>> Lew >>> TECO editor commands. I don't have direct experience with TECO, but >>> I've heard that a common diversion was to type random characters on >>> the command line, and see what the editor would do. >>> -- Paul >> J >> >> http://www.jsoftware.com/ > > Oh come on! Toy languages (such as any set of editor commands) and > joke languages (ala Intercal) don't count, even if they are > technically Turing-complete. ;) > > Nor does anything that was designed for the every-character-at-a- > premium punch-card era, particularly if it is, or rhymes with, > "COBOL". > > Those have excuses, like it's a joke or it's a constrained > environment. Perl, unfortunately, has no such excuses. If there were > such a thing as "embedded Perl", I'd have to hesitate here, but since > there isn't... Neither APL nor Snobol nor J are toy or joke languages. From kyosohma at gmail.com Mon Jun 11 09:47:18 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Mon, 11 Jun 2007 06:47:18 -0700 Subject: Pasting an image from clipboard in Tkinter? In-Reply-To: <1181564628.443138.165380@k79g2000hse.googlegroups.com> References: <1181564628.443138.165380@k79g2000hse.googlegroups.com> Message-ID: <1181569638.924072.25150@k79g2000hse.googlegroups.com> On Jun 11, 7:23 am, "exhuma.twn" wrote: > As many might know, windows allows to copy an image into the clipboard > by pressing the "Print Screen" button on the keyboard. Is it possible > to paste such an image from the clipboard into a "Text" widget in > Tkinter? Here is my first attempt with just trying to print out the > image data: > > ----------------- > def pasteImg(tgt): > global clipboardEnabled > if not clipboardEnabled: return > > win32clipboard.OpenClipboard(0) > print win32clipboard.GetClipboardData() > win32clipboard.CloseClipboard() > ----------------- > > This works fine with selecting text, but comes up with the following > error when trying to paste an image: > > ----------------- > Exception in Tkinter callback > Traceback (most recent call last): > File "C:\Python25\lib\lib-tk\Tkinter.py", line 1403, in __call__ > return self.func(*args) > File "X:\development\testing\tkwiki\tkwiki.py", line 52, in > Button( root, command=lambda: pasteImg(txt) ).pack() > File "X:\development\testing\tkwiki\tkwiki.py", line 38, in pasteImg > print win32clipboard.GetClipboardData() > TypeError: Specified clipboard format is not available > ----------------- > > Obviously the clipboard does not know about that format. Does that > mean I have to wait until it's implemented or are there other ways to > access the image data? I don't think you can paste to a text widget, but I could be mistaken. This link talks about pasting an image into a window, but I don't think it's really what you want...however, it might give you some ideas: http://effbot.org/zone/wck-3.htm (see the "Drawing Images" section) This link also talks about some of the same things: http://www.wadsworth.org/spider_doc/spider/docs/python/spipylib/tkinter.html If I understand them correctly, it sounds like you could possibly catch the the paste operation and convert the image to a TkImage and then paste it. I think that since it is in the clipboard, then it is a file object and this may work. I just don't know how you intercept a paste. Mike From jadestar at idiom.com Sun Jun 10 02:01:37 2007 From: jadestar at idiom.com (James T. Dennis) Date: Sun, 10 Jun 2007 06:01:37 -0000 Subject: PyGTK : a NEW simple way to code an app References: <1178898148.924772.200450@w5g2000hsg.googlegroups.com> Message-ID: <1181455297.331446@smirk> manatlan wrote: > I was a fan of "SimpleGladeApp/tepache way" to build a pygtk app. > I've build a new efficient/dynamic way to build a pygtk app ... > Here is an example : > ================================================= > class Fen(GladeApp): > """ > Window win > .title="Hello" > @delete_event > VBox > HBox > Label jo > .label="kokotte" > entry myEntry > .text="kuku" > gtkBuTTon b2 > .label="33" > @clicked > Label jo > .label="koko" > Button b > .label="3" > @clicked > """ > def init(self,m): > self.jo.set_text(m) > pass > def on_b_clicked(self,*a): > self.quit(3) > def on_b2_clicked(self,*a): > self.quit(33) > def on_win_delete_event(self,*args): > self.quit(4) > f=Fen("koko2") > print f.loop() > ================================================= > How it works : > in fact, the __doc__ is converted as a "glade file" > the tree of object is indented (like python way) > you can see some common pygtk widget ... > line starting with a dot is an property of the parent object. > line starting with a @ is a declaration of a event of the parent > object. > widgets are not case sensitive, and can start with "Gtk". If a second > word is provided it will be used as an "id", otherwise an unique id > will be build according the type of widget. > the window is created with glade, widgets are provided as attributs of > the instance, and signals are autoconnected on method > "on_[widgetId]_[event](self,*args)" (if a signal is missing in your > class, it warns you at run time) .... > It will not replace the use of glade-3 for complex widget ... but I > think it's an easy way to code very easily/quickly a simple pygtk > window/form. > I think it could be really useful/handly for beginners too. > for people which are involved in pygtk/python/gui ... i'd like to hear > your comments/ideas ... > Rq: > i don't provide the code now, but it will be released in next version > of "GladeApp" ( http://manatlan.infogami.com/GladeApp ) > it works already, but i need to make "packing properties available" > too ... I'd be a little leery of overloading the __doc__ strings in this way. (They are overloaded enough when used for doctest strings ... but those can serve a legitimate documentary purpose and other doctests can be stored separately). Perhaps it would make sense to standardize on a defined member name such as: GTK__Glade. The rest of your code could remain the same. Are there any other Python projects using other "magically introspected strings" approaches? I thought I saw something being used by some "programming by contract" or some AOP (aspect oriented programming) tools that might be using something like this. -- Jim Dennis, Starshine: Signed, Sealed, Delivered From steven.bethard at gmail.com Tue Jun 12 18:09:44 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 12 Jun 2007 16:09:44 -0600 Subject: SimplePrograms challenge In-Reply-To: References: <1181649968.097585.131780@g37g2000prf.googlegroups.com> <87vedsua4o.fsf@merkury.smsnet.pl> Message-ID: Steven Bethard wrote: > Rob Wolfe wrote: >> Steven Bethard writes: >>> I'd hate to steer a potential new Python developer to a clumsier >> >> "clumsier"??? >> Try to parse this with your program: >> >> page2 = ''' >> URLs >> >>
    >>
  • some page1
  • >>
  • some page2
  • >> >> ''' > > If you want to parse invalid HTML, I strongly encourage you to look into > BeautifulSoup. Here's the updated code: > > import ElementSoup # http://effbot.org/zone/element-soup.htm > import cStringIO > > tree = ElementSoup.parse(cStringIO.StringIO(page2)) > for a_node in tree.getiterator('a'): > url = a_node.get('href') > if url is not None: > print url I should also have pointed out that using the above ElementSoup code can parse the following text:: URLs
      some page1
    • some page2
    • where the HTMLParser code raises an HTMLParseError. STeVe From msj at infoserv.dk Wed Jun 20 10:53:36 2007 From: msj at infoserv.dk (Martin Skou) Date: Wed, 20 Jun 2007 16:53:36 +0200 Subject: python website In-Reply-To: <1182349364.574645.279350@q19g2000prn.googlegroups.com> References: <1182349364.574645.279350@q19g2000prn.googlegroups.com> Message-ID: <46793f39$0$8705$edfadb0f@dread14.news.tele.dk> The Daily Python-URL http://www.pythonware.com/daily/ From tjreedy at udel.edu Fri Jun 1 13:00:40 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 1 Jun 2007 13:00:40 -0400 Subject: What is equivalent of *this = that in python? References: <32e43bb70706010830t38e69cb1t732e5dbdaff6cd1b@mail.gmail.com> Message-ID: "Emin.shopper Martinian.shopper" wrote in message news:32e43bb70706010830t38e69cb1t732e5dbdaff6cd1b at mail.gmail.com... | How do I reassign self to another object? Exactly the way you give below. |For example, I want something like | | class foo: | def Update(self,other): Self and other are two local names. Self is presumed to be bound to an instance of foo. Other can be bound to anything, even the same thing as self. But presumably, the other object should be at least foo-compatible. | # make this object the same as other or make this object a copy of other 'same as' is a bit ambiguous. 'a copy' slightly less so. | self = other # This won't work. Yes is does. It reassigns the name 'self' to another object, which is what you requested at the top ;-) To copy attributes, you need self.attribute = other.attribute. Also look into the copy module for cloning objects. | What I really want is *this = other in C++ terminology. Strictly speaking, this is meaningless in Python terms (names, collection slots, attributes, and objects). Terry Jan Reedy From blmblm at myrealbox.com Mon Jun 25 17:32:38 2007 From: blmblm at myrealbox.com (blmblm at myrealbox.com) Date: 25 Jun 2007 21:32:38 GMT Subject: The Modernization of Emacs: terminology buffer and keybinding References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182545268.055596.228700@i38g2000prf.googlegroups.com> <1182661040.286559.150880@q75g2000hsh.googlegroups.com> Message-ID: <5eaqjmF36ga72U1@mid.individual.net> In article <1182661040.286559.150880 at q75g2000hsh.googlegroups.com>, Twisted wrote: > On Jun 23, 2:04 am, Robert Uhl wrote: [ snip ] > Apparently because you find the switch second nature, despite its not > being the obvious (which is ctrl-tab, to switch between documents in > an MDI app). Cheat sheet? Memorized with painstaking months of hard > effort? Thanks for proving my point, either way. Not really ragging on you, however it seems, but this is a pet peeve of mine, and I have a few minutes, and this thread is already pretty much out of control, so .... Painstaking months of hard effort? You know, I started out in the days before GUIs, so I have experience with cheat sheets, but I don't remember ever being given one and being told that there would be a quiz in a week, or a month, or whatever. Instead, I used the cheat sheet at first, and over the course of the first few -- hours, weeks, I don't know -- found that I needed it less and less, as the commands I actually used in my daily work made their way into my memory. (Does that mean that I didn't memorize all the commands on the cheat sheet? Maybe. But the ones I didn't learn were ones I didn't need.) To me it's similar to "memorizing" a phone number by dialing it enough times that it makes its way into memory without conscious effort. I suspect that not everyone's brain works this way, and some people have to look it up every time. For those people, I can understand why something without a GUI could be a painful experience. "YMMV", maybe. [ snip ] -- B. L. Massingill ObDisclaimer: I don't speak for my employers; they return the favor. From sigzero at gmail.com Thu Jun 21 15:13:45 2007 From: sigzero at gmail.com (Robert Hicks) Date: Thu, 21 Jun 2007 19:13:45 -0000 Subject: try/except with multiple files In-Reply-To: <1182453111.391374.279490@e9g2000prf.googlegroups.com> References: <1182452425.793305.193370@u2g2000hsc.googlegroups.com> <1182453111.391374.279490@e9g2000prf.googlegroups.com> Message-ID: <1182453225.866527.153390@q75g2000hsh.googlegroups.com> On Jun 21, 3:11 pm, Matimus wrote: > It depends, what are you going to do if there is an exception? If you > are just going to exit the program, then that works fine. If you are > going to just skip that file, then the above wont work. If you are > going to return to some other state in your program, but abort the > file opening, you might want to close any files that were opened. The > closing can be taken care if in the except block, but you will have to > know which ones opened successfully. > > In general I would do something like this for multiple files: > > [code] > filenames = ["fname1","fname2","fname3"] > for fn in filenames: > try: > f = open(fn) > except IOError: > # handle exception > #do something with f > [/code] > > But, that might not work for you if the files aren't homogeneous (each > have similar contents). If the files have distinctly different > purposes, I would just wrap them each in their own try/except block. > > I rambled a bit there, but I hope it helps. > > Matt Helps a bunch...thank you very much. Robert From sturlamolden at yahoo.no Mon Jun 18 12:28:14 2007 From: sturlamolden at yahoo.no (sturlamolden) Date: Mon, 18 Jun 2007 09:28:14 -0700 Subject: Matrix Multiplication In-Reply-To: References: <1182113543.957069.135240@k79g2000hse.googlegroups.com> <1182118748.755871.267780@u2g2000hsc.googlegroups.com> Message-ID: <1182184094.620093.15930@n60g2000hse.googlegroups.com> On Jun 18, 11:20 am, Jeremy Sanders wrote: > > NumPy has a matrix type that overloads the * operator. > Just a tiny followup, which may be important unless you carefully read the > documentation. The "*" operator doesn't do matrix multiplication for normal > numpy arrays That's what I wrote: "NumPy has a matrix type." It is called called numpy.matrix. I did not suggest using the array type numpy.array. Reading carefully is indeed important... From basilisk96 at gmail.com Wed Jun 6 21:40:27 2007 From: basilisk96 at gmail.com (Basilisk96) Date: Thu, 07 Jun 2007 01:40:27 -0000 Subject: creating lists based on parsed items In-Reply-To: References: <0138071BF1642F49BD9826823E668663DCA87A@ex2.casl.umd.edu> <1181170167.160965.126760@g37g2000prf.googlegroups.com> Message-ID: <1181180427.454415.136300@g4g2000hsf.googlegroups.com> > This would be a RTFM moment :) defaultdict is not a built-in, it is part > of the collections module. Bingo! I should have read higher up in the manual tree :) Thanks From evan at yelp.com Tue Jun 26 12:52:55 2007 From: evan at yelp.com (Evan Klitzke) Date: Tue, 26 Jun 2007 09:52:55 -0700 Subject: Installing python under the linux In-Reply-To: <1182867273.230244.151900@w5g2000hsg.googlegroups.com> References: <1182800785.231113.199750@n2g2000hse.googlegroups.com> <1182802267.969628.156960@o61g2000hsh.googlegroups.com> <1182845417.526433.59690@c77g2000hse.googlegroups.com> <4680F3DB.6040901@web.de> <1182867273.230244.151900@w5g2000hsg.googlegroups.com> Message-ID: On 6/26/07, vedrandekovic at v-programs.com wrote: > Hello, > > >No. The only way to change the keywords would be to edit the > >Python source and re-compile it. > > This was very helpful information , I already know that but I don't > know how > to that.PLEASE HELP ME ABOUT THIS, I WILL BE VERY GRATEFUL TO YOU. > > ( IF you can please step by step how to I install that source ) You need to execute the following commands: apt-get install build-essential fakeroot apt-get source python apt-get build-dep python cd python-some-more-stuff-here-and-a-version-number (make the changes you want to make) sudo dpkg-buildpackage -rfakeroot -b If you need more help building the deb, you should ask on the Ubuntu mailing lists. -- Evan Klitzke From nagle at animats.com Mon Jun 11 13:37:12 2007 From: nagle at animats.com (John Nagle) Date: Mon, 11 Jun 2007 10:37:12 -0700 Subject: Python optimization (was Python's "only one way to do it" philosophy isn't good?) In-Reply-To: <5d4broF31klo5U1@mid.uni-berlin.de> References: <1181368143.874341.273140@r19g2000prf.googlegroups.com> <9OVai.7525$u56.7287@newssvr22.news.prodigy.net> <5d4broF31klo5U1@mid.uni-berlin.de> Message-ID: Diez B. Roggisch wrote: > Regardless of the possibility of speeding it up - why should one want > this? Coding speed is more important than speed of coding in 90%+ of all > cases. When you have to start buying more servers for the server farm, it's a real pain. I'm actually facing that because Python's HTML parsing is so slow. John Nagle From larry.bates at websafe.com Thu Jun 21 11:54:16 2007 From: larry.bates at websafe.com (Larry Bates) Date: Thu, 21 Jun 2007 10:54:16 -0500 Subject: How to create a file with read access rights In-Reply-To: <1182439636.529600.126210@c77g2000hse.googlegroups.com> References: <1182439636.529600.126210@c77g2000hse.googlegroups.com> Message-ID: <7MadnZNB5eGBAufbnZ2dnUVZ_qTinZ2d@comcast.com> Johny wrote: > Is it possible to create a file on Linux with access rights? > For example > owner can read and write into the file > others can only read from the file > Thanks for replies > L. > See os.chmod() -Larry From haggardii at gmail.com Fri Jun 15 15:00:49 2007 From: haggardii at gmail.com (Matt Haggard) Date: Fri, 15 Jun 2007 12:00:49 -0700 Subject: PIL cutting off letters Message-ID: <1181934049.401650.115360@q19g2000prn.googlegroups.com> I'm using PIL (Python Imaging Library) to generate button images. They consist of a left end image, a middle, repeating image and a right side image.... anyway, that's not important I'm using a TTF font for the text of the button (Verdana.TTF) and it keeps cutting the bottom part of the the g's q's and y's off. Here's the important parts of my code (options contains command-line params): im = Image.new("RGB",(1,1)) font = ImageFont.truetype(options.font,options.fontsize) draw = ImageDraw.Draw(im) textsize = draw.textsize(options.text, font=font) im = im.resize( (totalwidth, maxheight) ) draw = ImageDraw.Draw(im) thecolor = "rgb(0,0,0)" x = (totalwidth - textsize[0]) / 2 y = (maxheight - textsize[1]) / 2 + options.offsetY draw.text((x, y), options.text, font=font, fill=thecolor ) im.save(savefile, quality=100) If I increase the font-size to larger than about 16, the tails appear... any clue as to why this happens or what I can do to fix it? From cam.ac.uk at mh391.invalid Sat Jun 23 16:50:46 2007 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Sat, 23 Jun 2007 21:50:46 +0100 Subject: Python changing keywords name In-Reply-To: <1182630774.701295.50890@k79g2000hse.googlegroups.com> References: <1182630774.701295.50890@k79g2000hse.googlegroups.com> Message-ID: vedrandekovic at v-programs.com wrote: > Hello AGAIN, > > I on working on windows and Python 2.4. Where can I find and CHANGE > python > grammar. ( I just want to change the keywords ) > > PLEASE HELP ME > SOMEBODY!!!!!! > > THANKS!!!!!!!!!!!!!!!!! This is the third time you have posted this today. Please stop. Also, you might want to moderate the tone of your messages. Some people might find a string of all caps and exclamation marks obnoxious. I think it is less likely to get you help. You may find this guide helpful . -- Michael Hoffman From me at privacy.net Sun Jun 3 04:42:32 2007 From: me at privacy.net (Mark Carter) Date: Sun, 03 Jun 2007 09:42:32 +0100 Subject: Python rocks In-Reply-To: <1hz3dq5.1ujabwt1n1e6mfN%aleax@mac.com> References: <4661700a$0$19261$da0feed9@news.zen.co.uk> <1hz3dq5.1ujabwt1n1e6mfN%aleax@mac.com> Message-ID: <46627efa$0$19248$da0feed9@news.zen.co.uk> Alex Martelli wrote: > Mark Carter wrote: > Yes, GMP is a pain to compile (especially on Mac OS X), but I believe > Just mentioning this in case you want to give Scheme another chance Thanks. I'll take a look at it. I think I've decided to finish off my little in project in Python first, though. I'd like to actually get it done (!). I may well decide to reimplement bits in either Scheme, or I might try my hand at Forth. My app will be small enough to permit re-writes. I had actually done a small 3-month Java project professionally about 7 years ago. Can't say I was too impressed. IMO, it was too verbose, I'm not an OO fanatic, and some immutable strings turned out to be not quite as immutable as I expected. I had a brief toy around with Java using Xcode very recently, and I was able to figure out how to download webpages easy enough (I do this to scrape stock quotes). I felt fairly confident that I could achieve what I wanted in Java, even though I'm fairly raw with it. I started from a default project using Xcode, and it seemed to generate a lot of base code. I quickly abandoned the Java idea, as I'm not gunning to be a Java developer, and Python seems to do what I want without fuss. I think that's the key to Python. You can do what you want without fuss, and it's copiously documented. From aisaac at american.edu Tue Jun 26 22:35:37 2007 From: aisaac at american.edu (Alan Isaac) Date: Wed, 27 Jun 2007 02:35:37 GMT Subject: guidance needed: best practice for script packaging Message-ID: This is a simple question about actual practice. I just want to know how you (yes you) are approaching this problem. The problem: What is the recommended packaging of demo scripts or test scripts for a package to be distributed to others to "play with". (I.e., without "installing".) Example: Suppose I have the package structure: package/ __init__.py subpackage1/ __init__.py moduleXX.py subpackage2/ __init__.py moduleYY.py Important detail: moduleXX uses a relative import to access moduleYY. The goal: I have a script test.py that I want to distribute with the package. This script will import moduleXX to illustrate or test the module's use. Is it the case that this script cannot reasonably be bundled with `package`? (I.e., within its directory structure.) Note: If I put it in the `subpackage1` directory and just import moduleXX, I will get ValueError: Attempted relative import in non-package Note: If I put it in the `package` directory and import subpackage1.moduleXX, I will get ValueError: Attempted relative import beyond toplevel package Here is one hack, based on a suggestion of Alex Martelli http://mail.python.org/pipermail/python-list/2007-May/438250.html and others. - add a `scripts` subdirectory to `package` - use path manipulation to find the directory holding `package` - insert this directory in sys.path This hack "works". However it has also been claimed that this approach is an insane for any shared code. Is it? If so, what is best practice? Note: I do not want to assume the package will be installed: a user should be able to play with it without installing it. This is a repeat question. The usual rule is, if you do not get an answer, you are asking the question in an unhelpful way. If my question is still unclear, I would appreciate any leads on how to clarify it. Thank you, Alan Isaac From doug at alum.mit.edu Fri Jun 29 17:59:05 2007 From: doug at alum.mit.edu (Douglas Alan) Date: Fri, 29 Jun 2007 17:59:05 -0400 Subject: Python's "only one way to do it" philosophy isn't good? References: <7xejjzmk7u.fsf@ruckus.brouhaha.com> <7xy7i7xjl5.fsf@ruckus.brouhaha.com> Message-ID: Lenard Lindstrom writes: > Douglas Alan wrote: >> [I]n Python, you can be 100% sure that your files >> will be closed in a timely manner without explicitly closing them, as >> long as you are safe in making certain assumptions about how your code >> will be used. Such assumptions are called "preconditions", which are >> an understood notion in software engineering and by me when I write >> software. > So documenting an assumption is more effective than removing the > assumption using a with statement? Once again I state that I have nothing against "with" statements. I used it all the time ages ago in Lisp. But (1) try/finally blocks were not to my liking for this sort of thing because they are verbose and I think error-prone for code maintenance. I and many others prefer relying on the refcounter for file closing over the try/finally solution. Consequently, using the refcounter for such things is a well-entrenched and succinct idiom. "with" statements are a big improvement over try/finally, but for things like file closing, it's six of one, half dozen of the other compared against just relying on the refcounter. (2) "with" statements do not work in all situations because often you need to have an open file (or what have you) survive the scope in which it was opened. You may need to have multiple objects be able to read and/or write to the file. And yet, the file may not want to be kept open for the entire life of the program. If you have to decide when to explicitly close the file, then you end up with the same sort of modularity issues as when you have to free memory explicitly. The refcounter handles these sorts of situations with aplomb. (3) Any code that is saving tracebacks should assume that it is likely to cause trouble, unless it is using code that is explicitly documented to be robust in the face of this, just as any code that wants to share objects between multiple threads should assume that this is likely to cause trouble, unless it is using code that is explicitly documented to be robust in the face of this. (4) Any code that catches exceptions should either return soon or clear the exception. If it doesn't, the problem is not with the callee, but with the caller. (5) You don't necessarily want a function that raises an exception to deallocate all of its resources before raising the exception, since you may want access to these resources for debugging, or what have you. |>oug From nick at craig-wood.com Mon Jun 4 05:30:05 2007 From: nick at craig-wood.com (Nick Craig-Wood) Date: Mon, 04 Jun 2007 04:30:05 -0500 Subject: Non-blocking subprocess call References: <442be$4661b3e7$4275d90a$6641@FUSE.NET> Message-ID: Kevin Walzer wrote: > I'm currently using os.popen in an application of mine, which calls for > non-blocking data, in this fashion: > > self.file = os.popen('echo %s | sudo -S /sw/bin/fink -y install %s' % > (self.passtext, self.packagename), 'r', os.O_NONBLOCK) > > What is the equivalent/comparable call in the new subprocess module? I > can't find any reference in the Python docs to non-blocking > streams. You'll probably be better off with the pexpect module for this http://pexpect.sourceforge.net/ Doesn't work on windows. Looks like you are doing OS X though so should work fine there -- Nick Craig-Wood -- http://www.craig-wood.com/nick From eugene.morozov at gmail.com Thu Jun 21 04:47:46 2007 From: eugene.morozov at gmail.com (eugene.morozov at gmail.com) Date: Thu, 21 Jun 2007 08:47:46 -0000 Subject: Indenting in Emacs Message-ID: <1182415666.423187.274240@u2g2000hsc.googlegroups.com> Hello, Does anyone know how to make python-mode correctly indent nested lists and dictionaries. I hate indenting Django url patterns and Zope Archetypes schemas by hand, because python-mode indents them in incorrect and ugly way. Here's how it should be: StringField('reference', widget=StringWidget( description='Position reference' )), Here's how python-mode indents this code: schema = BaseSchema.copy() + Schema(( StringField('reference', widget=StringWidget( description='Position reference' )), I can provide examples of how ugly it indents nested dictionaries/ lists/tuples, but I think that everyone using emacs already have seen that. py-version is 4.78 Are we doomed to manually indent python lists in Emacs? I didn't find any patches fixing indentation in python-mode. Eugene From jmcbray at carcosa.net Fri Jun 22 16:53:07 2007 From: jmcbray at carcosa.net (Jason F. McBrayer) Date: Fri, 22 Jun 2007 16:53:07 -0400 Subject: rsync module? References: Message-ID: "Evan Klitzke" writes: > Are there any python modules for accessing rsync from python? I would > like to be able to rsync files from a python script to a remote server > running an rsync daemon. I'm well aware that I can invoke rsync using > subprocess, os.system, etc., but I am curious if there is a way to do > it directly. I'm not aware of a standalone rsync module for Python, but duplicity (http://www.nongnu.org/duplicity/) provides python bindings for librsync for its own use. You could pull those in to your project. -- +-----------------------------------------------------------+ | Jason F. McBrayer jmcbray at carcosa.net | | If someone conquers a thousand times a thousand others in | | battle, and someone else conquers himself, the latter one | | is the greatest of all conquerors. --- The Dhammapada | From rw at smsnet.pl Thu Jun 14 16:08:18 2007 From: rw at smsnet.pl (Rob Wolfe) Date: Thu, 14 Jun 2007 22:08:18 +0200 Subject: Efficient way of generating original alphabetic strings like unix file "split" References: <1181846461.238047.84140@j4g2000prf.googlegroups.com> Message-ID: <87d4zyqoy5.fsf@merkury.smsnet.pl> py_genetic writes: > Hi, > > I'm looking to generate x alphabetic strings in a list size x. This > is exactly the same output that the unix command "split" generates as > default file name output when splitting large files. > > Example: > > produce x original, but not random strings from english alphabet, all > lowercase. The length of each string and possible combinations is > dependent on x. You don't want any repeats. > > [aaa, aab, aac, aad, .... aax, ...... bbc, bbd, .... bcd] > > I'm assumming there is a slick, pythonic way of doing this, besides > writing out a beast of a looping function. I've looked around on > activestate cookbook, but have come up empty handed. Any suggestions? You didn't try hard enough. :) http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/190465 -- HTH, Rob From p at ulmcnett.com Thu Jun 14 10:06:39 2007 From: p at ulmcnett.com (Paul McNett) Date: Thu, 14 Jun 2007 07:06:39 -0700 Subject: Build EXE on Mac OsX 10.4 In-Reply-To: References: <1181762699.145088.159500@j4g2000prf.googlegroups.com> <46705507.4000201@ulmcnett.com> Message-ID: <46714B6F.7080106@ulmcnett.com> Sherm Pendley wrote: > "Gabriel Genellina" writes: > >> En Wed, 13 Jun 2007 17:35:19 -0300, Paul McNett

      escribi?: >> >>> Tempo wrote: >>>> Has anyone sucesfully built a *.exe file on a mac operating system >>>> before from a *.py file? I have been trying to do this with >>>> pyinstaller, but I keep getting errors and I don't know how to >>>> install [...] >>> You need to build Mac Apps on Mac, Windows EXE's on Windows, and Linux >>> ELF's on Linux. You can't build a windows.exe from Mac, just as you >>> can't build a mac.app from Windows. >> That's not entirely true. gcc on linux can generate a Windows EXE, and >> using: python setup.py bdist_wininst, you can generate a complete >> binary installer for Windows. I'm not sure if this can be done on a >> Mac too. > > In principle, certainly - there's even a MacPort package for a complete > cygwin installation. I've built a number of packages with it - SDL and > several related libraries, for instance. There are also ELF cross-compiler > MacPort packages, presumably for building Linux binaries. > > On the other hand, I *haven't* tried any of those compilers with setup.py, > and I have no idea if it can support those targets in practice. :-( There's the rub. In practice, it is hard enough getting my setup.py correct for building a nice windows.exe from Windows. Plus, the first thing I want to do after building an exe is *test* it on the target platform... -- pkm ~ http://paulmcnett.com From apardon at forel.vub.ac.be Mon Jun 18 06:44:14 2007 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 18 Jun 2007 10:44:14 GMT Subject: a_list.count(a_callable) ? References: <1181850818.567840.251090@x35g2000prf.googlegroups.com> <1181853479.914070.217270@i13g2000prf.googlegroups.com> <1181855184.511137.100870@z28g2000prd.googlegroups.com> <1181916937.648267.163070@z28g2000prd.googlegroups.com> Message-ID: On 2007-06-15, Ping wrote: >> >> sum(1 for i in a_list if a_callable(i)) >> >> -- >> Carsten Haesehttp://informixdb.sourceforge.net > > This works nicely but not very intuitive or readable to me. > > First of all, the generator expression makes sense only to > trained eyes. Secondly, using sum(1 ...) to mean count() > isn't very intuitive either. > > I would still prefer an expression like a_list.count(a_callable), > which is short, clean, and easy to understand. :) However, > it does produce ambiguities if a_list is a list of callables. > Should the count() method match values or check return values > of a_callable? There are several possible designs but I'm not > sure which is better. If you want to check return values, I would thing your callable argument should make the call. Something like: def returns_less_than_three(func): return func() < 3 ls.count(returns_less_than_three) Checking the return values implictly, would make it vey hard if not impossible to check against the callables themselves if you want to. -- Antoon Pardon From rh00667 at gmail.com Wed Jun 6 12:47:35 2007 From: rh00667 at gmail.com (rhXX) Date: Wed, 06 Jun 2007 16:47:35 -0000 Subject: lists - append - unique and sorted In-Reply-To: References: <1181143597.563633.241640@o5g2000hsb.googlegroups.com> Message-ID: <1181148455.348104.275230@m36g2000hse.googlegroups.com> On Jun 6, 6:35 pm, Josiah Carlson wrote: ok, tks to all for ur help and comments!!! > Neil Cerutti wrote: > > On 2007-06-06, rhXX wrote: > >> and/or > > >> - SORTED - INSERT in the correct place using some criteria? > > > Consult the Python Docs about the heapq module. > > Heaps (as produced by heapq) are not sorted. This will not produce > correct results unless one then pops everything and de-dupes the output. > > As Diez has already said, 'use the bisect module' . > > - Josiah From http Mon Jun 18 18:56:03 2007 From: http (Paul Rubin) Date: 18 Jun 2007 15:56:03 -0700 Subject: cStringIO unicode weirdness Message-ID: <7x7iq0j2ik.fsf@ruckus.brouhaha.com> Python 2.5 (r25:51908, Oct 6 2006, 15:24:43) [GCC 4.1.2 20060928 (prerelease) (Ubuntu 4.1.1-13ubuntu4)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import StringIO, cStringIO >>> StringIO.StringIO('a').getvalue() 'a' >>> cStringIO.StringIO('a').getvalue() 'a' >>> StringIO.StringIO(u'a').getvalue() u'a' >>> cStringIO.StringIO(u'a').getvalue() 'a\x00\x00\x00' >>> I would have thought StringIO and cStringIO would return the same result for this ascii-encodeable string. Worse: >>> StringIO.StringIO(u'a').getvalue().encode('utf-8').decode('utf-8') u'a' does the right thing, but >>> cStringIO.StringIO(u'a').getvalue().encode('utf-8').decode('utf-8') u'a\x00\x00\x00' looks bogus. Am I misunderstanding something? From vedrandekovic at v-programs.com Fri Jun 22 09:41:31 2007 From: vedrandekovic at v-programs.com (vedrandekovic at v-programs.com) Date: Fri, 22 Jun 2007 06:41:31 -0700 Subject: Changing the names of python keywords Message-ID: <1182519691.290422.134390@n60g2000hse.googlegroups.com> Hello again, Thanks for everything previously, I was change the grammar and Lib/ keyword.py, now Python recognize "koristiti" as a keyword, but that is not enough: when I write in my python shell: >>> koristiti os # "koristiti" get keyword "color", but I get error: File "", line 1 koristi os ^ SyntaxError: invalid syntax and now, when I write: >>> import os # "import" don't get keyword "color" but still working Please help me, thanks!!!!!!!!!!!!!!!! From davelist at mac.com Sat Jun 9 16:02:07 2007 From: davelist at mac.com (davelist at mac.com) Date: Sat, 9 Jun 2007 16:02:07 -0400 Subject: running python scripts via crontab In-Reply-To: <501094.52491.qm@web54509.mail.yahoo.com> References: <501094.52491.qm@web54509.mail.yahoo.com> Message-ID: On Jun 9, 2007, at 9:10 AM, Mr SZ wrote: > Hello all, > I wrote a simple python script to send mail via smtp to my gmail > acc.I can run it as python /home/phil/Desktop/smtp.py but when I > add the same to my crontab as > > * * * * * /usr/bin/python2.5 /home/phil/Desktop/smtp.py > > ,it doesn't run.I checked the process by using top command and > python did start a thread but died soon. > > I need some help here. > > The python script uses tls-lite lib to use tls over smtp. > One possible issue is that I believe the crontab entries to not run with the same environment that your normal user login does. If you set any environment variables in your .bashrc or .bash_profile file, try including those lines at the top of your crontab file. Here's the first line in my crontab file (this is on OS X, but the issue is likely the same on Linux). PATH=/opt/local/bin:/sw/bin:/sw/sbin:/usr/bin:/bin:/usr/sbin:/sbin:/ usr/X11R6/bin:/Users/dreed/bin And are you really wanting to run the script every single minute (or is that just for testing)? Dave From kyosohma at gmail.com Wed Jun 20 17:13:36 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Wed, 20 Jun 2007 14:13:36 -0700 Subject: wxpython: Redirect the stdout to a textctrl In-Reply-To: <1182373417.606213.19190@g37g2000prf.googlegroups.com> References: <1182284207.035976.92170@q19g2000prn.googlegroups.com> <1182287230.696722.247930@u2g2000hsc.googlegroups.com> <1182373417.606213.19190@g37g2000prf.googlegroups.com> Message-ID: <1182374016.548332.74970@w5g2000hsg.googlegroups.com> On Jun 20, 4:03 pm, Alejandro wrote: > On Jun 19, 5:07 pm, kyoso... at gmail.com wrote:> Give this a try: > > > > > [good piece of code] > > > > > It worked like a charm! Thanks. > > I still don't understand why my initial aproach didn't work as > expected. > > Regards, > Alejandro. Alejandro, Yeah, I'm not sure what the deal is with your code. But I've never used the LogTextCtrl widget. You might ask why it doesn't work directly by posting to the wxPython user's group here: http://www.wxpython.org/maillist.php Mike From alexandru.lz at gmail.com Mon Jun 18 05:57:24 2007 From: alexandru.lz at gmail.com (alexandru.lz at gmail.com) Date: Mon, 18 Jun 2007 02:57:24 -0700 Subject: The Modernization of Emacs In-Reply-To: <1182149920.511188.241520@q75g2000hsh.googlegroups.com> References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182149920.511188.241520@q75g2000hsh.googlegroups.com> Message-ID: <1182160644.003705.274820@w5g2000hsg.googlegroups.com> > > > * Reduce the use of the word "buffer" in the emacs documentation. > > Call it "opened file" or "unsaved document". > > As far as I understand the concept of buffer is much much wider than > of "unsaved document" or "file". Should we call dired buffer as > "unsaved document"? > It is much wider, which is why it was used in the first place. Considering most of Xah's article, I think an animated paperclip (maybe in ASCII art) should be the top priority for emacs developers. This would be an important step in modernizing emacs. Leaving this aside, I'm also taking a wild guess that some *nices (not just Linux distros, but also *BSD, Solaris etc.) could well provide a binary package of emacs compiled with its GTK UI, besides those they're already providing (nox and the ugly one for X). It's a fair assumption to consider that not anyone has GTK, but it's common enough to provide an alternative to that stumpy Xlib-based (I think :-\) UI that's default in just about every binary package around. It's not just that it looks ugly, it's also somewhat awkward at times. From jeffrey.rollin at gmail.com Tue Jun 12 06:22:55 2007 From: jeffrey.rollin at gmail.com (Jeff Rollin) Date: Tue, 12 Jun 2007 11:22:55 +0100 Subject: Newsgroup query References: Message-ID: In the last episode, on Tuesday 26 Sivan 5767 11:21, Marc 'BlackJack' Rintsch wrote: > In , Jeff Rollin wrote: > >> Why do I not see my messages with attached files in the newsgroup, and is >> there any way to configure this? > > No, most news servers strip attachments from postings in non-binary > groups. It's a plain text medium. > > Ciao, > Marc 'BlackJack' Rintsch OK, I'll keep that in mind. TVM. Jeff From steve at REMOVE.THIS.cybersource.com.au Fri Jun 22 22:36:40 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sat, 23 Jun 2007 12:36:40 +1000 Subject: Adding method to a class on the fly References: <1182538969.522044.209560@q19g2000prn.googlegroups.com> <1182543862.369337.36880@z28g2000prd.googlegroups.com> <1182547065.295969.258820@g37g2000prf.googlegroups.com> <1182547724.690874.279230@g37g2000prf.googlegroups.com> <1182548694.545515.81060@e9g2000prf.googlegroups.com> Message-ID: On Fri, 22 Jun 2007 14:44:54 -0700, John Henry wrote: > The above doesn't exactly do I what need. I was looking for a way to > add method to a class at run time. > > What does work, is to define an entire sub-class at run time. Like: > > class DummyParent: > def __init__(self): > return > > def method_static(self, text): > print text > return > > text = "class Dummy(DummyParent):" > text += "\n\t" + "def __init(self):" > text += "\n\t" + "\tDummyParent.__init__(self)" > text += "\n\t" + "def method_dynamic(self):" > text += "\n\t" + "\tself.method_static(\"it's me\")" > > exec text (By the way, you misspelled __init__.) The correct way to add methods to an instance is with the instancemethod() function. class Parrot: def __init__(self): import new # define a function def method_dynamic(self, *args): args.insert(0, "hello, it's me!") return self.method_static(*args) # convert it into an instance method method = new.instancemethod(function, self, self.__class__) # add it to self self.method_dynamic = method def method_static(self, text): return text And here is how I use it: >>> p = Parrot() >>> p.method_dynamic() # call from an instance "it's me" >>> Parrot.method_dynamic # does it exist in the class? Traceback (most recent call last): File "", line 1, in ? AttributeError: class Parrot has no attribute 'method_dynamic' BUT, having said all that, are you sure this is what you want to do? This is probably a better way to get the same results: class Parrot: def __init__(self): self.text = "hello, it's me!" def method_dynamic(self): return self.method_static(self.text) def method_static(self, text): return text Earlier in the thread, you said you wanted a CLASS method, which is very different. You can use the classmethod built-in function (no need to import new) to create class methods: class Parrot: def method_dynamic(cls): return cls.method_static(cls(), "hello it's me") # or alternatively cls().method_static("hello it's me") method_dynamic = classmethod(method_dynamic) def method_static(self, text): return text Note: if you are using recent versions of Python, instead of saying "method = classmethod(method)" AFTER the block, you can use a decorator before the block. Making method_dynamic a class method and calling an instance method is not a good way of doing things, since the class method has to create a new instance before calling method_static, only to throw it away afterwards. That is wasteful and could be very expensive. A better way is to change your class so that method_static is a class method too, especially since it doesn't use self: class Parrot: @classmethod def method_dynamic(cls): return cls.method_static("hello it's me") @classmethod def method_static(cls, text): return text (Actually, since method_static doesn't even use the class, you could use staticmethod instead of classmethod. Remember to remove the "cls" argument.) Hope this helps, -- Steven. From martin at v.loewis.de Tue Jun 12 02:20:21 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 12 Jun 2007 08:20:21 +0200 Subject: Setting the encoding in the basic auth header In-Reply-To: <1181627140.208015.256160@q19g2000prn.googlegroups.com> References: <1181627140.208015.256160@q19g2000prn.googlegroups.com> Message-ID: <466E3B25.80304@v.loewis.de> > It seems that both browsers are using the iso-8859-1 charset. Is there > any way I can get them to encode the data with utf-8 instead? As a further follow-up, see https://bugzilla.mozilla.org/show_bug.cgi?id=41489 They explain that *TEXT is defined in RFC 2616, which specifies that non-ASCII characters must be MIME-header-encoded. So 0BA4 should be encoded as '=?utf-8?b?4K6k?=', according to the specification. No browser currently implements that. Regards, Martin From timid.Gentoo at gmail.com Thu Jun 28 17:06:14 2007 From: timid.Gentoo at gmail.com (_spitFIRE) Date: Thu, 28 Jun 2007 14:06:14 -0700 Subject: exception from a thread Message-ID: <1183064774.900116.198270@k79g2000hse.googlegroups.com> assume a scenario, where there is a class that for doing some work, spawns lot of threads. class X: def __init__(self): # Spawns some threads to # do some work now, assuming that at least one of the threads encounters a problem while doing work and throws an exception. Would I be able to handle that error in the caller class? When I try to do this, I see that the errors thrown by the threads never cascade to this caller :( From http Mon Jun 25 21:47:04 2007 From: http (Paul Rubin) Date: 25 Jun 2007 18:47:04 -0700 Subject: Collections of non-arbitrary objects ? References: <1182449993.223262.229500@z28g2000prd.googlegroups.com> <87k5twx4hf.fsf@benfinney.id.au> <1182559502.069773.321620@i38g2000prf.googlegroups.com> <87wsxvrzsj.fsf@benfinney.id.au> <1182620734.940718.196520@e16g2000pri.googlegroups.com> <467ed491$0$27132$426a34cc@news.free.fr> <1182780863.067601.89320@d30g2000prg.googlegroups.com> <46801791$0$32172$426a34cc@news.free.fr> Message-ID: <7x7iprlc6f.fsf@ruckus.brouhaha.com> Bruno Desthuilliers writes: > You know, Python is now something like 17 years old, and is used by a > *lot* of peoples for a *lot* of programs - some of them far from > trivial. I think you can be confident in this experience. IOW, just > write your code, and you'll find out that the kind of problems you > seem to fear so much will not happens that often. Assembler and Cobol have been around even longer... From jadestar at idiom.com Tue Jun 12 20:56:51 2007 From: jadestar at idiom.com (James T. Dennis) Date: Wed, 13 Jun 2007 00:56:51 -0000 Subject: Convert String to Int and Arithmetic References: <1181658761.300066.118210@a26g2000pre.googlegroups.com> Message-ID: <1181696211.88974@smirk> tereglow wrote: > Hello, > I am a complete newbie to Python and am accustomed to coding in PHP/ > Perl/Shell. I am trying to do the following: > I have a string: > cpuSpeed = 'Speed: 1000000000' > What I would like to do is extract the '1000000000' from the string, > and divide that by 1000 twice to get the speed of a processor in MHz. > My understanding is that I need to 'import re' and then use re.split > to get the first part done. The second part confuses me because I'm > unable to convert the '1000000000' to an integer to run division > against it. > Basically, I want to come out with 1000 for the above string. Any > help would be appreciated. > Tom The most obvious approach, rather hard-coded to the example, would be: cpuMhz = float(cpuSpeed[6:]) / 10 ** 6 ... take a "slice" of the string, cpuSpeed, from character seven (zero-based) to the end of the string (cpuSpeed[6:]) and try to convert it into a floating point number (with the float() function) and then divide that by the one million -- Jim Dennis, Starshine: Signed, Sealed, Delivered From rtw at freenet.co.uk Fri Jun 15 18:12:00 2007 From: rtw at freenet.co.uk (Rob Williscroft) Date: Fri, 15 Jun 2007 17:12:00 -0500 Subject: Get the current date, python 2.2 References: Message-ID: On Fri, 15 Jun 2007 14:46:20 -0700, nano wrote: > In article , rtw at freenet.co.uk > says... >> On Fri, 15 Jun 2007 14:30:36 -0700, nano wrote: >> >> > Using python 2.2 what is the simplest way to get the current date >> > value? I have looked in so many places. The question is often asked >> > and the usual response indicates how to get the current date and time >> > like >> > >> > now = time.localtime() >> > >> > I want just the date, like 2007-06-15. The value will go into a >> > postgresql Date type column. >> >> >>> import datetime >> >>> d = datetime.date.today() >> >>> d.isoformat() >> '2007-06-15' >> >>> >> >>> >> Rob. >> > Thanks, I'd read that today() was only good for 2.3? Right I missed that, though its actually the datetime module that is new in 2.3. This should do though: >>> import time >>> time.strftime( "%Y-%m-%d" ) '2007-06-15' >>> -- Rob. From malaclypse2 at gmail.com Wed Jun 27 15:19:24 2007 From: malaclypse2 at gmail.com (Jerry Hill) Date: Wed, 27 Jun 2007 15:19:24 -0400 Subject: Zip File Woes In-Reply-To: <4966172950419983052@unknownmsgid> References: <4966172950419983052@unknownmsgid> Message-ID: <16651e80706271219q500fc01dx10db65f899d989e7@mail.gmail.com> On 6/27/07, Robert Rawlins - Think Blue wrote: > zip = zipfile.ZipFile('Media/Media.zip', 'r') Shouldn't you open this file in binary mode? It shouldn't make any difference on unix machines, but will possibly break under windows. That may also explain why it works properly in one environment, and not in another. -- Jerry From bignose+hates-spam at benfinney.id.au Wed Jun 20 22:28:15 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 21 Jun 2007 12:28:15 +1000 Subject: PEP 3107 and stronger typing (note: probably a newbie question) References: <1182369568.941307.316260@p77g2000hsh.googlegroups.com> Message-ID: <87vedivy68.fsf@benfinney.id.au> Stephen R Laniel writes: > Perhaps it would help for me to explain what I'd like. Thanks for taking the time to think about the request and re-formulate it. > Under both Perl and Python, I've found myself > having/wanting to write things like so: > > def my_func( int_arg, str_arg ): > try: > int_arg = int( int_arg ) > str_arg = str( str_arg ) > except ValueError: > sys.stderr.write( "Args are not of the right type\n" ) > sys.exit(1) The first question that comes to mind -- and you'll find this question asked of hundreds of people who come to this list with similar stated goals -- is this: Why are you doing the above? In Python, the pattern is to allow that exception to propagate back to the code that tried to use the function, which is the one that is apparently using the function incorrectly. That is, you haven't actually told us what you'd like. You've shown us a function that effectively does nothing but create a str and and int -- and then discard them. What does this function need to do that you want to catch an exception and abort inside the function? -- \ "It is well to remember that the entire universe, with one | `\ trifling exception, is composed of others." -- John Andrew | _o__) Holmes | Ben Finney From rustompmody at gmail.com Sun Jun 24 23:24:55 2007 From: rustompmody at gmail.com (Rustom Mody) Date: Mon, 25 Jun 2007 08:54:55 +0530 Subject: The Modernization of Emacs: terminology buffer and keybinding Message-ID: Hi folks! Dont want to spoil the fun of a real flame war here but what I want to ask is directly relevant to emacs in python [And the answers may even add some light to the current heat :-) ] I will be training a bunch of kids for using python in a data-center linux-sysadmin context. I intend to use emacs [apologies twisted -- cant change my anti-rodent preferences after 20 years ] but not clear what are the best setups. My questions are 1. Which python mode should one use? It seems there is one from python and one from emacs and both are deliberately named so as to be confusable!! I would like one that gives... 2. Good support for debugging: I hear pdbtrack is better than pdb -- but I am not able to figure how to use it. 3. Is it possible to get brief help on methods/functions using mouse-hovering/F1 rather than having to go out to pydoc etc 4. Also maybe a (minor?) mode to convert selections of interpreter text into doctests? 5. The menu contains something called IM-python but that contains nothing except *rescan* 6. Turning off semantic. semantic (is that the same as fly-make??) seems to randomly get into 99% CPU usage. How to turn it off? From aleax at mac.com Sat Jun 16 01:25:38 2007 From: aleax at mac.com (Alex Martelli) Date: Fri, 15 Jun 2007 22:25:38 -0700 Subject: Python's "only one way to do it" philosophy isn't good? References: <1181368143.874341.273140@r19g2000prf.googlegroups.com> Message-ID: <1hzrsp4.7vjuav1aegg0tN%aleax@mac.com> Neil Cerutti wrote: > On 2007-06-12, Antoon Pardon wrote: > > On 2007-06-11, Terry Reedy wrote: > >> More so than supporters of most other languages, in particular > >> Scheme? > > > > Well to my knowledge (which could be vastly improved), scheme > > doesn't have some Zen-rules that include something like this. > > > > I tried to google for similar remarks in relation to scheme but > > I got no results. Maybe your google skills are better. > > It's in _The Revised^%d Report on Scheme_, Introduction: > > 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. > > Of course, that was written well before Scheme had most of its > current features. The "Spirit of C" section in the preface of the ISO Standard for C phrases this principle as "Provide only one way to do an operation". Despite the phrasing variations, this commonality goes well with my perception that, at their roots, Scheme, C and Python share one philosophical underpinning (one that's extremely rare among programming languages as a whole) -- an appreciation of SIMPLICITY AND UNIFORMITY as language characteristics. Alex From __peter__ at web.de Thu Jun 28 12:18:05 2007 From: __peter__ at web.de (Peter Otten) Date: Thu, 28 Jun 2007 18:18:05 +0200 Subject: Collections of non-arbitrary objects ? References: <1182449993.223262.229500@z28g2000prd.googlegroups.com> <87k5twx4hf.fsf@benfinney.id.au> <1182559502.069773.321620@i38g2000prf.googlegroups.com> <87wsxvrzsj.fsf@benfinney.id.au> <1182620734.940718.196520@e16g2000pri.googlegroups.com> <467ed491$0$27132$426a34cc@news.free.fr> <1182780863.067601.89320@d30g2000prg.googlegroups.com> <46801791$0$32172$426a34cc@news.free.fr> <1182863704.364272.5950@i13g2000prf.googlegroups.com> <46812159$0$24920$426a74cc@news.free.fr> <1182961835.134162.311670@x35g2000prf.googlegroups.com> <4682ca40$0$14981$426a74cc@news.free.fr> <1183046497.377835.125290@e16g2000pri.googlegroups.com> Message-ID: walterbyrd wrote: > I can do this: > x = tuple(sorted(list((3,2,1)))) The list() conversion is superfluous: >>> tuple(sorted((3,2,1))) (1, 2, 3) Peter From carsten at uniqsys.com Thu Jun 21 09:03:03 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Thu, 21 Jun 2007 09:03:03 -0400 Subject: Reading multiline values using ConfigParser In-Reply-To: <1182394281.778904.315430@z28g2000prd.googlegroups.com> References: <1182358231.269388.250510@m36g2000hse.googlegroups.com> <1182394281.778904.315430@z28g2000prd.googlegroups.com> Message-ID: <1182430983.3376.18.camel@dot.uniqsys.com> On Thu, 2007-06-21 at 02:51 +0000, Phoe6 wrote: > On Jun 20, 10:35 pm, "John Krukoff" wrote: > > > > Is there anyway, I can include multi-line value in the configfile? I > > > > > Following the link to RFC 822 (http://www.faqs.org/rfcs/rfc822.html) > > indicates that you can spread values out over multiple lines as long as > > there is a space or tab character imeediately after the CRLF. > > Thanks for the response. It did work! > > >>> config = ConfigParser() > >>> config.read("Testcases.txt") > ['Testcases.txt'] > >>> output = config.get("Information", "Testcases") > >>> print output > > tct123 > tct124 > tct125 > >>> output > '\ntct123\ntct124\ntct125' > >>> > > However, as I am going to provide Testcases.txt to be "user editable", > I cannot assume or "ask users" to provide value testcases surronded by > spaces. I got to figure out a workaround here. Since you don't actually need a multi-line entry but rather a list of single-line entries, you could ask your users to enter something like this: TestcaseCount=3 Testcase1=tct123 Testcase2=tct124 Testcase3=tct125 HTH, -- Carsten Haese http://informixdb.sourceforge.net From CarlosLuis.Perez at medianet.es Thu Jun 14 20:42:02 2007 From: CarlosLuis.Perez at medianet.es (=?iso-8859-1?Q?Carlos_Luis_P=E9rez_Alonso?=) Date: Fri, 15 Jun 2007 02:42:02 +0200 Subject: Problems with regular expressions Message-ID: <37BCDB14F06B98469A85DEC4771763B574C6EF@exch01.medianet.es> I have the next piece of code: ------------------------------------------------------------------------ if re.search('^(taskid|bugid):\\d+',logMessage): return 0 else: sys.stderr.write("El comentario tiene que contener el taskid:#### o el bugid:####") return 1 ------------------------------------------------------------------------- The regular exprexi?n is "^(taskid|bugid):\\d+" Mi problem is that if logMessage == "taskid:234" the regular expression matched teorically, but the result is always "None" and the function returns 1. ?Does anybody has an idea of what is happening here? Thanks From anamax at earthlink.net Wed Jun 27 18:32:42 2007 From: anamax at earthlink.net (Andy Freeman) Date: Wed, 27 Jun 2007 15:32:42 -0700 Subject: Python's "only one way to do it" philosophy isn't good? In-Reply-To: References: <7x3b0nmkk6.fsf@ruckus.brouhaha.com> <7xejjzmk7u.fsf@ruckus.brouhaha.com> <7xy7i7xjl5.fsf@ruckus.brouhaha.com> <1182872972.417776.78650@o11g2000prd.googlegroups.com> <7xtzsuy7fe.fsf@ruckus.brouhaha.com> <1182955743.076746.114790@i38g2000prf.googlegroups.com> Message-ID: <1182983562.095262.127850@x35g2000prf.googlegroups.com> On Jun 27, 8:09 am, "Chris Mellon" wrote: > On 6/27/07, Andy Freeman wrote: > > It's easy enough to get around the lack of objectness and add the > > equivalent of an iterator iterface, in either language. The fact that > > lisp folks haven't bothered suggests that this isn't a big enough > > issue. > > Is this where I get to call Lispers Blub programmers, because they > can't see the clear benefit to a generic iteration interface? The "Blub" argument relies on inability to implement comparable functionality in "blub". (For example, C programmers don't get to call Pythonists Blub programmers because Python doesn't use {} and Pythonistas don't get to say the same about C programmers because C doesn't use whitespace.) Generic iterators can be implemented by lisp programmers and some have. Others haven't had the need. > > The difference is that lisp users can easily define python-like for > > while python folks have to wait for the implementation. > > Yes, but Python already has it (so the wait time is 0), and the Lisp > user doesn't. "for" isn't the last useful bit of syntax. Python programmers got to wait until 2.5 to get "with". Python 2.6 will probably have syntax that wasn't in Python 2.5. Lisp programmers with a syntax itch don't wait anywhere near that long. From hpasanen at gmail.com Tue Jun 26 07:53:05 2007 From: hpasanen at gmail.com (harri) Date: Tue, 26 Jun 2007 04:53:05 -0700 Subject: PEP 3107 and stronger typing (note: probably a newbie question) In-Reply-To: <467a9209$0$22165$426a74cc@news.free.fr> References: <1182369568.941307.316260@p77g2000hsh.googlegroups.com> <5dveb4F360un0U1@mid.individual.net> <467a9209$0$22165$426a74cc@news.free.fr> Message-ID: <1182858785.886469.93060@n60g2000hse.googlegroups.com> Bruno Desthuilliers wrote: [...] > > It seems obvious from this that static typecheking would require > dropping all dynamism from Python - then turning it into another, very > different (and mostly useless as far as I'm concerned) language. IOW : > you can't have Python *and* static typechecks - both are mutually > exclusive. Hence my answer : if you want static typecheking, you'll have > to use another language - one way or another. Well, static typing for me is usually the way to get the last speed required once the algorithmic improvements are exhausted. The language Pyrex uses combines dynamic and static typing in a very useful manner. "Practicality beats purity" Harri From andre.roberge at gmail.com Tue Jun 26 16:46:27 2007 From: andre.roberge at gmail.com (=?iso-8859-1?B?QW5kcuk=?=) Date: Tue, 26 Jun 2007 20:46:27 -0000 Subject: problem mixing gettext and properties In-Reply-To: <1182885474.515335.242470@e9g2000prf.googlegroups.com> References: <1182880358.100599.139120@j4g2000prf.googlegroups.com> <1182885474.515335.242470@e9g2000prf.googlegroups.com> Message-ID: <1182890787.295156.161000@g37g2000prf.googlegroups.com> On Jun 26, 4:17 pm, Andr? wrote: > On Jun 26, 3:56 pm, Peter Otten <__pete... at web.de> wrote: > > > > > Andr? wrote: > > > I've encountered a problem using gettext with properties while using a > > > Python interpreter. > > > > Here's a simple program that illustrate the problem. > > > ============== > > > # i18n_test.py: test of gettext & properties > > > > import gettext > > > > fr = gettext.translation('i18n_test', './translations', > > > languages=['fr']) > > > _ = fr.gettext # untested > > > > help = _("Help me!") > > > > class Test_i18n(object): > > > def get(self): > > > __help = _("HELP!") > > > return __help > > > help_prop = property(get, None, None, 'help') > > > > test = Test_i18n() > > > > print help > > > print test.help_prop > > > #### end of file > > > > To run the above program, you need to have the strings translated and > > > the proper ".po" and ".mo" files created. (for those interested, I > > > can send the whole lot in a zip file) > > > > If I run the program as is, the output is: > > > Aidez-moi! > > > AIDE!!! > > > > Ok, let's try with the Python interpreter: > > > > ActivePython 2.4.2 Build 248 (ActiveState Corp.) based on > > > Python 2.4.2 (#67, Oct 30 2005, 16:11:18) [MSC v.1310 32 bit (Intel)] > > > on win32 > > > Type "help", "copyright", "credits" or "license" for more information. > > >>>> import i18n_test > > > Aidez-moi! > > > AIDE!!! > > > > # No surprise there so far. > > > >>>> print i18n_test.help > > > Aidez-moi! > > >>>> print i18n_test.test.help_prop > > > AIDE!!! > > >>>> i18n_test.help > > > 'Aidez-moi!' > > > > # all of the above are as expected; now for the first surprise > > > >>>> i18n_test.test.help_prop > > > Traceback (most recent call last): > > > File "", line 1, in ? > > > File "i18n_test.py", line 12, in get > > > __help = _("HELP!") > > > TypeError: 'str' object is not callable > > > > # and a second surprise where we try to repeat something that used to > > > work > > > >>>> print i18n_test.test.help_prop > > > Traceback (most recent call last): > > > File "", line 1, in ? > > > File "i18n_test.py", line 12, in get > > > __help = _("HELP!") > > > TypeError: 'str' object is not callable > > > > #============= > > > > Dare I say: "Help!" I really need to use the above at the > > > interpreter prompt. > > > > Andr? > > > The _ builtin is set to the result of the last expression evaluated by the > > interpreter: > > > >>> for i in range(3): > > > ... i > > ... > > 0 > > 1 > > 2>>> _ > > 2 > > >>> import __builtin__ > > >>> __builtin__._ > > > 2 > > > Therefore you get a name clash with _() as an alias for gettext(). Use > > module-global aliases instead, e. g. > > > _ = fr.gettext > > > in the above code. > > > Peter > > Thanks, that works ... but, [snip...] One more question (back to the original) post. Why does i18n_test.help does the right thing but i18n_test.test.help_prop does not? Both use _() ... Is it because help = _(...) is defined at the module level but test.help_prop is defined locally, and that the lookup for _() is done first locally (finds nothing) and then globally (outside the module scope) ? Andr? From krzysztof.wlodarczyk at mobiltek.pl Tue Jun 19 13:22:41 2007 From: krzysztof.wlodarczyk at mobiltek.pl (=?ISO-8859-2?Q?Krzysztof_W=B3odarczyk?=) Date: Tue, 19 Jun 2007 19:22:41 +0200 Subject: Python/C API bug (multithreading) Message-ID: <467810E1.5050300@mobiltek.pl> Hi, I think I've found a bug in Python/C API and multithreading. I'm currently creating an intrusion detection system based on mobile agents. I have an AgentPlatform (C/C++) and 2 agents on it (2 Python scripts: Snort and Anomaly) These 2 agents are each running its own Python interpreter (both by Py_Run*** stuff). Of course I do have Threading on (I mean there is: PyGILStateEnsure stuff as well). I also have an interface that is used by both agents (Python scripts) to access my Agent Platform (C/C++ program). That interface have one method: AgentPlatform.getPacket() - when I call it in Python - appropriate method AgentPlatform.getPacket() is called in C/C++ AgentPlatform. Between these two moments somthing bad happens. This happens when Snort calls Python's AgentPlatform.getPacket() and just before C/C++'s AgentPlatform.getPacket() is called - another agent - Anomaly Agent calls its Python's AgentPlatform.getPacket(). In this particular moment everything hangs:((((((((((((( Let me show it on an image: http://www.mobiltek.pl/~mrbpl/tmp/PythonBug.JPG Is there any simple way to fix this damned bug?? best regards -- Krzysztof W?odarczyk Centrum Technologii Mobilnych Mobiltek S.A. e-mail: krzysztof.wlodarczyk at mobiltek.pl mobile: 502-525-035 This email is confidential and is intended for receipt solely by the individual or entity to which it is addressed. Any review, use, retention, distribution or disclosure by others is strictly prohibited. If you are not the intended recipient (or authorized to receive for the recipient), please contact the sender by reply email and delete all copies of this message. Thank you. From johnmfisher at comcast.net Thu Jun 14 20:00:19 2007 From: johnmfisher at comcast.net (John Fisher) Date: Thu, 14 Jun 2007 17:00:19 -0700 Subject: OS X install confusion References: <1hzp0kw.4i0y5i1cqnlwoN%johnmfisher@comcast.net> <6b03b$46717b5e$4275d90a$18801@FUSE.NET> <1181842656.810802.24810@x35g2000prf.googlegroups.com> Message-ID: <1hzpj69.1k6hn46vkidfkN%johnmfisher@comcast.net> Ted wrote: > On Jun 14, 1:31 pm, Kevin Walzer wrote: > > John Fisher wrote: > > > Hi Groupies, > > > > > I have an Intel Macbook running OS X 10.4. > > > > > It came installed with Python 2.3.5. I have since installed MacPython > > > with version 2.4.4, cool. > > > > > When I open a bash terminal session and type python, it brings up > > > version 2.3.5. If I type IDLE it brings up version 2.4.4. > > > > > My question: what do I have to do to get it to bring up 2.4.4 with the > > > "python" command? > > > > > Thanks for bringing light to my ignorance. > > > > > JF > > > > Sounds like a path problem. Apple's system Python is installed in > > /usr/bin. Your installation is probably in /usr/local/bin. Edit your > > profile or use the full path. > > > > -- > > Kevin Walzer > > Code by Kevinhttp://www.codebykevin.com > > The default python on tiger (2.3.5) is sym-linked to /usr/bin/python > and /usr/bin/pythonw. > > I found it easier to relink to the new installation path. This also > leaves /usr/bin/python23 and /usr/bin/pythonw23 still linked to the > original version if you want to quickly check something. > > Cheers, > Ted OK, please give a little more information how I can accomplish this "re-link". Thanks, JF From eadmund42 at NOSPAMgmail.com Thu Jun 21 10:49:22 2007 From: eadmund42 at NOSPAMgmail.com (Robert Uhl) Date: Thu, 21 Jun 2007 08:49:22 -0600 Subject: The Modernization of Emacs References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182344981.372713.298580@w5g2000hsg.googlegroups.com> <86y7ieoiv7.fsf@lola.quinscape.zz> <1182347061.347199.133480@g4g2000hsf.googlegroups.com> <874pl2eg2j.fsf@W0053328.mgh.harvard.edu> <1182370016.986915.202150@u2g2000hsc.googlegroups.com> Message-ID: Twisted writes: > > Given that in its out-of-the-box configuration it's well-nigh unusable > without a printed-out "cheat sheet" of some kind, of the sort that > were supposed to have died out in the 80s, getting it customized poses > something of a catch-22 for anyone trying to get started using it. I don't see that. C-h t is your friend if you're starting out. The only keystrokes a user really needs to remember are C-x C-s and C-x C-c; everything else simple text editing needs works as expected (arrow keys, backspace and so forth). Granted, text-mode is friendlier than fundamental-mode. Still, as a pico replacement emacs works well enough--and as the user continue to works, he discovers more and more functionality, eventually having a 10,000-line .emacs... -- Robert Uhl Listening to someone who brews his own beer is like listening to a religious fanatic talk about the day he saw the light. --Ross Murray, Montreal Gazette, 1991 From martin at v.loewis.de Wed Jun 20 01:20:35 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Wed, 20 Jun 2007 07:20:35 +0200 Subject: ARM cross compile - one last problem In-Reply-To: <1182295994.875288.85550@q75g2000hsh.googlegroups.com> References: <1182275375.513700.46290@g4g2000hsf.googlegroups.com> <1182295994.875288.85550@q75g2000hsh.googlegroups.com> Message-ID: <4678B923.60908@v.loewis.de> > Alright, I looked into this a little more, and those symbols > definitely exist in my compiled python executable. How are extensions > linked to the python interpreter? Python assumes that extension modules can be linked against the executable, i.e. that *at run-time* those symbols will get resolved. This works fine for the Unix ELF binary format, but may require certain linker flags, such as --export-dynamic. It doesn't work for Windows PE32, therefore, on Windows, Python compiles the run-time as a DLL (pythonXY.dll), and extension modules link to that. I would expect that Linux on ARM also uses ELF, so dynamic lookup of symbols from the executable should be possible. Do "nm -D --defined-only python" to see whether the symbols are in the *dynamic* symbol table. If not, use the proper linker flag to make them so. Regards, Martin From tjreedy at udel.edu Thu Jun 21 19:33:35 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 21 Jun 2007 19:33:35 -0400 Subject: Python's "only one way to do it" philosophy isn't good? References: <1181368143.874341.273140@r19g2000prf.googlegroups.com><7x3b0nmkk6.fsf@ruckus.brouhaha.com> Message-ID: "Douglas Alan" wrote in message news:lcfy4ljej2.fsf at gaffa.mit.edu... | Steven D'Aprano writes: | | > On Wed, 20 Jun 2007 17:23:42 -0400, Douglas Alan wrote: | | >> Macros are a way to abstract syntax the way that objects are used to | >> abstract data types and that iterators and generators abstract control, | >> etc. | | > But why is the ability to abstract syntax good? | | It allows the community to develop language features in a modular way | without having to sully the code base for the language itself. [etc] Some of the strongest opposition to adding macros to Python comes from people like Alex Martelli who have had experience with them in *multi-person production* projects. He claimed in various posts that the net effect was to reduce productivity. So convince us (and Guido!) that he is wrong ;-) But I would prefer you somehow try to help make usable multi-arg and predicate dispatch a reality. tjr From josiah.carlson at sbcglobal.net Sat Jun 9 18:52:32 2007 From: josiah.carlson at sbcglobal.net (Josiah Carlson) Date: Sat, 09 Jun 2007 22:52:32 GMT Subject: Python's "only one way to do it" philosophy isn't good? In-Reply-To: References: <1181368143.874341.273140@r19g2000prf.googlegroups.com> Message-ID: Alexander Schmolck wrote: > Josiah Carlson writes: > >> James Stroud wrote: >>> Terry Reedy wrote: >>>> In Python, you have a choice of recursion (normal or tail) >>> Please explain this. I remember reading on this newsgroup that an advantage >>> of ruby (wrt python) is that ruby has tail recursion, implying that python >>> does not. Does python have fully optimized tail recursion as described in >>> the tail recursion Wikipedia entry? Under what circumstances can one count >>> on the python interpreter recognizing the possibility for optimized tail >>> recursion? >> Note that Terry said that you could do normal or tail recursion, he didn't >> claim that either were optimized. > > Well yeah, but without the implication how do the two words "or tail" add to > the information content of the sentence? Normal and tail recursion are different, based upon whether or not one can technically considered to be done with the stack frame. def normal(arg): if arg == 1: return 1 return arg * normal(arg-1) def tail(arg, default=1): if arg == 1: return arg * default return tail(arg-1, default*arg) >> As for why tail calls are not optimized out, it was decided that being able >> to have the stack traces (with variable information, etc.) was more useful >> than offering tail call optimization > > I don't buy this. What's more important, making code not fail arbitrarily (and > thus making approaches to certain problems feasible that otherwise wouldn't > be) or making it a be a bit easier to debug code that will fail arbitrarily? > Why not only do tail-call optimization in .pyo files and get the best of both > worlds? I didn't make the decisions, I'm just reporting what was decided upon. Personally, I have never found the lack of tail call optimization an issue for two reasons. The first is because I typically write such programs in an iterative fashion. And generally for recursion for which tail call optimization doesn't work (the vast majority of recursive algorithms I use), I typically write the algorithm recursively first, verify its correctness, then convert it into an iterative version with explicit stack. I find it is good practice, and would be necessary regardless of whether Python did tail call optimization or not. >> (do what I say). > > Where did you say run out of memory and fail? More importantly how do you say > "don't run out of memory and fail"? By virtue of Python's underlying implementation, Python "does what I say", it doesn't "do what I mean". While I may not have explicitly stated "run out of stack space", the underlying implementation *has* limited stack space. You are stating that when you write a tail recursive program, you want Python to optimize it away by destroying the stack frames. And that's fine. There are tail-call optimization decorators available, and if you dig into sourceforge, there should even be a full patch to make such things available in a previous Python. However, Python is not Lisp and is not partially defined by infinite recursion (see sys.setrecursionlimit() ). Instead, it is limited by the C call stack (in CPython), and makes guarantees regarding what will always be available during debugging (the only thing that optimization currently does in Python at present is to discard docstrings). If you want to change what is available for debugging (to make things like tail call optimization possible), you are free to write and submit a PEP. In the mean time, you may need to do some source conversion. - Josiah From showell30 at yahoo.com Mon Jun 4 00:28:16 2007 From: showell30 at yahoo.com (Steve Howell) Date: Sun, 3 Jun 2007 21:28:16 -0700 (PDT) Subject: Python, Dutch, English, Chinese, Japanese, etc. In-Reply-To: Message-ID: <360047.75934.qm@web33503.mail.mud.yahoo.com> --- Ross Ridge wrote: > >Asia: > > > > Python should be *completely* internationalized > for > >Mandarin, Japanese, and possibly Hindi and Korean. > >Not just identifiers. I'm talking the entire > >language, keywords and all. > > > btw. Mandarin is a spoken dialect Chinese, what > you're actually asking > for is a Simplified-Chinese version of Python. > I'm just trying to divide-and-conquer the problem of promoting Python literacy in the world. To the extent that you have a billion people in the world who all speak/write a mostly common language, I wonder if you wouldn't try to go even further than PEP 3131 and truly translate Python to Chinese, whatever that means. I'm wondering if all the English keywords in Python would present too high a barrier for most Chinese people--def, if, while, for, sys, os, etc. So you might need to go even further than simply allowing identifiers to be written in Simplified-Chinese. ____________________________________________________________________________________ Food fight? Enjoy some healthy debate in the Yahoo! Answers Food & Drink Q&A. http://answers.yahoo.com/dir/?link=list&sid=396545367 From kyosohma at gmail.com Mon Jun 18 12:03:07 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Mon, 18 Jun 2007 09:03:07 -0700 Subject: Custom wxPython Widget In-Reply-To: <1181964248.743455.168290@n60g2000hse.googlegroups.com> References: <1181964248.743455.168290@n60g2000hse.googlegroups.com> Message-ID: <1182182587.135376.235440@k79g2000hse.googlegroups.com> On Jun 15, 10:24 pm, Jens Thiede wrote: > What is the best source code to read? Any tips; suggestions? > > Thanks in advance > Jens Thiede I would recommend reading the wxPython demo source code. Also, this website has some custom widgets written in "pure wxPython", some of which are in the demo: http://xoomer.alice.it/infinity77/eng/freeware.html Mike From walterbyrd at iname.com Fri Jun 22 20:45:02 2007 From: walterbyrd at iname.com (walterbyrd) Date: Fri, 22 Jun 2007 17:45:02 -0700 Subject: Collections of non-arbitrary objects ? In-Reply-To: <87k5twx4hf.fsf@benfinney.id.au> References: <1182449993.223262.229500@z28g2000prd.googlegroups.com> <87k5twx4hf.fsf@benfinney.id.au> Message-ID: <1182559502.069773.321620@i38g2000prf.googlegroups.com> On Jun 21, 5:38 pm, Ben Finney wrote: > That's a flippant response, but I don't understand the question. Everybody here seems to have about the same response: "why would you ever want to do that?" Maybe it's something that doesn't "need" to be done, but it seems to me that would give you a certain level of built-in integrity - you could be sure about what's in the structure. I would not expect that all of python would be that rigid, but I thought it might be worthwhile if there were one such structure. Think of this: why use tuples when lists are available? You can use a tuple to index a dictionary, but not a list - why? I the answer may be that sometimes you want some degree on inherent enforced structure. I'm sure the language could have designed to allow lists to index dictionary, but you would have to awfully careful with those lists. The burden would be on the programmer to make certain that those lists didn't change. But, it could be done, therefore tuples are not "needed" right? Languages like C are often criticized as being too rigid - you have to pre-define your variables, and pre-allocate your array sizes. But, languages like Perl and BASIC, are often criticized as being to sloppy - too few restrictions tend to lead to sloppy code. So I guess there is a sort of trade-off. I suppose I could use a database, that might give me some degree of assured integrity - depending on what database I used. From msj at infoserv.dk Tue Jun 26 08:06:34 2007 From: msj at infoserv.dk (Martin Skou) Date: Tue, 26 Jun 2007 14:06:34 +0200 Subject: text-mode tree viewer? In-Reply-To: <873b0fj9n5.fsf@wilson.homeunix.com> References: <873b0fj9n5.fsf@wilson.homeunix.com> Message-ID: <46810112$0$6273$edfadb0f@dread14.news.tele.dk> Not quite, but almost: data=[["Peter", ["Ian", [["Randy", ["Clara"]]]]], "Paul", ["Mary", ["Arthur"]]] def show(data,level): for i in data: if i.__class__.__name__=='list': show(i,level+1) else: print '%s->%s' % ('-'*level,i) show(data,0) /Martin From JoeSalmeri at hotmail.com Mon Jun 4 07:18:17 2007 From: JoeSalmeri at hotmail.com (Joe Salmeri) Date: Mon, 4 Jun 2007 07:18:17 -0400 Subject: Python 2.5.1 broken os.stat module References: <466140A6.1090100@v.loewis.de> <-aOdnbFdroD_gP_bnZ2dnUVZ_uKknZ2d@comcast.com> <4662750b$0$29898$9b622d9e@news.freenet.de> <4662F98C.8070709@v.loewis.de> Message-ID: <5smdnUc4LsuMaP7bnZ2dnUVZ_qarnZ2d@comcast.com> ""Martin v. L?wis"" wrote in message news:4662F98C.8070709 at v.loewis.de... >> It appears that you may have missed part of my tests. Sorry it was such >> a >> long reply but I was trying to provide a lot of detail so that others had >> a >> clear understanding of what was going on. > > Please understand that it is *extremely* tedious to follow your > messages. It would have been much better if they had been short and > to the point. > >> Changing the timezone will defintely change the "textual representation" >> of >> all timestamps just as you say (even though the actual UTC value has >> *not* >> changed), however, when DST starts/ends the "textual representation" of >> the >> timestamps on some files WILL ALSO CHANGE when the automatically adjust >> for >> DST setting is turned on. > > Right, and that's because switching to DST means that YOU MOVE TO A > DIFFERENT TIME ZONE. > > EST != EDT. > >> While it is true that I did change the timezone in the first part of the >> test (to establish the baseline), in the second part of the tests where >> the >> difference you are referring to occured, the timezone was *not* changed, >> the >> only thng that occured was that DST started. > > And that meant that the time zone *did* change. > >> When the date progressed to a point after DST had started Windows now >> reports the timestamp on that *unmodified* file now is 01/01/2007 08:00 >> PM. >> >> I did not change the timezone, the only thing that occurred was DST >> started. > > So you did change the timezone. > >> Over the years this issue has caused all sorts of problems for backup >> programs and CVS (greatly detailed in the article I provided the link >> for). > > That is very hard to believe. CVS and backup programs use the UTC time > stamp, and completely ignore the timezone. So when you agree that the > UTC time stamp did not change, CVS and the backup programs will work > just fine. > > There was a long-standing problem with changing time-stamps ON FAT. > On a FAT file system, the actual UTC time stamps change when the > timezone changes (including the change to and from DST). *That* > was a big problem for backup programs and CVS, and is now fixed > with NTFS. > >> You mixed up my tests, in that case as shown above the timezone did *not* >> change, the only thing that changed was that DST started and the file was >> created during a time when DST was not in effect. > > Right, so the timezone did change. > > Regards, > Martin From aleax at mac.com Sat Jun 30 19:41:00 2007 From: aleax at mac.com (Alex Martelli) Date: Sat, 30 Jun 2007 16:41:00 -0700 Subject: PEP 3107 and stronger typing (note: probably a newbie question) References: <1182369568.941307.316260@p77g2000hsh.googlegroups.com> <5dveb4F360un0U1@mid.individual.net> <467a9209$0$22165$426a74cc@news.free.fr> <1182858785.886469.93060@n60g2000hse.googlegroups.com> <46824d8d$0$2324$426a74cc@news.free.fr> <4682eddc$0$23164$426a74cc@news.free.fr> <5ehokpF38ov3jU2@mid.individual.net> <4683d5cd$0$8993$426a74cc@news.free.fr> <7xps3e3g9x.fsf@ruckus.brouhaha.com> <468565a0$0$3686$426a74cc@news.free.fr> <7xhcopj10g.fsf@ruckus.brouhaha.com> <46863ea7$0$970$426a34cc@news.free.fr> <1i0ikru.1uccqtm1efnzn3N%aleax@mac.com> <46868890$0$14484$426a34cc@news.free.fr> Message-ID: <1i0j4q0.w01fxqlt8nwsN%aleax@mac.com> Bruno Desthuilliers wrote: ... > >>Hmmm... For a dinausor, C seems well alive. Can you remind me which > > > > So do chickens. > > > I'm afraid I didn't get the joke... Are you saying that C is a rather, > well, primitive language ? The joke's just based on the fact that (based on DNA analysis) birds are said to be dinosaurs, and are definitely "well alive":-). Alex From gur.tom at gmail.com Tue Jun 19 08:00:05 2007 From: gur.tom at gmail.com (Tom Gur) Date: Tue, 19 Jun 2007 12:00:05 -0000 Subject: static python classes ? Message-ID: <1182254405.901790.189190@p77g2000hsh.googlegroups.com> Hi, I'm new to python, and I can't seem to find in the docs how to create the python equivalent of what's called in most OOP languages "static classes", can you give me a hint ? From bruno.42.desthuilliers at wtf.websiteburo.oops.com Fri Jun 15 07:29:12 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Fri, 15 Jun 2007 13:29:12 +0200 Subject: dynamically generated runtime methods & reflection In-Reply-To: References: Message-ID: <467277fc$0$21230$426a74cc@news.free.fr> Josiah Carlson a ?crit : (snip) > Well, the particular operation is typically called 'currying a > function', it's not 'currying' but 'partial application'. Currying is somehow the reverse of partial : it's a way of building a multiple-args function from single-args functions. From cousinstanley at hotmail.com Sat Jun 9 06:42:48 2007 From: cousinstanley at hotmail.com (Cousin Stanley) Date: Sat, 09 Jun 2007 05:42:48 -0500 Subject: Python's "only one way to do it" philosophy isn't good? References: <1181368143.874341.273140@r19g2000prf.googlegroups.com> Message-ID: <1181385768_30305@sp12lax.superfeed.net> > .... > In scheme, I believe you just have recursion. > .... Cousin TJR .... I'm a total scheme rookie starting only about 3 days ago and one of the mechanisms I went looking for was a technique for iteration .... Found in the scheme docs about iteration supplied via the reduce package .... "Iterate and reduce are extensions of named-let for writing loops that walk down one or more sequences such as the elements of a list or vector, the characters read from a port, or arithmetic series .... " The following scheme session illustrates a trivial example .... > , open reduce > > ( define ( list_loop this_list ) ( iterate loop ( ( list* this_item this_list ) ) ; iterate expression ( ( new_list '( ) ) ) ; state expression ( loop ( cons ( * 2 this_item ) new_list ) ) ; body expression ( reverse new_list ) ) ) ; final expression ; no values returned > > ( define L '( 1 2 3 4 5 ) ) ; no values returned > ( define result_i ( list_loop L ) ) ; no values returned > > result_i '(2 4 6 8 10) > However, just as in Python the map function might be both easier to code and more readable in many cases .... > ( define ( x2 n ) ( * 2 n ) ) ; no values returned > > ( define result_m ( map x2 L ) ) ; no values returned > > result_m '(2 4 6 8 10) Note .... No lambdas in my scheme code either .... ;-) -- Stanley C. Kitching Human Being Phoenix, Arizona ----== Posted via Newsfeeds.Com - Unlimited-Unrestricted-Secure Usenet News==---- http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ Newsgroups ----= East and West-Coast Server Farms - Total Privacy via Encryption =---- From Shihpin.Lin at gmail.com Sun Jun 3 23:10:32 2007 From: Shihpin.Lin at gmail.com (Shihpin) Date: Sun, 03 Jun 2007 20:10:32 -0700 Subject: example: 40286 -> 68204 In-Reply-To: References: <1180916590.000664.249810@z28g2000prd.googlegroups.com> Message-ID: <1180926632.927183.260000@g37g2000prf.googlegroups.com> Brian, Thanks! I will try it when I come home, > > Shihpin Lin > > This does it: > > >>>> def reversed_int(i): > > ... return int(''.join(reversed(str(i)))) > > ... > >>>> reversed_int(12345) > > 54321 > > Best, > > Brian vdB From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Sat Jun 23 06:31:53 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Sat, 23 Jun 2007 12:31:53 +0200 Subject: Error in following code References: <1182491886.184746.104640@x35g2000prf.googlegroups.com> Message-ID: <5e4b4pF36il55U1@mid.individual.net> Jay Loden wrote: > That should do the trick. Additionally, it does the trick to save the first entered number as default argument forever. Regards, Bj?rn -- BOFH excuse #117: the printer thinks its a router. From desertlinux at netscape.net Wed Jun 20 21:36:15 2007 From: desertlinux at netscape.net (Brian) Date: Wed, 20 Jun 2007 18:36:15 -0700 Subject: Text-To-Speech for the Mac (OS X) In-Reply-To: <1182386550.427279.249090@a26g2000pre.googlegroups.com> References: <1182386550.427279.249090@a26g2000pre.googlegroups.com> Message-ID: Hi Graham, Ahh, that works! Thank you... :-) Brian --- Graham Dumpleton wrote: > On Jun 21, 9:41 am, Brian wrote: >> Hello, >> >> Does anyone know how to get Python to be able to perform text-to-speech >> abilities for the Mac (OS X)? I have been searching Google, but have >> not found any helpful solutions or resources yet. > > os.system('say read the man page for "say"') > > :-) > > Graham > From amolj.1306 at gmail.com Fri Jun 15 07:41:36 2007 From: amolj.1306 at gmail.com (Amol) Date: Fri, 15 Jun 2007 11:41:36 -0000 Subject: Want to learn Python Message-ID: <1181907696.878873.214760@i13g2000prf.googlegroups.com> Hi, I want to learn Python in less than a month which resources should I use. I prefer to read books . Please give me a list of *recognized* resources. Thank You all From eduardo.padoan at gmail.com Mon Jun 25 11:11:00 2007 From: eduardo.padoan at gmail.com (Eduardo "EdCrypt" O. Padoan) Date: Mon, 25 Jun 2007 12:11:00 -0300 Subject: Collections of non-arbitrary objects ? In-Reply-To: <1182780863.067601.89320@d30g2000prg.googlegroups.com> References: <1182449993.223262.229500@z28g2000prd.googlegroups.com> <87k5twx4hf.fsf@benfinney.id.au> <1182559502.069773.321620@i38g2000prf.googlegroups.com> <87wsxvrzsj.fsf@benfinney.id.au> <1182620734.940718.196520@e16g2000pri.googlegroups.com> <467ed491$0$27132$426a34cc@news.free.fr> <1182780863.067601.89320@d30g2000prg.googlegroups.com> Message-ID: > I don't think there is anything wrong with the data structures that > exist in python. I was just wondering if there was a structure that > would restrict a collection to only allow certain types. The > "restrictedlist" class discussed in another thread may be the sort of > thing I was looking for. Just remenber that if you write a library using such a thing, your (consenting adults) users will not be able to store objects in your list that implement (part of) the interface of the type that you restricted. -- EduardoOPadoan (eopadoan->altavix::com) Bookmarks: http://del.icio.us/edcrypt From geoff.bache at pobox.com Mon Jun 11 07:56:43 2007 From: geoff.bache at pobox.com (geoffbache) Date: Mon, 11 Jun 2007 04:56:43 -0700 Subject: Threads, signals and sockets (on UNIX) In-Reply-To: <466D2FF6.2070209@web.de> References: <466D2FF6.2070209@web.de> Message-ID: <1181563003.508142.23870@g4g2000hsf.googlegroups.com> > Twisted *should* be able to do this, as it uses non-blocking IO. > > http://twistedmatrix.com/trac/ Thanks for the tip. I'll take a look if nobody has any better suggestions. It still seems to me that what I'm trying to do is essentially quite simple, and shouldn't require as large a tool as Twisted to fix it. Isn't Twisted basically for web applications? Geoff From siona at chiark.greenend.org.uk Tue Jun 26 12:11:50 2007 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 26 Jun 2007 17:11:50 +0100 (BST) Subject: Python changing keywords name References: <1182630774.701295.50890@k79g2000hse.googlegroups.com> <1182651282.747106.239720@o61g2000hsh.googlegroups.com> Message-ID: Gabriel Genellina wrote: >(I hope nobody will abuse this technique... Y perd=F3n a los >hispanoparlantes por lo horrible de la traducci=F3n). Ah, I only spotted this when I came to post a response. And the reason I was going to post a response was that these: > 'assert': 'afirmar', > 'exec': 'ejecutar', > 'import': 'importar', > 'pass': 'pasar', > 'print': 'imprimir', > 'raise': 'lanzar', > 'return': 'retornar', > 'try': 'intentar', > 'yield': 'producir', look rather odd to this non-native Spanish speaker (or at least reader), and I was going to ask if they sounded more idiomatically correct if it's not your nth language. I guess they don't 8-) -- \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 edreamleo at charter.net Tue Jun 12 10:22:39 2007 From: edreamleo at charter.net (Edward K Ream) Date: Tue, 12 Jun 2007 09:22:39 -0500 Subject: Leo 4.4.3 beta 2 released Message-ID: Leo 4.4.3 beta 2 is available at: http://sourceforge.net/project/showfiles.php?group_id=3458&package_id=29106 Leo is a text editor, data organizer, project manager and much more. See: http://webpages.charter.net/edreamleo/intro.html The highlights of Leo 4.4.3: ---------------------------- - Added support for chapters in Leo's core. - Added support for zipped .leo files. - Added a leoBridge module that allows full access to all of Leo's capabilities from programs running outside of Leo. - Removed all gui-dependent code from Leo's core. - Better support for the winpdb debugger. - Added support for @enabled-plugins nodes in settings files. - Added support for @open-with nodes in settings files. - Added support for @bool write_strips_blank_lines setting. - The__wx_gui plugin is now functional. - Leo can use aspell on Linux when using Python 2.5 or later. - Many minor improvements, new settings, commands and bug fixes. Links: ------ Leo: http://webpages.charter.net/edreamleo/front.html Home: http://sourceforge.net/projects/leo/ Download: http://sourceforge.net/project/showfiles.php?group_id=3458 CVS: http://leo.tigris.org/source/browse/leo/ Quotes: http://webpages.charter.net/edreamleo/testimonials.html Edward -------------------------------------------------------------------- Edward K. Ream email: edreamleo at charter.net Leo: http://webpages.charter.net/edreamleo/front.html -------------------------------------------------------------------- From joerg.birkhold at gmail.com Wed Jun 13 08:37:24 2007 From: joerg.birkhold at gmail.com (madprocessor) Date: Wed, 13 Jun 2007 12:37:24 -0000 Subject: shape recognition Message-ID: <1181738244.510271.269550@q19g2000prn.googlegroups.com> hi there, does anybody know about shape / gesture recognition librarys for python? like cali: http://immi.inesc-id.pt/cali/ thx joerg From Mail.To.Nathaniel at gmail.com Tue Jun 5 05:28:12 2007 From: Mail.To.Nathaniel at gmail.com (Mail.To.Nathaniel at gmail.com) Date: Tue, 05 Jun 2007 09:28:12 -0000 Subject: Beginner question: module organisation In-Reply-To: <1179595428.485794.160300@q75g2000hsh.googlegroups.com> References: <1179148188.698342.317080@w5g2000hsg.googlegroups.com> <1179593109.409934.193690@l77g2000hsb.googlegroups.com> <1179595428.485794.160300@q75g2000hsh.googlegroups.com> Message-ID: <1181035692.844359.216210@w5g2000hsg.googlegroups.com> Thank you for all your help! I'll study the proposals to chose the one I prefer or to create something new :) Anyway, this is a perfect start-up for me. Nathaniel. From showell30 at yahoo.com Mon Jun 11 18:05:20 2007 From: showell30 at yahoo.com (Steve Howell) Date: Mon, 11 Jun 2007 15:05:20 -0700 (PDT) Subject: Properties for modules? In-Reply-To: <3C177ED9-E6D8-48B6-A394-6A6D935F2A3F@leafe.com> Message-ID: <571489.4093.qm@web33515.mail.mud.yahoo.com> --- Ed Leafe wrote: > I have a simple module that reads in values from > disk when imported, > and stores them in attributes, allowing for code > like: > > >>> import moduleFoo > >>> print moduleFoo.someSetting > 'the value' > > What I'd like to do is have a more property-like > behavior, so that > if they try to set the value of > moduleFoo.someSetting, it also > persists it to disk. But properties are really only > useful in > instances of classes; if I define 'someSetting' as a > property at the > module level, I get: > > >>> import moduleFoo > >>> print moduleFoo.someSetting > > > Does anyone know any good tricks for getting > property-like behavior > here? > Sorry to stray from your question a bit, but you are reminding me of something that happens a lot in my coding. I'll code something as a module, then turn it into a class. I usually do it early enough in the ballgame that it's not a major undertaking, but it can still be kind of tedious. In a lot of ways modules and classes are interchangable in how you use them, and I'm curious what strategies other people adopt in making the progression from modules to classes. For example, is there some sort of magical way to turn a module into a class, i.e. to make it less of a singleton? I promise to horribly abuse such techniques till I learn better... Right now, when I make the conversion, I just kind of mechanically indent a bunch of functions, put a "class" statement on top of them, add some self-dots, etc., but it feels kind of wrong at times. ____________________________________________________________________________________ Got a little couch potato? Check out fun summer activities for kids. http://search.yahoo.com/search?fr=oni_on_mail&p=summer+activities+for+kids&cs=bz From aisaac at american.edu Thu Jun 28 09:52:13 2007 From: aisaac at american.edu (Alan Isaac) Date: Thu, 28 Jun 2007 13:52:13 GMT Subject: equality & comparison by default (was Re: Too many 'self' in python.That's a big flaw in this language.) In-Reply-To: References: <1182942154.185461.89620@e9g2000prf.googlegroups.com> <1i0cy8z.z94q5d1dxgexxN%aleax@mac.com> Message-ID: A.T.Hofkamp wrote: >>>>a = Car2(123) >>>>b = Car2(123) >>>>a == b > > True > >>>>set([a,b]) > > set([Car2(123), Car2(123)]) > > I get a set with two equal cars, something that never happens with a set > my math teacher once told me. Then your math teacher misspoke. You have two different cars in the set, just as expected. Use `is`. http://docs.python.org/ref/comparisons.html This is good behavior. Cheers, Alan Isaac From faulkner891 at gmail.com Wed Jun 27 08:11:34 2007 From: faulkner891 at gmail.com (faulkner) Date: Wed, 27 Jun 2007 05:11:34 -0700 Subject: Too many 'self' in python.That's a big flaw in this language. In-Reply-To: <1182942154.185461.89620@e9g2000prf.googlegroups.com> References: <1182942154.185461.89620@e9g2000prf.googlegroups.com> Message-ID: <1182946294.941781.115350@n2g2000hse.googlegroups.com> On Jun 27, 7:02 am, "hide1... at gmail.com" wrote: > HI > I'm currently using Python. I find that a instance variable must > confined with self, > for example: > class a: > def __init__(self): > self.aa=10 > def bb(self): > print self.aa # See .if in c++,I could use aa to change that > variable > > That's a big inconvenience in coding ,especially when you have lot of > variable > If you method need 10 variables ,you have to type "self" for 10 times > and that also makes your variable longer. > > >From My point,I think this only help python interpreter to deside > > where to look for. > Is there anyone know's how to make the interpreter find instance name > space first? > Or any way to make programmer's life easier? http://www.voidspace.org.uk/python/weblog/arch_d7_2006_12_16.shtml#e584 From python at rcn.com Fri Jun 29 04:44:28 2007 From: python at rcn.com (Raymond Hettinger) Date: Fri, 29 Jun 2007 01:44:28 -0700 Subject: Getting some element from sets.Set In-Reply-To: References: <1178258913.095438.173020@h2g2000hsg.googlegroups.com> <1178267029.258868.219800@h2g2000hsg.googlegroups.com> <1178316417.371855.63170@p77g2000hsh.googlegroups.com> <1178725344.400736.210280@n59g2000hsh.googlegroups.com> Message-ID: <1183106668.977384.47890@i38g2000prf.googlegroups.com> > $ python -m timeit -s "s = set('abcdef')" "x = iter(s).next()" > 1000000 loops, best of 3: 0.399 usec per loop > > $ python -m timeit -s "s = set('abcdef')" "x = s.pop(); s.add(x)" > 1000000 loops, best of 3: 0.339 usec per loop > > So it looks like it's more efficient to use s.pop() + s.add(). There's a faster, cleaner way: >python -m timeit -s "s = set('abcdef')" "x = iter(s).next()" 1000000 loops, best of 3: 0.539 usec per loop >python -m timeit -s "s = set('abcdef')" "x = s.pop(); s.add(x)" 1000000 loops, best of 3: 0.465 usec per loop >python -m timeit -s "s = set('abcdef')" "for x in s: break" 1000000 loops, best of 3: 0.175 usec per loop FWIW, the latter approach is general purpose and works with any iterable (useful for reading the first line of file objects for example). Raymond From alexteo21 at yahoo.com Fri Jun 8 07:18:43 2007 From: alexteo21 at yahoo.com (alexteo21) Date: Fri, 08 Jun 2007 04:18:43 -0700 Subject: Does python 2.3.3 pty module has a bug? Message-ID: <1181301523.131072.237550@g37g2000prf.googlegroups.com> Hi, System: Solaris Python version: 2.3.3 For a automation job, I used pexpect module together with python for creating a ftp session automatically and downloading the file. I notice that after closing the child. The file descriptor is not closed (check /proc//fd) After running the script for a while, I start seeing too many files open error. I have a development machine running Linux using python 2.3.3. I execute the same code on it. The file descriptor is closed everytime after the pexpect child is closed. My question is - Is this a bug with pty module for solaris for python 2.3.3? Appreciate your comments Thanks, Alex From nospam at no.spam Wed Jun 13 06:06:09 2007 From: nospam at no.spam (=?ISO-8859-1?Q?Markus_Sch=F6pflin?=) Date: Wed, 13 Jun 2007 12:06:09 +0200 Subject: cStringIO change in 2.4 vs 2.5. Regression? In-Reply-To: References: Message-ID: Terry Reedy wrote: > "Markus Sch?pflin" wrote in message > news:f3p07k$u62$1 at nntp.ilk.net... > | Hello, > | > | I just stumbled accross a difference between cStringIO in Python 2.4 > | and 2.5. You can no longer feed arrays to cStringIO. > [snip] > | Has this change been done on purpose or is it a regression? > > I doubt that an intentional change would have been made for cStringIO and > not StringIO. Two ways to investigate: scan the detailed listing of 2.5 > changes for mention of array and cStringIO modules; check the source code > checkin messages for both for the relevant time period. This might also > suggest who to send an inquiry to who might not be reading here. First of all, thank you very much for you answer and sorry for the late reply, I was AFK for some days. I scanned the NEWS file and the only change which caught my attention is - Patches #1298449 and #1298499: Add some missing checks for error returns in cStringIO.c. but the corresponding check-in doesn't look suspicious. Next I had a look at the source code of the trunk: cStringIO.c:newIobject() calls abstract.c:PyObject_AsCharBuffer(), which, AFAICT, is the only possible source for the exception reported. The exception is raised when the given object doesn't have conversions to an I/O buffer, but when looking at arraymodule.c there is array_as_buffer which provides the needed conversions. The code looks pretty much the same on the 2.5 branch, so I don't have an explanation for the observed behaviour. > If you do not get a satifactory resolution here, file a bug report on SF. > But remember that all bug fixers are volunteers just like you, so any > investigation you do and report on to make response easier will likely make > it quicker also. I think I'll file a bug at SF... maybe someone else will spot something. Thanks, Markus From agillesp at gmail.com Mon Jun 11 14:52:53 2007 From: agillesp at gmail.com (alg) Date: Mon, 11 Jun 2007 18:52:53 -0000 Subject: REALLY need help with iterating a list. In-Reply-To: <1181586648.614514.228900@m36g2000hse.googlegroups.com> References: <1181586648.614514.228900@m36g2000hse.googlegroups.com> Message-ID: <1181587973.157830.177810@i38g2000prf.googlegroups.com> Reverse iteration should do the trick, if I understand your problem: for server in reversed(serverlist): ... else: serverlist.remove(server) On Jun 11, 11:30 am, Radamand wrote: > This has been driving me buggy for 2 days, i need to be able to > iterate a list of items until none are left, without regard to which > items are removed. I'll put the relevant portions of code below, > please forgive my attrocious naming conventions. > Basically i'm trying to spin up some subprocesses that will ping a > group of servers and then wait until all of them have completed (good > or bad), store the ping result and the return code, and move on. > The problem comes in the second block, when i try to iterate the > list of servers and remove the ones that are finished, for some reason > Python appears to re-index the list when I remove an item and the next > step through the loop it cant find the item its expecting because the > indexes have changed. > Any assistance would be appreciated... > > ============================================================================= > for server in serverlist: > ping[server] = subprocess.Popen("ping -c 1 " + str(server) + " 5", > shell=True, stdout=subprocess.PIPE) > > while len(serverlist) > 0: > for server in serverlist: > if ping[server].returncode==None: > ping[server].poll() > else: > pingresult[server] = ping[server].stdout.read() > pingreturncode[server] = ping[server].returncode > serverlist.remove(server) From kirby.urner at gmail.com Mon Jun 11 18:55:45 2007 From: kirby.urner at gmail.com (kirby.urner at gmail.com) Date: Mon, 11 Jun 2007 22:55:45 -0000 Subject: Who uses Python? In-Reply-To: <1180985830.288414.208850@q69g2000hsb.googlegroups.com> References: <1180985830.288414.208850@q69g2000hsb.googlegroups.com> Message-ID: <1181602545.269986.227840@d30g2000prg.googlegroups.com> On Jun 4, 12:37 pm, walterbyrd wrote: > I mean other than sysadmins, programmers, and web-site developers? > I use Python to teach mathematics and analytical thinking to both children and adults. The OO way of casting a problem has a lot of power. I'm working in the CP4E tradition (Computer Programming for Everybody), an initiative launched by Guido in the early days of Python. And yes, I actually get paid for this work (some of it -- I volunteer my time too). http://www.4dsolutions.net/ocn/cp4e.html I'm also a database programmer, use other languages besides Python, use Python for other tasks besides teaching. Kirby PS: my background is philosophy, my major at Princeton (famous philo guy Richard Rorty was my thesis advisor and one of my best teachers -- his obit is in today's New York Times). From ladynikon at gmail.com Tue Jun 19 12:24:51 2007 From: ladynikon at gmail.com (Danyelle Gragsone) Date: Tue, 19 Jun 2007 12:24:51 -0400 Subject: pydev help In-Reply-To: References: <59f9c5160706190856k5793ec2bn7d66ab518fedf1ca@mail.gmail.com> Message-ID: <59f9c5160706190924j3a0a5977ldcdd80da123d2226@mail.gmail.com> ty! Danyelle From goon12 at gmail.com Tue Jun 26 08:12:26 2007 From: goon12 at gmail.com (Joe Riopel) Date: Tue, 26 Jun 2007 08:12:26 -0400 Subject: Python Info. In-Reply-To: <163f0ce20706252342k734e0341qe59aa62eeb3b42a0@mail.gmail.com> References: <1182836595.006152.87320@j4g2000prf.googlegroups.com> <4680ACEC.7060500@web.de> <163f0ce20706252342k734e0341qe59aa62eeb3b42a0@mail.gmail.com> Message-ID: <6a2ccd190706260512w4c0f59b3r4a2231a62824d260@mail.gmail.com> On 6/26/07, kaens wrote: > It was like being slapped with the mid-90s That was awesome. > On 6/26/07, Stefan Behnel wrote: > > Brandon wrote: > > > Check it out: www.BrandonsMansion.com That is horrible. From larry.bates at websafe.com Thu Jun 21 11:53:07 2007 From: larry.bates at websafe.com (Larry Bates) Date: Thu, 21 Jun 2007 10:53:07 -0500 Subject: Adding Python to the path in Windows In-Reply-To: <1182439377.009844.320760@q75g2000hsh.googlegroups.com> References: <1182437575.810986.205610@n2g2000hse.googlegroups.com> <1182439377.009844.320760@q75g2000hsh.googlegroups.com> Message-ID: <7MadnZBB5eFFA-fbnZ2dnUVZ_qTinZ2d@comcast.com> kyosohma at gmail.com wrote: > On Jun 21, 10:10 am, Duncan Booth > wrote: >> k... at thenortheastgroup.com wrote: >>> I have many users using two different versions of python, 2.4 and >>> 2.5. I am running Python scripts on their computers programmatically, >>> but I can't run it with the full path because they have different >>> versions installed. I need to run it like 'python {script name}'. So >>> I need to add Python to the path. How do I do this permanently >>> without going to each computer and setting it through the GUI? I >>> tried creating a Windows batch script using setx, but the user had to >>> be an administrator. >>> Or is there any other way I can run whatever version of Python happens >>> to be installed with a single command? Anyone have any ideas? Such a >>> simple issue, there must be a simple solution. (of course, this is >>> Windows). >> Assuming they have Python installed normally there will be file >> associations set up for .py and .pyw, so all you need to do to type in >> the script name: Python itself does not need to be in the path. >> N.B. You do need to include the .py extension unless you can arrange to >> edit the PATHEXT environment variable. >> >> e.g. >> >> C:\Temp>type t.py >> import sys >> print sys.version >> >> C:\Temp>t.py >> 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit (Intel)] >> >> C:\Temp>assoc .py >> .py=Python.File >> >> C:\Temp>ftype Python.File >> Python.File="C:\Python25\python.exe" "%1" %* > > If your users aren't programmers, then why not just run Python over > the network? That's what we do at my place of employment. The only > machines that have Python actually installed are development machines. > > Mike > Another solution is to use py2exe to convert your python program into an .exe file that you can distribute. Then they require no Python installation at all. I use py2exe and Inno Installer to do just that and it works great. -Larry From jkrukoff at ltgc.com Tue Jun 12 01:08:22 2007 From: jkrukoff at ltgc.com (John Krukoff) Date: Mon, 11 Jun 2007 23:08:22 -0600 Subject: Accessing global namespace from module In-Reply-To: <200706112119.16124.techlist@pathfinder.phys.utk.edu> Message-ID: <000201c7acaf$b3352f90$0301a8c0@naomi> > -----Original Message----- > From: python-list-bounces+jkrukoff=ltgc.com at python.org [mailto:python- > list-bounces+jkrukoff=ltgc.com at python.org] On Behalf Of Reuben D. > Budiardja > Sent: Monday, June 11, 2007 7:19 PM > To: python-list at python.org > Subject: Re: Accessing global namespace from module > > On Monday 11 June 2007 17:10:03 Gabriel Genellina wrote: > > En Mon, 11 Jun 2007 17:29:35 -0300, reubendb > escribi?: > > > On Jun 11, 3:30 pm, "Gabriel Genellina" > > > > > > wrote: > > >> En Mon, 11 Jun 2007 15:18:58 -0300, reubendb > > >> > > >> escribi?: > > >> > The problem is I don't define the functions AddPlot() and > DrawPlots(). > > >> > It's built into the python interpreter of the CLI version of the > > >> > program I mentioned, and they are defined on the main script. I > load > > >> > the main script using something like "software -cli -s > > >> > mainscript.py". > > >> > In the mainscript.py I import myModule, but of course myModule does > > >> > not have access to the functions defined in the global namespace of > > >> > mainscript.py. > > >> > > >> Don't you have some import statements at the top of mainscript.py > that > > >> are > > >> responsible for bringing AddPlot and DrawPlots into the current > > >> namespace? > > >> Import the same things in your second module. > > > > > > No, I *don't* have any import statement mainscript.py. When using this > > > software's CLI, AddPlot and DrawPlots are available to me > > > automagically from mainscript.py. Hence my question: How do I make > > > this available from other module. Is there any way at all ? > > > > Yes: create your own module on-the-fly, using the recipe posted earlier > by > > John Krukoff. > > If there are many functions, try enumerating them all: > > > > import sys > > from types import ModuleType as module > > > > plotModule = module('plot') > > for key,value in globals().items(): > > if key[:2] != '__': > > setattr(plotModule, key, value) > > > > sys.modules['plot'] = plotModule > > Great ! That seems to work, thanks a lot. > One last question. Do I have to do this for ever script I write, or can I > put > this into separate file and "include" it somehow ? > I am going to have several mainscripts.py, and all is going to import > myModule > that will need access to this plots subroutine. It'll be great if I can > put > this trick on a single file that is included by the main scripts, to avoid > violating DRY principle. > > Thanks for all the help. > RDB > -- > Reuben D. Budiardja > -- > http://mail.python.org/mailman/listinfo/python-list Well, an alternative way to access the main script namespace is using: >>> import __main__ >>> __main__.AddPlot( blah, blah ) And so on, from within your imported file that you want to have muck about in the main namespace. I've no idea if your custom application will setup __main__ properly, but the documentation indicates that it should work the same way for an embedded application. You can probably substitute dir( __main__ ) for globals( ) in the above script and have it set things up automatically. --------- John Krukoff jkrukoff at ltgc.com From tokyo246 at gmail.com Thu Jun 21 04:36:42 2007 From: tokyo246 at gmail.com (Kenji Noguchi) Date: Thu, 21 Jun 2007 01:36:42 -0700 Subject: string formatter %x and a class instance with __int__ cannot handle long Message-ID: <2ba587f0706210136p54363e04y974577aefdfef00b@mail.gmail.com> 2007/6/20, half.italian at gmail.com : > In your second example y is an instance of class X...not an int. y.v > is an int. Are you hoping it will cast it to an int as needed using > your method? If so, I think you need to do so explicitly...ie "%08x" > % int(y) > > ~Sean I confirmed that "%08x" % int(y) works. And yes, I'm hoping so. It actually works that way if the v is less than or equal to 0x7ffffffff. Please try the test script. It's essentially the same test with some more print statements. All but test d-3 appears to be ok. 2007/6/20, Gabriel Genellina : > It is a bug, at least for me, and I have half of a patch addressing it. As > a workaround, convert explicitely to long before formatting. I'm interested in your patch. What's the other half still missing? Thanks, Kenji Noguchi --->8---->8--->8--- #!/usr/bin/env python class X: def __init__(self, v): self.v = v def __int__(self): print "Hey! I'm waken up!" return self.v def test(arg): print 1,type(int(arg)) print 2,"%08x" % int(arg) print 3,"%08x" % arg a = 0x7fffffff b = X(0x7fffffff) c = 0x80000000 d = X(0x80000000) print "----test a----" ; test(a) print "----test b----" ; test(b) print "----test c----" ; test(c) print "----test d----" ; test(d) --->8---->8--->8--- And here is the result ----test a---- 1 2 7fffffff 3 7fffffff ----test b---- 1 Hey! I'm waken up! 2 Hey! I'm waken up! 7fffffff 3 Hey! I'm waken up! 7fffffff ----test c---- 1 2 80000000 3 80000000 ----test d---- 1 Hey! I'm waken up! 2 Hey! I'm waken up! 80000000 3 Hey! I'm waken up! Traceback (most recent call last): File "", line 23, in ? File "", line 13, in test TypeError: int argument required From stuffduff at cox.net Wed Jun 20 14:39:42 2007 From: stuffduff at cox.net (stuffduff) Date: Wed, 20 Jun 2007 18:39:42 -0000 Subject: SIGSEGV gcmodule.c:241 closing python after module import In-Reply-To: <1182349342.952030.35230@q69g2000hsb.googlegroups.com> References: <1182349342.952030.35230@q69g2000hsb.googlegroups.com> Message-ID: <1182364782.996983.171760@o61g2000hsh.googlegroups.com> On Jun 20, 9:22 am, stuffduff wrote: > Hi, > > I have a python extension that works fine while it is running, but > when I exit python I get this error: > > GNU gdb Red Hat Linux (6.5-15.fc6rh) > Copyright (C) 2006 Free Software Foundation, Inc. > GDB is free software, covered by the GNU General Public License, and > you are > welcome to change it and/or distribute copies of it under certain > conditions. > Type "show copying" to see the conditions. > There is absolutely no warranty for GDB. Type "show warranty" for > details. > This GDB was configured as "i386-redhat-linux-gnu"...Using host > libthread_db library "/lib/libthread_db.so.1". > > (gdb) run > Starting program: python2.4 > > ... > > > > Program received signal SIGSEGV, Segmentation fault. > [Switching to Thread -1208243504 (LWP 12884)] > collect (generation=2) at Modules/gcmodule.c:241 > 241 Modules/gcmodule.c: No such file or directory. > in Modules/gcmodule.c > (gdb) bt > #0 collect (generation=2) at Modules/gcmodule.c:241 > #1 0x080e1ec5 in PyGC_Collect () at Modules/gcmodule.c:1196 > #2 0x080da88a in Py_Finalize () at Python/pythonrun.c:353 > #3 0x08055176 in Py_Main (argc=0, argv=0xbfb8dae4) at Modules/main.c: > 513 > #4 0x08054962 in main (argc=-1208273400, argv=0x812ed68) > at Modules/python.c:23 > > I haven't figured out what it is trying to collect. Is there a way to > tell? > > Thanks, > > Sean Debug build of python2.4.4 gives: python: Modules/gcmodule.c:240: update_refs: Assertion `gc->gc.gc_refs == (-3)' failed. This error also appears here: http://www.redhat.com/archives/fedora-devel-list/2006-March/msg00009.html From __peter__ at web.de Mon Jun 11 05:52:02 2007 From: __peter__ at web.de (Peter Otten) Date: Mon, 11 Jun 2007 11:52:02 +0200 Subject: Regular Text References: <1181552035.275951.68010@g4g2000hsf.googlegroups.com> <1181554370.583984.70530@q66g2000hsg.googlegroups.com> Message-ID: jaeltong at yahoo.co.uk wrote: > Wow, that is fast. Thanks. > >> In your code, you should use string literals like >> >> my_path = r"C:\Programs\Python\new" >> my_path = "C:\\Programs\\Python\\new" >> >> But you said "a program to retrieve the filepath" - and I understand that >> you dont have a string literal, and you compute it somehow. Escape >> characters should not be a problem then. Have you verified the contents >> of the text file? With notepad? > > I meant, I used a GUI-Tkinter Script to retrieve the input(the > directory). my program is supposed to > 1. get the directory from the GUI Script, > with my_path= FieldValue.insert(n, variable.get()) > 2. open a text file > 3. and edit a filepath in the file, > 4 then saving as another new file... > > if that is the case, how should I do, in order to get the input in the > correct format?? The user can input literals like "...\t..." via the GUI, and Python will interpret the sequence "\t" as a backslash followed by the letter t. If you want to allow the user to use forward slashes, too, apply os.path.normpath(): ... os.path.normpath(variable.get()) ... Peter From david.golden at oceanfree.net Fri Jun 22 22:17:19 2007 From: david.golden at oceanfree.net (David Golden) Date: Sat, 23 Jun 2007 03:17:19 +0100 Subject: The Modernization of Emacs References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182344981.372713.298580@w5g2000hsg.googlegroups.com> <1182370884.853838.321440@c77g2000hse.googlegroups.com> <2jpok4-ajt.ln1@zoogz.gregorie.org> <1182551884.239660.209700@x35g2000prf.googlegroups.com> Message-ID: Twisted wrote: > If I sit down at a windows text editor (or > even kwrite or similar) I can just focus on the job. Faced with emacs > or most other text-mode editors (but not MS-DOS Edit, interestingly) > the editor keeps intruding on my focus. Oops. > "emacs or most other text-mode editors" sounds very much like you believe emacs works in a pure text mode too? It can, of course, and that's a good thing, but that's certainly not how I usually use it - it has a GUI, you know. From cginboston at hotmail.com Mon Jun 18 07:20:52 2007 From: cginboston at hotmail.com (Chaz Ginger) Date: Mon, 18 Jun 2007 07:20:52 -0400 Subject: XMLRPC and SSL Message-ID: <46766A94.9000701@hotmail.com> I have a web service that I built and it requires using SSL. I have found a few examples of clients using SSL but none that allow me to change the client's certificate or the chain of certificates the client will use to authenticate the server. I was wondering if anyone knows of a good example of this? TIA, Chaz. From horpner at yahoo.com Thu Jun 21 08:44:01 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Thu, 21 Jun 2007 12:44:01 GMT Subject: Split file into several and reformat References: Message-ID: On 2007-06-21, bomber71 at aapt.net.au wrote: > Hi, > > I want to take read an input file (sels.txt) that looks like: > > Begin sels > sel1 = {1001, 1002, 1003, ... > ... > 1099} > > sel2 = {1001, 1008, 1009 ... > ... > 1299} > End sels > > And turn it into an output file for each of the "sels" in the input file, i.e > sel1.txt: > > L1001 > L1002 > L1003 > ... > L1099 > > and sel2.txt: > > L1001 > L1008 > L1009 > ... > L1299 > > And so on. Many thanks, I think I'd put together a simple grammar and then write a recursive descent parser that spit out my output files. But that's just because I find that kind of thing fun. ;) -- Neil Cerutti I'm tired of hearing about money, money, money, money, money. I just want to play the game, drink Pepsi, wear Reebok. --Shaquille O'Neal From nagle at animats.com Mon Jun 25 12:42:31 2007 From: nagle at animats.com (John Nagle) Date: Mon, 25 Jun 2007 09:42:31 -0700 Subject: urllib interpretation of URL with ".." In-Reply-To: References: <467cc85f$0$3039$9b622d9e@news.freenet.de> Message-ID: Duncan Booth wrote: > "Martin v. L?wis" wrote: > > >>>Is "urllib" wrong? > Section 5.2 is also relevant here. In particular: > > >> g) If the resulting buffer string still begins with one or more >> complete path segments of "..", then the reference is >> considered to be in error. Implementations may handle this >> error by retaining these components in the resolved path (i.e., >> treating them as part of the final URI), by removing them from >> the resolved path (i.e., discarding relative levels above the >> root), or by avoiding traversal of the reference. > > > The common practice seems to be for client-side implementations to handle > this using option 2 (removing them) and servers to use option 3 (avoiding > traversal of the reference). urllib uses option 1 which is also correct but > not as useful as it might be. That's helpful. Thanks. In Python, of course, "urlparse.urlparse", which is the main function used to disassemble a URL, has no idea whether it's being used by a client or a server, so it, reasonably enough, takes option 1. (Yet another hassle in processing real-world HTML.) John Nagle From NoSpam at Hccnet.nl Sat Jun 30 16:24:35 2007 From: NoSpam at Hccnet.nl (Hans) Date: Sat, 30 Jun 2007 22:24:35 +0200 Subject: win32event.WaitForInputIdle() returns too soon References: <4684330c$0$742$3a628fcd@textreader.nntp.hccnet.nl> Message-ID: <4686bc03$0$735$3a628fcd@textreader.nntp.hccnet.nl> "Gabriel Genellina" schreef in bericht news:mailman.184.1183090500.22759.python-list at python.org... > En Thu, 28 Jun 2007 19:15:40 -0300, Hans escribi?: > >> I'm sending keyboard and mouse events to a seperate windows application. >> I use win32event.WaitForInputIdle() before calling e.g. >> win32api.keybd_event() >> However it seems that WaitForInputIdle() returns too soon because some >> of my >> events get lost. Now I'v created my own WaitForInputIdle() which calls > > From the Microsoft docs for WaitForInputIdle: "The WaitForInputIdle > function only works with GUI applications. If a console application calls > the function, it returns immediately, with no wait." > A typical Python script is a console application. > > -- > Gabriel Genellina Well, this is weird. I searched for doc on the internet and that description differs: The process you're waiting for needs bo have a message queue (it does in my case), not the process that calls WaitForInputIdle. Hans Waits until the specified process is waiting for user input with no input pending, or until the time-out interval has elapsed. DWORD WINAPI WaitForInputIdle( HANDLE hProcess, DWORD dwMilliseconds ); Parameters hProcess [in] A handle to the process. If this process is a console application or does not have a message queue, WaitForInputIdle returns immediately. dwMilliseconds [in] The time-out interval, in milliseconds. If dwMilliseconds is INFINITE, the function does not return until the process is idle. From kyosohma at gmail.com Tue Jun 5 11:42:57 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Tue, 05 Jun 2007 15:42:57 -0000 Subject: Beginning Python In-Reply-To: <1181053786.724436.132900@n15g2000prd.googlegroups.com> References: <1181053786.724436.132900@n15g2000prd.googlegroups.com> Message-ID: <1181058177.835839.31810@o5g2000hsb.googlegroups.com> On Jun 5, 9:29 am, abhiee wrote: > Hello , I have just begun learning python...and I'm loving it...Just > wanted to ask you that how much time would it take me to learn python > completely and which languages should i learn alongwith python to be a > good professional programmer?...Now i only know C.... > thanx in advance! I think a more accurate question would be "how long does it take to learn python so I don't have to look stuff up constantly". Knowing any language completely is nigh impossible unless you designed it yourself. However, I must say that learning Python so that you can just start programming well without always going for help is quite easy. I would think it would take 1-3 months depending on your ability to suck in information and the amount of time you actually program. As I understand it, the top languages are still Java and C++, with COBOL being a major player in insurance/business environments. I would recommend pretty much any web language as more and more is heading towards the online world. Thus, Java/Javascript, PHP, Perl, CSS, CGI, etc are good to know. Check out this interesting graph on computer language trends: http://www.cs.berkeley.edu/~flab/languages.html Mike From sschwarzer at sschwarzer.net Sun Jun 10 16:56:10 2007 From: sschwarzer at sschwarzer.net (Stefan Schwarzer) Date: Sun, 10 Jun 2007 22:56:10 +0200 Subject: Needed: FTP Upload Directory Tree script In-Reply-To: References: Message-ID: <466C656A.8040207@sschwarzer.net> Hello Ian, On 2007-06-10 10:01, IanC wrote: > Does anyone know of a function or script to upload an entire > subdirectory tree from a local file space to an FTP server? > > The Python distribution comes with "ftpmirror.py", which performs > a mirror download of a directory tree, but I need the "Upload" > version of this. I'm just working on an ftputil[1] extension[2] to copy/mirror directory trees between local filesystems and remote FTP hosts. It's in pre-alpha state (just in development), but maybe it already does what you want. Did I note that this is an only slightly tested module and might destroy your files? - That is, use it at your own risk. I recommend you look at the source code of ftp_sync.py before using it. It works like this: - Download[3] and install ftputil. - Download the file[2] and put it into the site-packages/ftputil directory. - Use the library like: import ftputil from ftputil import ftp_sync source = ftp_sync.LocalHost() target = ftputil.FTPHost(hostname, username, password) syncer = ftp_sync.Syncer(source, target) syncer.sync(source_directory, target_directory) Note that the _contents_ of source_directory (_not_ the directory itself) will be copied to the already-existing target_directory. If you have further questions or feedback, please send e-mail to the ftputil mailing list[4] or to me[5]. [1] http://ftputil.sschwarzer.net [2] http://ftputil.sschwarzer.net/trac/browser/trunk/ftp_sync.py?format=txt [3] http://ftputil.sschwarzer.net/trac/wiki/Download [4] mailto:ftputil at codespeak.net [5] mailto:sschwarzer at sschwarzer.net Stefan From msj at infoserv.dk Wed Jun 6 03:08:32 2007 From: msj at infoserv.dk (msj at infoserv.dk) Date: Wed, 06 Jun 2007 00:08:32 -0700 Subject: Encoding problem with web application (Paste+Mako) Message-ID: <1181113712.128103.228180@q69g2000hsb.googlegroups.com> Hi I have a problem with encoding non-ascii characters in a web application. The application uses Paste and Mako. The code is here: http://www.webudkast.dk/demo.txt The main points are: After getting some user generated input using paste.request.parse_formvars, how should this be correctly saved to file? How should this afterward be read from the file, and fed correctly into a Mako template? Thanks. Martin From steven.bethard at gmail.com Tue Jun 12 16:26:53 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 12 Jun 2007 14:26:53 -0600 Subject: Pattern Classification Frameworks? In-Reply-To: References: Message-ID: Evan Klitzke wrote: > What frameworks are there available for doing pattern classification? > I'm generally interested in the problem of mapping some sort of input > to one or more categories. For example, I want to be able to solve > problems like taking text and applying one or more tags to it like > "romance", "horror", "poetry", etc. This isn't really my research > specialty, but my understanding is that Bayesian classifiers are > generally used for problems like this. In fact, a wide variety of classifiers are used in text classification, including Bayesian approaches, support vector machines, conditional random fields, etc. > Are there any other frameworks I should be aware of? I have used (but not recently) Orange: http://www.ailab.si/orange I haven't used, but have been meaning to try, PyML: http://pyml.sourceforge.net/ A more recent addition (whose documentation needs work) is: http://montepython.sourceforge.net/ And here's a Summer of Code project to build an ML library: http://projects.scipy.org/scipy/scipy/wiki/MachineLearning These are all general-purpose machine learning frameworks. So they can be applied to pretty much any classification problem (including the text classification problems you're looking at). You just need to pick out a set of relevant features to describe your data, and feed those features along with your chosen labels to a machine learning algorithm. STeVe From mail at timgolden.me.uk Sat Jun 2 12:43:00 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Sat, 02 Jun 2007 17:43:00 +0100 Subject: Trouble killing a process on windows In-Reply-To: <1180801625.231797.158370@p77g2000hsh.googlegroups.com> References: <1180801625.231797.158370@p77g2000hsh.googlegroups.com> Message-ID: <46619E14.1040802@timgolden.me.uk> Thomas Nelson wrote: > from subprocess import Popen > from time import sleep > import win32api > war3game = Popen(["C:\Program Files\Warcraft III\Frozen Throne.exe"]) > sleep(30) > print "slept for 30" > print win32api.TerminateProcess(int(war3game._handle),-1) > #print > ctypes.windll.kernel32.TerminateProcess(int(war3game._handle),-1) > print "terminated process" > > Here's the output: > slept for 30 > Traceback (most recent call last): > File "C:\Python24\warcraft\runwar3.py", line 7, in ? > print win32api.TerminateProcess(int(war3game._handle),-1) > error: (5, 'TerminateProcess', 'Access is denied.') > > I'm logged in as adminstrator. Does anyone know how to fix this > problem? There's nothing obvious. I assume you got your info from here? http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/347462 Just for completeness, have you tried the pid-based technique shown there? I've no idea why it should work if this one doesn't but... (I have a slight suspicion that the fact that it opens the process with a "for-termination" flag might help). Failing that, you can see if WMI can do it (although I assume that, under the covers, WMI just calls TerminateProcess): http://timgolden.me.uk/python/wmi_cookbook.html#create_destroy_notepad I suppose you might have to adjust your token privs to include, say the Debug priv. This is designed to let you take control of any process (and terminate it, or whatever). If it looks like you need to do that, post back and I -- or someone else -- can try to run up an example. TJG From dummy666 at mail.ru Fri Jun 22 17:28:44 2007 From: dummy666 at mail.ru (askel) Date: Fri, 22 Jun 2007 21:28:44 -0000 Subject: Adding method to a class on the fly In-Reply-To: <1182547065.295969.258820@g37g2000prf.googlegroups.com> References: <1182538969.522044.209560@q19g2000prn.googlegroups.com> <1182543862.369337.36880@z28g2000prd.googlegroups.com> <1182547065.295969.258820@g37g2000prf.googlegroups.com> Message-ID: <1182547724.690874.279230@g37g2000prf.googlegroups.com> On Jun 22, 5:17 pm, 7stud wrote: > On Jun 22, 2:24 pm, askel wrote: > > > class Dummy: > > def method(self, arg): > > print arg > > > def method2(self, arg): > > self.method(arg) > > > Dummy.method2 = method2 > > Dummy.method2('Hello, world!') > > Traceback (most recent call last): > File "test1.py", line 8, in ? > Dummy.method2('Hello, world!') > TypeError: unbound method method2() must be called with Dummy instance > as first argument (got str instance > instead) > > > > >I like that to be the same as: > > >class Dummy: > > def __init__(self): > > return > > > def method_dynamic(self): > > return self.method_static("it's me") > > > def method_static(self, text): > > print text > > return > > >so that I can do: > > >dum=Dummy.method_dynamic() > > >and see "it's me" printed. > > When are you able to see that? there is no way to call instance method from static one. but in your case you can make something like: class Dummy: @staticmethod def method(arg): print arg def method2(arg): Dummy.method(arg) Dummy.method2 = staticmethod(method2) Dummy.method2('Hello, world!') - OR - def method2(cls, arg): cls.method(arg) Dummy.method2 = classmethod(method2) Dummy.method2('Hello, world!') From mcl.office at googlemail.com Sat Jun 2 04:32:06 2007 From: mcl.office at googlemail.com (mosscliffe) Date: Sat, 02 Jun 2007 01:32:06 -0700 Subject: Cookie: Not understanding again In-Reply-To: <1180743184.755904.155510@m36g2000hse.googlegroups.com> References: <1180709394.151350.103200@q69g2000hsb.googlegroups.com> <1180743184.755904.155510@m36g2000hse.googlegroups.com> Message-ID: <1180773126.214516.218140@q69g2000hsb.googlegroups.com> On 2 Jun, 01:13, David Wahler wrote: > On Jun 1, 3:49 pm, mosscliffe wrote:> I have the following code, which I thought would create a cookie, if > > one did not exist and on the html form being sent to the server, it > > would be availabe for interrogation, when the script is run a second > > time. > > > It seems to me there is something basic missing in that I should need > > to tell the server I am sending a cookie, but all the docs I have read > > imply it is done automatically, if one creates a 'Cookie.SimpleCookie' > > > I know my understanding is poor of web server logic, but if anyone can > > help, I will be most grateful. > > > This may be more to do with Web Server behaviour than python > > programming, but surely there is a way of doing this in python. > > > David, Thanks for your help. I spent all last night trying to get it to work, but I can not work out how to force my cookie into the response header. The most annoying part is on one occasion it did and the cookie sat there until I killed the session. By the time I discovered 'pageinfo' add-in for firefox, the cookie had gone. I have read a lot about cookies, but the grey matter is very slow at absorbing nowadays. I was wondering if I should add the 'path=/' to my cookie, as I am using a host that has numbers for the IP address and my domain name when used, is via a frame. Although the python bit to display the contents (when it did work), did not show any value for 'path'. Could I create the response header in python and get it executed as part of my form submission ? Obviously, still struggling. Richard > The cookie values have to be sent to the browser as part of the > response headers. (Modifying the Cookie object doesn't do this for you > -- the Cookie instance just acts as a container.) In other words, > something like this: > > c = Cookie.SimpleCookie() > c.load(os.environ['HTTP_COOKIE']) > # ...modify cookie object... > print "Content-Type: text/html" > print c > print > # send the HTML text > > -- David From arkanes at gmail.com Thu Jun 28 09:02:34 2007 From: arkanes at gmail.com (Chris Mellon) Date: Thu, 28 Jun 2007 08:02:34 -0500 Subject: Python's "only one way to do it" philosophy isn't good? In-Reply-To: References: <7xejjzmk7u.fsf@ruckus.brouhaha.com> <7xy7i7xjl5.fsf@ruckus.brouhaha.com> Message-ID: <4866bea60706280602q77670427g980bc1a6d488fdf1@mail.gmail.com> On 6/27/07, Douglas Alan wrote: > "Chris Mellon" writes: > > > On 6/27/07, Douglas Alan wrote: > > >> The C++ folks feel so strongly about this, that they refuse to provide > >> "finally", and insist instead that you use destructors and RAII to do > >> resource deallocation. Personally, I think that's taking things a bit > >> too far, but I'd rather it be that way than lose the usefulness of > >> destructors and have to use "when" or "finally" to explicitly > >> deallocate resources. > > > This totally misrepresents the case. The with statement and the > > context manager is a superset of the RAII functionality. > > No, it isn't. C++ allows you to define smart pointers (one of many > RAII techniques), which can use refcounting or other tracking > techniques. Refcounting smart pointers are part of Boost and have > made it into TR1, which means they're on track to be included in the > next standard library. One need not have waited for Boost, as they can > be implemented in about a page of code. > > The standard library also has auto_ptr, which is a different sort of > smart pointer, which allows for somewhat fancier RAII than > scope-based. > Obviously. But theres nothing about the with statement that's different than using smart pointers in this regard. I take it back, there's one case - when you need only one scope in a function, with requires an extra block while C++ style RAII allows you to > > It doesn't overload object lifetimes, rather it makes the intent > > (code execution upon entrance and exit of a block) explicit. > > But I don't typically wish for this sort of intent to be made > explicit. TMI! I used "with" for *many* years in Lisp, since this is > how non-memory resource deallocation has been dealt with in Lisp since > the dawn of time. I can tell you from many years of experience that > relying on Python's refcounter is superior. > I question the relevance of your experience, then. Refcounting is fine for memory, but as you mention below, memory is only one kind of resource and refcounting is not necessarily the best technique for all resources. Java has the same problem, where you've got GC so you don't have to worry about memory, but no tools for managing non-memory resources. > Shouldn't you be happy that there's something I like more about Python > than Lisp? > I honestly don't care if anyone prefers Python over Lisp or vice versa. If you like Lisp, you know where it is. > > Nobody in their right mind has ever tried to get rid of explicit > > resource management - explicit resource management is exactly what you > > do every time you create an object, or you use RAII, or you open a > > file. > > This just isn't true. For many years I have not had to explicitly > close files in Python. Nor have I had to do so in C++. They have > been closed for me implicitly. "With" is not implicit -- or at least > not nearly as implicit as was previous practice in Python, or as is > current practice in C++. > You still don't have to manually close files. But you cannot, and never could, rely on them being closed at a given time unless you did so. If you need a file to be closed in a deterministic manner, then you must close it explicitly. The with statement is not implicit and never has been. Implicit resource management is *insufficient* for the general resource management case. It works fine for memory, it's okay for files (until it isn't), it's terrible for thread locks and network connections and database transactions. Those things require *explicit* resource management. > > *Manual* memory management, where the tracking of references and > > scopes is placed upon the programmer, is what people are trying to > > get rid of and the with statement contributes to that goal, it > > doesn't detract from it. > > As far as I am concerned, memory is just one resource amongst many, > and the programmer's life should be made easier in dealing with all > such resources. > Which is exactly what the with statement is for. > > Before the with statement, you could do the same thing but you > > needed nested try/finally blocks > > No, you didn't -- you could just encapsulate the resource acquisition > into an object and allow the destructor to deallocate the resource. > If you did this in Python, your code was wrong. You were coding C++ in Python. Don't do it. > > RAII is a good technique, but don't get caught up on the > > implementation details. > > I'm not -- I'm caught up in the loss of power and elegance that will > be caused by deprecating the use of destructors for resource > deallocation. > Python has *never had this*. This never worked. It could seem to work if you carefully, manually, inspected your code and managed your object lifetimes. This is much more work than the with statement. To the extent that your code ever worked when you relied on this detail, it will continue to work. There are no plans to replace pythons refcounting with fancier GC schemes that I am aware of. > > The with statement does exactly the same thing, but is actually > > superior because > > > > a) It doesn't tie the resource managment to object creation. This > > means you can use, for example, with lock: instead of the C++ style > > Locker(lock) > > I know all about "with". As I mentioned above, Lisp has had it since > the dawn of time. And I have nothing against it, since it is at times > quite useful. I'm just dismayed at the idea of deprecating reliance > on destructors in favor of "with" for the majority of cases when the > destructor usage works well and is more elegant. > Nothing about Pythons memory management has changed. I know I'm repeating myself here, but you just don't seem to grasp this concept. Python has *never* had deterministic destruction of objects. It was never guaranteed, and code that seemed like it benefited from it was fragile. > > b) You can tell whether you exited with an exception, and what that > > exception is, so you can take different actions based on error > > conditions vs expected exit. This is a significant benefit, it > > allows the application of context managers to cases where RAII is > > weak. For example, controlling transactions. > > Yes, for the case where you might want to do fancy handling of > exceptions raised during resource deallocation, then "when" is > superior, which is why it is good to have in addition to the > traditional Python mechanism, not as a replacement for it. > "with". And it's not replacing anything. > >> Right, but that doesn't mean that 99.9% of the time, the programmer > >> can't immediately tell that cycles aren't going to be an issue. > > > They can occur in the most bizarre and unexpected places. To the point > > where I suspect that the reality is simply that you never noticed your > > cycles, not that they didn't exist. > > Purify tells me that I know more about the behavior of my code than > you do: I've *never* had any memory leaks in large C++ programs that > used refcounted smart pointers that were caused by cycles in my data > structures that I didn't know about. > I'm talking about Python refcounts. For example, a subtle resource leak that has caught me before is that tracebacks hold references to locals in the unwound stack. If you relied on refcounting to clean up a resource, and you needed exception handling, the resource wasn't released until *after* the exception unwound, which could be a problem. Also holding onto tracebacks for latter processing (not uncommon in event based programs) would artificially extend the lifetime of the resource. If the resource you were managing was a thread lock this could be a real problem. > > And if you think you won't need it because python will get "real" GC > > you're very confused about what GC does and how. > > Ummm, I know all about real GC, and I'm quite aware than Python has > had it for quite some time now. (Though the implementation is rather > different last I checked than it would be for a language that didn't > also have refcounted GC.) > > > A generic threadsafe smart pointer, in fact, is very nearly a GIL. > > And how's that? I should think that modern architectures would have > an efficient way of adding and subtracting from an int atomically. If > they don't, I have a hard time seeing how *any* multi-threaded > applications are going to be able to make good use of multiple > processors. > > > Get cracking then. You're hardly the first person to say this. > > However, of the people who say it, hardly anyone actually produces > > any code and the only person I know of who did dropped it when > > performance went through the floor. Maybe you can do better. > > I really have no desire to code in C, thank you. I'd rather be coding > in Python. (Hence my [idle] desire for macros in Python, so that I > could do even more of my work in Python.) > In this particular conversation, I really don't think that theres much to say beyond put up or shut up. The experts in the field have said that it's not practical. If you think they're wrong, you're going to need to prove it with code, not by waving your hand. > > There's no particular reason why Lisp is any better for AI research > > than anything. > > Yes, there is. It's a very flexible language that can adapt to the > needs of projects that need to push the boundaries of what computer > programmers typically do. > That doesn't make Lisp any better at AI programming than it is for writing databases or spreadsheets or anything else. > > I'm not familiar with the TIOBE metric, but I can pretty much > > guarantee that regardless of what it says there is far more COBOL > > code in the wild, being actively maintained (or at least babysat) > > than there is lisp code. > > I'm agree that there is cedrtainly much more Cobol code being > maintained than there is Lisp code, but that doesn't mean that there > are more Cobol programmers writing new code than there are Lisp > programmers writing new code. A project would have to be run by a > madman to begin a new project in Cobol. > More than you'd think, sadly. Although depending on your definition of "new project", it may not count. There's a great deal of new code being written in COBOL to run on top of old COBOL systems. > >> Re Lisp, though, there used to be a joke (which turned out to be > >> false), which went, "I don't know what the most popular programming > >> language will be in 20 years, but it will be called 'Fortran'". In > >> reality, I don't know what the most popular language will be called 20 > >> years from now, but it will *be* Lisp. > > > And everyone who still uses the language actually called Lisp will > > continue to explain how it isn't a "real" lisp for a laundry list of > > reasons that nobody who gets work done actually cares about. > > And where are you getting this from? I don't know anyone who claims > that any commonly used dialect of Lisp isn't *really* Lisp. > The language of the future will not be Common Lisp, and it won't be a well known dialect of Lisp. It will have many Lisp like features, and "true" Lispers will still claim it doesn't count, just as they do about Ruby and Python today. From half.italian at gmail.com Thu Jun 21 11:45:11 2007 From: half.italian at gmail.com (half.italian at gmail.com) Date: Thu, 21 Jun 2007 15:45:11 -0000 Subject: How to create a file with read access rights In-Reply-To: <1182439636.529600.126210@c77g2000hse.googlegroups.com> References: <1182439636.529600.126210@c77g2000hse.googlegroups.com> Message-ID: <1182440711.147467.89930@x35g2000prf.googlegroups.com> On Jun 21, 8:27 am, Johny wrote: > Is it possible to create a file on Linux with access rights? > For example > owner can read and write into the file > others can only read from the file > Thanks for replies > L. That all depends on your umask. Most commonly, the default value is 022 which translates to 755 or ower has full control, and all others can read and execute. If you'd like to change a specific files permissios with python, look into os.chmod() ~Sean From josiah.carlson at sbcglobal.net Mon Jun 18 00:18:03 2007 From: josiah.carlson at sbcglobal.net (Josiah Carlson) Date: Sun, 17 Jun 2007 21:18:03 -0700 Subject: Trivial string substitution/parser In-Reply-To: References: Message-ID: Samuel wrote: > On Sun, 17 Jun 2007 11:00:58 +0000, Duncan Booth wrote: > >> The elegant and lazy way would be to change your specification so that $ >> characters are escaped by $$ not by backslashes. Then you can write: >> >>>>> from string import Template >>>>> ... > > Thanks, however, turns out my specification of the problem was > incomplete: In addition, the variable names are not known at compilation > time. You mean at edit-time. >>> t.substitute(variable1="hello", variable2="world") Can be replaced by... >>> t.substitute(**vars) ...as per the standard **kwargs passing semantics. - Josiah From cousinstanley at hotmail.com Sat Jun 2 00:00:58 2007 From: cousinstanley at hotmail.com (Cousin Stanley) Date: Fri, 01 Jun 2007 23:00:58 -0500 Subject: subexpressions References: Message-ID: <1180756858_54747@sp12lax.superfeed.net> > .... > After years of discussion, Guido has decided > to leave lambda alone for 3.0. > > It will not be neither expanded, nor removed, nor renamed. But it still will be as ugh, ugh, ugh-lee as a mule walking backwards ..... ;-) -- Stanley C. Kitching Human Being Phoenix, Arizona ----== Posted via Newsfeeds.Com - Unlimited-Unrestricted-Secure Usenet News==---- http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ Newsgroups ----= East and West-Coast Server Farms - Total Privacy via Encryption =---- From jjl at pobox.com Thu Jun 21 19:27:09 2007 From: jjl at pobox.com (John J. Lee) Date: Thu, 21 Jun 2007 23:27:09 GMT Subject: eggs considered harmful References: Message-ID: <87fy4knb1u.fsf@pobox.com> Harry George writes: [...] > These are unacceptable behaviors. I am therefore dropping ZODB3, and > am considering dropping TurboGears and ZSI. If the egg paradigm > spreads, yet more packages will be dropped (or will never get a chance > to compete for addition). > > I've asked before, and I'll ask again: If you are doing a Python > project, please make a self-sufficient tarball available as well. You > can have dependencies, as long as they are documented and can be > obtained by separate manual download. 1. Given the presumptuous tone of your own message, I guess I'm not in danger of coming across as more rude than you when I point out that your requirements are just that: your own. The rest of the world won't *always* bend over backwards to support just exactly what you'd most prefer. 2. You can run your own private egg repository. IIRC, it's as simple as a directory of eggs and a plain old web server with directory listings turned on. You then run easy_install -f URL package_name instead of easy_install package_name . The distutils-sig archives will have more on this. 3. Alternatively, you could create bundled packages that include dependencies (perhaps zc.buildout can do that for you, even? not sure) John From v.davis2 at cox.net Fri Jun 8 20:17:51 2007 From: v.davis2 at cox.net (v.davis2) Date: Fri, 8 Jun 2007 17:17:51 -0700 Subject: DAO and Access97 WHERE clause fails Message-ID: Hi all, I am attempting to use Access97 as the database to hold the results of a python script. I seem to be able to make simple SELECT clauses work (like SELECT * FROM TableName), but have not been able to figure out how to add a WHERE clause to that (e.g., SELECT * FROM TableName WHERE myFieldName = 34) This fails complaining that the wrong number of parameters are present. I haved tried DAO36 and I have tried the ADO version with the same results. Therefore I have to conclude it is my screwup! Help in the forum or via email would sure be appreciated! (v.davis2 at cox.net) Here is the skeleton code: import win32com.client daoEngine = win32com.client.Dispatch('DAO.DBEngine.35') sDBname = 'vpyAnalyzeDirectorySize.mdb' sDB = 'c:\\documents and settings\\vic\\my documents\\tools\\python25\\_myscripts\\'+sDBname daoDB = daoEngine.OpenDatabase(sDB) sSQL1 = 'SELECT * FROM T_Index2DirName' daoRS = daoDB.OpenRecordset(sSQL1) # this works FINE and I can play with the record set # hsDB = hash(sDB) sSQL3 = 'SELECT * FROM T_Index2DirName WHERE iIndex = hsDB' # names are all correct in mdb file daoRStest = daoDB.OpenRecordset(sSQL3) # this FAILS, even though the record is there daoRS.Close() Traceback (most recent call last): File "C:\Documents and Settings\Vic\My Documents\Tools\python25\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py", line 310, in RunScript exec codeObject in __main__.__dict__ File "C:\Documents and Settings\Vic\My Documents\Tools\python25\_MyScripts\TestForPosting01.py", line 14, in daoRStest = daoDB.OpenRecordset(sSQL3) # this FAILS, even though record is there File "C:\Documents and Settings\Vic\My Documents\Tools\python25\lib\site-packages\win32com\gen_py\00025E01-0000-0000-C000-000000000046x0x5x0.py", line 523, in OpenRecordset , Type, Options, LockEdit) com_error: (-2147352567, 'Exception occurred.', (0, 'DAO.Database', 'Too few parameters. Expected 1.', 'jeterr35.hlp', 5003061, -2146825227), None) From max at alcyone.com Tue Jun 5 23:37:50 2007 From: max at alcyone.com (Erik Max Francis) Date: Tue, 05 Jun 2007 20:37:50 -0700 Subject: c[:]() In-Reply-To: References: <00b301c7a690$25af37d0$240110ac@Muse> <015701c7a7a4$584fac00$240110ac@Muse> Message-ID: Steven D'Aprano wrote: > On Tue, 05 Jun 2007 18:26:50 -0400, Terry Reedy wrote: > >> "Warren Stringer" wrote in message >> news:015701c7a7a4$584fac00$240110ac at Muse... | I am porting code that >> only uses this form | a[:4]b() >> | >> | Which translates to: >> | >> | for i in range(4): >> | a[i].b() >> >> Or, more directly and perhaps more efficiently: >> >> for e in a[:4]: e.b() > > I'm thinking that is more efficient only because four is a small number. > If you wanted to iterate over the first 2**22 items in a list of 2**22+1 > items, making a copy of the sub-list first would probably be a bad idea :) Then again, in that case, so would making a list of the indices with `range`, which is what the original poster was suggesting. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM, Y!M erikmaxfrancis To endure what is unendurable is true endurance. -- (a Japanese proverb) From sjmachin at lexicon.net Fri Jun 22 17:55:37 2007 From: sjmachin at lexicon.net (John Machin) Date: Fri, 22 Jun 2007 14:55:37 -0700 Subject: newbie question: parsing street name from address In-Reply-To: <1182527026.794658.4110@w5g2000hsg.googlegroups.com> References: <1182433644.485185.197690@w5g2000hsg.googlegroups.com> <1182451414.139267.7910@w5g2000hsg.googlegroups.com> <1182463419.846372.314550@d30g2000prg.googlegroups.com> <1182527026.794658.4110@w5g2000hsg.googlegroups.com> Message-ID: <1182549337.236321.222890@q19g2000prn.googlegroups.com> On Jun 23, 1:43 am, Eric wrote: > On Jun 21, 6:03 pm, John Machin wrote: > > > > > On Jun 22, 4:43 am, Eric wrote: > > > > On Jun 21, 9:47 am, cjl wrote: > > > > > P: > > > > > I am working on a project that requires geocoding, and have written a > > > > very simple geocoder that uses the Google service. > > > > > I would like to be able to extract the name of the street from the > > > > addresses in my data, however they vary significantly. Here a some > > > > examples: > > > > > 25 Main St > > > > 2500 14th St > > > > 12 Bennet Pkwy > > > > Pearl St > > > > Bennet Rd and Main st > > > > 19th St > > > > > As you can see, sometimes I have the house number, and sometimes I do > > > > not. Sometimes the street name is a number. Sometimes I simply have > > > > the names of intersecting streets. > > > > > I would like to be able to parse the above into the following: > > > > > Main St > > > > 14th St > > > > Bennet Pkwy > > > > Pearl St > > > > Bennet Rd > > > > Main St > > > > 19th St > > > > > How might I approach this complex parsing problem? > > > > > -CJL > > > > You might be able to use consistencies in your data to make this > > > simpler. If the examples you have there are representative, it looks > > > like what you should do is look for a word like 'St' or 'Rd' and then > > > return that word and the previous word. > > > The OP's data already contains > > [corner|cnr [of]] Foo Rd and|& Bar St > > and real world data will contain things like > > 1234 John F Kennedy Memorial Drive > > 456 Broadway > > > As Paul wrote, "Parsing street addresses is a very complex parsing > > problem", even when you restrict yourself to one mostly-English- > > speaking country. Software written under such restrictions rapidly > > breaks down elsewhere (Rue de la Paix, Wilhelmstrasse, Avenida 9 de > > Julio, etc) and blows up altogether when street names aren't used in > > postal addresses (e.g. Japan). > > No doubt that address parsing is, in general, a very difficult > problem. However, it may not be necessary for him to solve the > general problem. If his dataset is more limited in formats then his > problem is much simpler. Ignore the last sentence of my post. Restrict the application to [sub]urban addresses in the USA. If the OP's dataset is real-world data, it will contain cases of street addresses that don't fit "look for a word like 'St' or 'Rd' and then return that word and the previous word." To expect an OP in a newsgroup to provide representative examples is charmingly naive :-) and in any case the OP had already provided a corner case [pun intended] that busted your rule. Cheers, John From __peter__ at web.de Thu Jun 14 13:32:14 2007 From: __peter__ at web.de (Peter Otten) Date: Thu, 14 Jun 2007 19:32:14 +0200 Subject: Method much slower than function? References: <1181781612.939800.238890@q19g2000prn.googlegroups.com> <1181799961.148499.32210@o11g2000prd.googlegroups.com> Message-ID: Chris Mellon wrote: > On 6/14/07, Peter Otten <__peter__ at web.de> wrote: >> Peter Otten wrote: >> >> > Leo Kislov wrote: >> > >> >> On Jun 13, 5:40 pm, ido... at gmail.com wrote: >> >>> Hi all, >> >>> >> >>> I am running Python 2.5 on Feisty Ubuntu. I came across some code >> >>> that is substantially slower when in a method than in a function. >> >>> >> >>> >>> cProfile.run("bar.readgenome(open('cb_foo'))") >> >>> >> >>> 20004 function calls in 10.214 CPU seconds >> >> >> >>> >>> cProfile.run("z=r.readgenome(open('cb_foo'))") >> >>> >> >>> 20004 function calls in 0.041 CPU seconds >> >>> >> >> >> >> I suspect open files are cached so the second reader >> >> picks up where the first one left: at the of the file. >> >> The second call doesn't do any text processing at all. >> >> >> >> -- Leo >> > >> > Indeed, the effect of attribute access is much smaller than what the OP >> > is seeing: >> >> I have to take that back >> > > Your tests (which I have snipped) show attribute access being about 3x > slower than local access, which is consistent with my own tests. The > OP is seeing a speed difference of 2 orders of magnitude. That's far > outside the range that attribute access should account for. Not if it conspires to defeat an optimization for string concatenation $ cat iadd.py class A(object): def add_attr(self): self.x = "" for i in xrange(10000): self.x += " yadda" def add_local(self): x = "" for i in xrange(10000): x += " yadda" add_local = A().add_local add_attr = A().add_attr $ python2.5 -m timeit -s'from iadd import add_local' 'add_local()' 100 loops, best of 3: 3.15 msec per loop $ python2.5 -m timeit -s'from iadd import add_attr' 'add_attr()' 10 loops, best of 3: 83.3 msec per loop As the length of self.x grows performance will continue to degrade. The original test is worthless as I tried to explain in the section you snipped. Peter From wildemar at freakmail.de Mon Jun 4 17:53:27 2007 From: wildemar at freakmail.de (Wildemar Wildenburger) Date: Mon, 04 Jun 2007 23:53:27 +0200 Subject: *Naming Conventions* In-Reply-To: <1180992512.3586.5.camel@localhost.localdomain> References: <1180909218.939713.112010@q69g2000hsb.googlegroups.com> <1180990280.960271.235550@h2g2000hsg.googlegroups.com> <4664820D.3060503@freakmail.de> <1180992512.3586.5.camel@localhost.localdomain> Message-ID: <466489D7.2000301@freakmail.de> Carsten Haese wrote: > On Mon, 2007-06-04 at 23:20 +0200, Wildemar Wildenburger wrote: > >> I guess it is commonplace to use i, j, k and n >> (maybe others) in constructs like >> >> for i in range(len(data)): >> do_stuff(data[i]) >> >> Or should the good python hacker do that differently? Hope not ;). >> > > That's a big, fat "Heck, Yes": > > for thing in data: > do_stuff(thing) > > Boy is my face red! Holy Moly ... that was so obvious! See, that's what you get for coding too much matlab! Screw that! /W From jstroud at mbi.ucla.edu Mon Jun 11 17:10:43 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Mon, 11 Jun 2007 14:10:43 -0700 Subject: Link Dictionary In-Reply-To: <1181593466.934730.299660@i38g2000prf.googlegroups.com> References: <1181593466.934730.299660@i38g2000prf.googlegroups.com> Message-ID: anush shetty wrote: > Hi, > I have two dictionaries > > dict1={'B8': set(['I8', 'H8', 'B2', 'B7', 'F8', 'C9', 'G8', 'B4', > 'B5', 'B6', 'C8', 'E8', 'D8', 'B3', 'A9', 'A8', 'C7', 'B9', 'A7', > 'B1']), 'B9': set(['I9', 'H9', 'A7', 'F9', 'B3', 'B6', 'G9', 'B4', > 'B5', 'C9', 'B7', 'E9', 'B1', 'B2', 'D9', 'A9', 'A8', 'C8', 'B8', > 'C7']), 'D1': set(['F1', 'F2', 'F3', 'G1', 'I1', 'D2', 'H1', 'A1', > 'D4', 'B1', 'D8', 'D9', 'D6', 'D7', 'C1', 'D5', 'E1', 'D3', 'E3', > 'E2'])} > > and > dict2= > {'I6': '0', 'H9': '9', 'I2': '0', 'E8': '0', 'H3': '0', 'H7': '0', > 'I7': '3', 'I4': '0', 'H5': '0', 'F9': '0', 'G7': '5', 'G6': '9', > 'G5': '0', 'E1': '7', 'G3': '2', 'G2': '0', 'G1': '0', 'I1': '0', > 'C8': '0', 'I3': '5', 'E5': '0', 'I5': '1', 'C9': '0', 'G9': '0', > 'G8': '0', 'A1': '0', 'A3': '3', 'A2': '0', 'A5': '2', 'A4': '0', > 'A7': '6', 'A6': '0', 'C3': '1', 'C2': '0', 'C1': '0', 'E6': '0', > 'C7': '4', 'C6': '6', 'C5': '0', 'C4': '8', 'I9': '0', 'D8': '0', > 'I8': '0', 'E4': '0', 'D9': '0', 'H8': '0', 'F6': '8', 'A9': '0', > 'G4': '6', 'A8': '0', 'E7': '0', 'E3': '0', 'F1': '0', 'F2': '0', > 'F3': '6', 'F4': '7', 'F5': '0', 'E2': '0', 'F7': '2', 'F8': '0', > 'D2': '0', 'H1': '8', 'H6': '3', 'H2': '0', 'H4': '2', 'D3': '8', > 'B4': '3', 'B5': '0', 'B6': '5', 'B7': '0', 'E9': '8', 'B1': '9', > 'B2': '0', 'B3': '0', 'D6': '2', 'D7': '9', 'D4': '1', 'D5': '0', > 'B8': '0', 'B9': '1', 'D1': '0'} > > Now I want to create a dict which would have both the keys and values > to be of the corresponding values of dict2. > > Something like this: > > Eg. The first key in dict1 i.e. B8 as 0 (0 is the value of B8 in > dict2) mapped as set(['0','0','0',...]). > > Can anyone help me out with this. > - > Anush > new_dict = {} for akey, aset in dict1.items(): new_dict[akey] = sum(int(dict2[k]) for k in aset) James From http Sat Jun 30 14:02:47 2007 From: http (Paul Rubin) Date: 30 Jun 2007 11:02:47 -0700 Subject: Python's "only one way to do it" philosophy isn't good? References: <1182750077.570603.160240@q69g2000hsb.googlegroups.com> <7xir9cbm0g.fsf@ruckus.brouhaha.com> <7xejjzmk7u.fsf@ruckus.brouhaha.com> <7xy7i7xjl5.fsf@ruckus.brouhaha.com> <1182872972.417776.78650@o11g2000prd.googlegroups.com> <1182873568.454491.302860@e9g2000prf.googlegroups.com> <7xps3iy73h.fsf@ruckus.brouhaha.com> <7x1wfudtw9.fsf@ruckus.brouhaha.com> Message-ID: <7x8xa1pbg8.fsf@ruckus.brouhaha.com> Douglas Alan writes: > P.S. Besides Haskell is basically a refinement of ML, which is a > dialect of Lisp. I'd say Haskell and ML are descended from Lisp, just like mammals are descended from fish. From fuzzyman at gmail.com Mon Jun 25 16:41:12 2007 From: fuzzyman at gmail.com (Fuzzyman) Date: Mon, 25 Jun 2007 20:41:12 -0000 Subject: eggs considered harmful In-Reply-To: References: Message-ID: <1182804072.789708.302980@c77g2000hse.googlegroups.com> On Jun 21, 1:10 pm, Harry George wrote: > ...at least around here. > > I run a corporate Open Source Software Toolkit, which makes hundreds > of libraries and apps available to thousands of technical employees. > The rules are that a) a very few authorized downloaders obtain > tarballs and put them in a depot and b) other users get tarballs from > the depot and build from source. > > Historically, python packages played well in this context. Install > was a simple download, untar, setup.py build/install. > > Eggs and with other setuptools-inspired install processes break this > paradigm. The tarballs are incomplete in the first place. The builds > sometimes wander off to the internet looking for more downloads. The > installs sometimes wander off to the internet looking for > compatibility conditions. (Or rather they try to do so and fail > because I don't let themn through the firewall.) I understand your situation and I have some misgivings myself. It reminds me of the time when I worked in a 'corporate environment' and I was trying to install a Perl application to get round the internet blocking. The application (localproxy - very good) was *intended* to be installed via CPAN for tracking requirements - which didn't work behind our proxy firewall. Although the project author (a very technical guy) knew the direct dependencies, some of these had dependencies. He *didn't know* the full dependency set for his project. Eventually, through trial and error (and a lot of help from the author) I was able to get it working. But it was painful. My guess is that a lot of the world's computers are behind firewalls or proxies that preclude automatic dependency resolution. *However*, there is a very good reason why setuptools and eggs are gaining in popularity (and will continue to do so). For the majority of users eggs are just *so damned convenient*. Being able to do ``easy_install some_project`` and have it just work is fantastic. There are probably ways round this. For most non-esoteric eggs it should be possible to create an ordinary installation tarball from an egg. If you do easy_install of a project into a bare Python installation (a VM instance for example) then you should be able to see which dependencies are fetched. If this is too much then I fear that you may be SOL... Fuzzyman http://www.voidspace.org.uk/ironpython/index.shtml From thomas.pohl at gmail.com Tue Jun 5 06:53:56 2007 From: thomas.pohl at gmail.com (thomas.pohl at gmail.com) Date: Tue, 05 Jun 2007 03:53:56 -0700 Subject: Feature request: New string conversion type to ignore list item Message-ID: <1181040836.014198.223080@h2g2000hsg.googlegroups.com> Hi, let's assume you want to nicely print the content of a list except for one (or some) individual item. You could do it like this: t = ["foo", "skip me", 1, 2, 3] print("text: %s\nvalues: %i %i %i" % (t[0], t[2], t[3], t[4])) If there was a conversion type which simply ignores the corresponding list item - let's call it "%v" like "void" - things would be much easier: t = ["foo", "skip me", 1, 2, 3] print("text: %s\nvalues: %v%i %i %i" % t) I guess that this new conversion type wouldn't break any existing code. What do you think? Cheers, Tom From gagsl-py2 at yahoo.com.ar Mon Jun 25 21:36:34 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 25 Jun 2007 22:36:34 -0300 Subject: Collections of non-arbitrary objects ? References: <1182449993.223262.229500@z28g2000prd.googlegroups.com> <87k5twx4hf.fsf@benfinney.id.au> <1182559502.069773.321620@i38g2000prf.googlegroups.com> <87wsxvrzsj.fsf@benfinney.id.au> <1182620734.940718.196520@e16g2000pri.googlegroups.com> <467ed491$0$27132$426a34cc@news.free.fr> <1182780863.067601.89320@d30g2000prg.googlegroups.com> Message-ID: En Mon, 25 Jun 2007 11:14:23 -0300, walterbyrd escribi?: > I have probably expressed this incorrectly. What I meant was: > >>>> a = [1,2,3] >>>> b = a >>>> a[1] = 'spam' > > Here, I have changed b, without an explicit assignment. After I > assigned a to b, I never did another "b =" yet b changed anyway > because I changed a. I am not saying there is anything wrong with > this, I'm just explaining what I meant. I think you should benefit reading this short article: http://effbot.org/zone/python-objects.htm -- Gabriel Genellina From newsgroups at debain.org Sat Jun 2 13:41:01 2007 From: newsgroups at debain.org (Samuel) Date: Sat, 2 Jun 2007 17:41:01 +0000 (UTC) Subject: Automating a telnet session with an echo to stdout Message-ID: Hi, I am trying to automate a telnet session (currently using Python's telnetlib) and would like to echo any response of the remote host to stdout, as soon as it arrives on telnetlib's open TCP socket. Currently I print the return value of the read_some() method (or other read* methods) to the screen. However, that way of doing it means that the response gotten from the remote host is printed only periodically. Can anyone point me to how to enable the immediate echo? I know that this is possible using interact(), but I do not want to hand the session over to the user, I just want him to see what's going on. -Samuel From bj_666 at gmx.net Sat Jun 23 11:03:48 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Sat, 23 Jun 2007 17:03:48 +0200 Subject: SIMD powered Python References: <1182554657.444684.268050@i13g2000prf.googlegroups.com> <1182607699.214626.85230@u2g2000hsc.googlegroups.com> Message-ID: In <1182607699.214626.85230 at u2g2000hsc.googlegroups.com>, Bytter wrote: > Marc 'BlackJack' Rintsch escreveu: >> In <1182554657.444684.268050 at i13g2000prf.googlegroups.com>, Bytter wrote: >> >> > Is there any I&D ongoing about using SIMD [1] instructions, like SSE >> > [2], to speed up Python, especially regarding functional features, >> > like list comprehension, map and reduce, etc.. ? >> >> SIMD instruction sets know about "low level" data types, Python is about >> objects. `map()`, `reduce()`, list comprehension work on arbitrary >> iterables so how do you expect SIMD instructions handle this? Even simple >> lists contain objects and those don't have to be of the same type. > > True... But maybe in NumPy arrays that would be more feasible...? Yes but that's in external libraries and not in the Python interpreter. So it won't speed up Python code like list comprehensions but "just" calls to external functions written in C, Fortran or assembler if those make use of SIMD instructions. Ciao, Marc 'BlackJack' Rintsch From borud-news at borud.no Thu Jun 21 10:52:17 2007 From: borud-news at borud.no (Bjorn Borud) Date: 21 Jun 2007 16:52:17 +0200 Subject: The Modernization of Emacs: terminology buffer and keybinding References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182272495.990807.99110@a26g2000pre.googlegroups.com> <87tzt3ihev.fsf@kobe.laptop> <1182370216.961241.6960@n60g2000hse.googlegroups.com> Message-ID: [Twisted ] | | Being beginner-friendly doesn't have to be at the expense of power or | expert-user usability. depends on your definition of "expert". :-) | On the other hand, being actively beginner-hostile leads to nobody | adopting the tool. Then again, if you don't mind being the last | generation that'll ever use it, then I guess you're okay with that. obviously I lie awake dreading the day this happens. on my tombstone will say "here lies the last Emacs user on earth. M-x rip". -Bj?rn From paul at boddie.org.uk Mon Jun 25 08:25:21 2007 From: paul at boddie.org.uk (Paul Boddie) Date: Mon, 25 Jun 2007 05:25:21 -0700 Subject: Which XML? In-Reply-To: References: Message-ID: <1182774321.157937.289700@n2g2000hse.googlegroups.com> On 25 Jun, 02:04, Bruno Barberi Gnecco wrote: > I've found a lot of XML libraries for Python. Any advices on which > one to use (or *not* to use)? My requirements are: support for XPath, > stability (a must, segfaults are not an option), with DOM API and good > performance desirable. You might be interested in libxml2dom: http://www.python.org/pypi/libxml2dom It uses libxml2 under the covers, meaning that it has good performance and supports XPath, but I can't always guarantee stability: libxml2 can get quite upset in some situations, but I've worked fairly hard to avoid triggering them. The module API is similar to PyXML/minidom and I've found some time to add minimal support for DOM events and SVG, although there's a long way to go in both of these areas. This is a project with just me as the developer, although there are a number of helpful users who have kindly provided bug reports and suggestions for improvements over the years. Paul From lialie at gmail.com Sun Jun 3 00:31:48 2007 From: lialie at gmail.com (lialie) Date: Sun, 03 Jun 2007 12:31:48 +0800 Subject: How to control the creation of an instance? Message-ID: <46624434.3070103@gmail.com> Hi, suppose i have a free_object list[Sample1, Smaple2....]. when create a new object sample(*args, **kwds), if free_object_list isn't empty, just pop one from free_object_list instead of creating a new instance. any way to do this? I do some work as follows: class Sample(object): used_object = [] free_object = [] def __init__(self, *args, **kwds): pass def __new__(self, *args, **kwds): if Sample.free_object: obj = Sample.free_object.pop(0) else: obj = object.__new__(Sample, *args, **kwds) Sample.used_object.append(obj) return obj ######## still get a new instance :( def Release(self): Sample.used_object.remove(self) Sample.free_object.append(self) return True From mail at microcorp.co.za Wed Jun 6 02:36:19 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Wed, 6 Jun 2007 08:36:19 +0200 Subject: Who uses Python? References: <1180985830.288414.208850@q69g2000hsb.googlegroups.com><1181028719.829671.22230@a26g2000pre.googlegroups.com><1181034089.239173.282900@g4g2000hsf.googlegroups.com><1181062218.780387.219200@n4g2000hsb.googlegroups.com> Message-ID: <000401c7a8c3$1ce7f080$03000080@hendrik> "Stef Mientki" wrote: > I use Python as a replacement for MatLab, > and intend to use it as replacement for Delphi, AutoIt, PHP, VB. > And I'ld love to use it as a replacement for micro controller programming. If you have a little sub - 64k micro this is not really practical. What we have done is to define a limited virtual machine with a simple "assembler" language and used Python to write the "compiler" for it. Then you have to write the interpreter for the virtual machine in the native micro's code - Either using C or assembler, and you are away from the hardware, into a useful layer of abstraction. ... well sort of - in such a small thing, you are never really far from the hardware, as that is what its supposed to be controlling - but what it definitely buys you is that your apps written in your special language become portable between disparate processors like say an ARM at the upper end and an 8031/8051 at the lower... Such "interpreters" are surprisingly little code, and they work well - faster than what one would expect. - often outperforming C code that does pass by value... - Hendrik From moishyyehuda at gmail.com Fri Jun 8 00:06:38 2007 From: moishyyehuda at gmail.com (moishyyehuda at gmail.com) Date: Fri, 08 Jun 2007 04:06:38 -0000 Subject: mysqlimport error Message-ID: <1181275598.499237.207850@e65g2000hsc.googlegroups.com> whey when I execute this statment cursor.execute("""mysqlimport merchandise 1.txt""") I get this error ProgrammingError: (1064, "You have an error in your SQL syntax. Check the manual that corresponds to your MySQL server version for the right syntax to use near 'mysqlimport merchandise 1.txt' at line 1") args = (1064, "You have an error in your SQL syntax. Check the...se near 'mysqlimport merchandise 1.txt' at line 1") From nogradi at gmail.com Fri Jun 29 15:12:39 2007 From: nogradi at gmail.com (Daniel Nogradi) Date: Fri, 29 Jun 2007 21:12:39 +0200 Subject: Voluntary Abstract Base Classes In-Reply-To: References: <5f56302b0706290838j377ed7dct2cd2807394f791cf@mail.gmail.com> Message-ID: <5f56302b0706291212j327ece73j6017413a8373304d@mail.gmail.com> > > Well, the short question is: what are they? I've read Guido's python > > 3000 status report on > > http://www.artima.com/weblogs/viewpost.jsp?thread=208549 where he > > mentions ABC's but don't quite understand what the whole story is > > about. > > The story is at PEP 3119: > http://www.python.org/dev/peps/pep-3119/ Thanks, I overlooked that somehow. Daniel From bj_666 at gmx.net Fri Jun 8 11:36:26 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Fri, 08 Jun 2007 17:36:26 +0200 Subject: interating over single element array References: <4Beai.13210$5j1.6184@newssvr21.news.prodigy.net> Message-ID: In <4Beai.13210$5j1.6184 at newssvr21.news.prodigy.net>, T. Crane wrote: > Can someone please explain to me why I can't do something like this: > > a = 1 > > for value in a: > print str(value) > > If I run this I get the error: > > 'int' object is not iterable Well the message explains why you can't do this. `a` is bound to an integer and integers are not iterable. > Obivously this is an absurd example that I would never do, but in my > application the length of 'a' can be anything greater than 0, and I want to > be able to handle cases when 'a' has only one element without coding a > special case just in the event that len(a) = 1. ``len(a)`` wouldn't work either because integers have no "length": In [16]: a = 1 In [17]: len(a) --------------------------------------------------------------------------- exceptions.TypeError Traceback (most recent call last) /home/new/ TypeError: len() of unsized object > any suggestions are appreciated, Yes, don't try iterating over objects that are not iterable. ;-) What you *can* do is iterating over lists, tuples or other iterables with just one element in them. Try ``a = [1]``. Ciao, Marc 'BlackJack' Rintsch From lew at lewscanon.nospam Fri Jun 22 19:17:36 2007 From: lew at lewscanon.nospam (Lew) Date: Fri, 22 Jun 2007 19:17:36 -0400 Subject: The Modernization of Emacs In-Reply-To: <1182550354.781164.238200@z28g2000prd.googlegroups.com> References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182344981.372713.298580@w5g2000hsg.googlegroups.com> <86y7ieoiv7.fsf@lola.quinscape.zz> <1182347061.347199.133480@g4g2000hsf.googlegroups.com> <874pl2eg2j.fsf@W0053328.mgh.harvard.edu> <1182370016.986915.202150@u2g2000hsc.googlegroups.com> <87k5tx7444.fsf@W0053328.mgh.harvard.edu> <1182550354.781164.238200@z28g2000prd.googlegroups.com> Message-ID: Twisted wrote: > I find these anecdotes liberally sprinkled into this thread frankly > unbelievable. Either they are not using the same software I understand > "emacs" to refer to, or someone somewhere is simply lying. So if someone provides evidence with which you disagree, you accuse them of lying. There's no opportunity for reasoned discourse in the face of such tactics. Or room for new information to combat one's prejudices. -- Lew From paul at science.uva.nl Thu Jun 7 05:31:10 2007 From: paul at science.uva.nl (Paul Melis) Date: Thu, 07 Jun 2007 11:31:10 +0200 Subject: Help a C++ escapee! In-Reply-To: References: Message-ID: Hello, Simon Pickles wrote: > Can someone help me leave the murky c++ world and enter shiny pythonland? Welcome! > I have a problem with importing and global variables, here's my code: > > [...] > > When run, I come unstuck here: > > self.clientSocket, self.clientAddress = network.accept() > > I get a nameError on 'network', yet it is one in the global namespace, > defined in server.py before CServerThread.Listen() is called. That won't work (as you found out :)). You need to make 'network' available within socketManager.py. Each module on its own has a namespace, there isn't such a thing as a global namespace that is accessible from all modules, like you are used to in C or C++. So when you access the variable 'network' in module socketManager it is looked up in that module's namespace. When you read through socketManager.py (without looking at any other code) you will see that 'network' isn't being defined anywhere. I would solve it like this: Pass it as a parameter to CNetworkManager's and CServerThread's constructor and store it as an instance variable, i.e. for CNetworkManager: class CNetworkManager: def __init__(self, network): self.network = network ... and then later pass it again to the thread you're creating. Another way to have something a bit more like a global namespace would be to create a new module, say we name it globals.py. ------------------------- # globals.py # initially, no network set network = None ------------------------- Each module that needs access to globals would then import the globals module and access its variables. So, server.py would do import globals globals.network = CNetworkManager() globals.network.Listen() and socketManager.py would do import globals ... self.clientSocket, self.clientAddress = globals.network.accept() (You could also selectively import the network variable of course with "from globals import network"). Hope this helps, Paul From jadamson at partners.org Thu Jun 21 11:01:19 2007 From: jadamson at partners.org (Joel J. Adamson) Date: Thu, 21 Jun 2007 11:01:19 -0400 Subject: The Modernization of Emacs: terminology buffer and keybinding References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182272495.990807.99110@a26g2000pre.googlegroups.com> <87tzt3ihev.fsf@kobe.laptop> <1182370216.961241.6960@n60g2000hse.googlegroups.com> <85zm2ufjpb.fsf@lola.goethe.zz> <1182372592.803332.288260@u2g2000hsc.googlegroups.com> <5dtk4tF34jrimU1@mid.dfncis.de> Message-ID: <87bqf973nk.fsf@W0053328.mgh.harvard.edu> Matthias Buelow writes: > > Here's a nice one from Ken Thompson: > > ``I abhor a system designed for the "user", if that word is a coded > pejorative meaning "stupid and unsophisticated".'' That's a good one. It's going on my wall. Joel -- Joel J. Adamson Biostatistician Pediatric Psychopharmacology Research Unit Massachusetts General Hospital Boston, MA 02114 (617) 643-1432 (303) 880-3109 A webpage of interest: http://www.gnu.org/philosophy/sylvester-response.html From harry.g.george at boeing.com Thu Jun 21 08:10:21 2007 From: harry.g.george at boeing.com (Harry George) Date: Thu, 21 Jun 2007 12:10:21 GMT Subject: eggs considered harmful Message-ID: ...at least around here. I run a corporate Open Source Software Toolkit, which makes hundreds of libraries and apps available to thousands of technical employees. The rules are that a) a very few authorized downloaders obtain tarballs and put them in a depot and b) other users get tarballs from the depot and build from source. Historically, python packages played well in this context. Install was a simple download, untar, setup.py build/install. Eggs and with other setuptools-inspired install processes break this paradigm. The tarballs are incomplete in the first place. The builds sometimes wander off to the internet looking for more downloads. The installs sometimes wander off to the internet looking for compatibility conditions. (Or rather they try to do so and fail because I don't let themn through the firewall.) These are unacceptable behaviors. I am therefore dropping ZODB3, and am considering dropping TurboGears and ZSI. If the egg paradigm spreads, yet more packages will be dropped (or will never get a chance to compete for addition). I've asked before, and I'll ask again: If you are doing a Python project, please make a self-sufficient tarball available as well. You can have dependencies, as long as they are documented and can be obtained by separate manual download. Thanks for listening. -- Harry George PLM Engineering Architecture From nguyenhuuthanh at gmail.com Sat Jun 23 00:10:19 2007 From: nguyenhuuthanh at gmail.com (Genie T) Date: Sat, 23 Jun 2007 04:10:19 -0000 Subject: newbie question about unicode Message-ID: <1182571819.128093.18980@i13g2000prf.googlegroups.com> Hi, can anybody tell me whether these two expressions have the same meanings? s = u'' s1 = s.encode('utf-8') AND s1 = unicode(s,'utf-8') Thanks :) From kay.schluehr at gmx.net Thu Jun 21 13:53:33 2007 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Thu, 21 Jun 2007 10:53:33 -0700 Subject: PEP 3107 and stronger typing (note: probably a newbie question) In-Reply-To: References: Message-ID: <1182448413.966430.299590@m36g2000hse.googlegroups.com> On Jun 20, 8:53 pm, Stephen R Laniel wrote: > Reading [1], I wonder: why isn't the compiler making better > use of (purely optional) type labeling? Why not make a compiler > directive so that > > a) it will check the types of all my arguments and return > values, and maybe even > b) do some type inference up the call stack? That's simply because no one knows about the effects it has on Pythons programming practices. Hence it is outsourced to "3rd party packages" and these can be x-compilers as well that do all the inference stuff and translate to Pyrex, C++, D or any other language having an appropriate bridge. This stuff is simply beyond Python 3.0 and might be addressed in subsequent versions such as Python 3.1 or Python 3.2 when experiences are collected with different "annotations handlers". From showell30 at yahoo.com Wed Jun 13 00:15:22 2007 From: showell30 at yahoo.com (Steve Howell) Date: Tue, 12 Jun 2007 21:15:22 -0700 (PDT) Subject: Python's "only one way to do it" philosophy isn't good? In-Reply-To: Message-ID: <725498.90657.qm@web33511.mail.mud.yahoo.com> --- John Nagle wrote: > > There's a real reason. Remember, functions are > dynamically > replaceable. The compiler would have to detect that > the function > doesn't modify or replace itself while recursing for > this optimization > to be valid. Worst case, another thread could > replace the function > while it was recursing, invalidating the tail > recursion optimization. > You would just change the language definition to say that once you enter f(), any call to f() from within f() behaves as if the recursively called f() still points to the originally bound version of f. To want any other behavior would be absurd, anyhow. I could see the utility of this restriction even without optimization. ____________________________________________________________________________________ Boardwalk for $500? In 2007? Ha! Play Monopoly Here and Now (it's updated for today's economy) at Yahoo! Games. http://get.games.yahoo.com/proddesc?gamekey=monopolyherenow From sc0rp at hot.pl Fri Jun 22 16:41:36 2007 From: sc0rp at hot.pl (Jacek Trzmiel) Date: Fri, 22 Jun 2007 22:41:36 +0200 Subject: regular expression concatenation with strings In-Reply-To: <1182543519.337279.25800@z28g2000prd.googlegroups.com> References: <1182543519.337279.25800@z28g2000prd.googlegroups.com> Message-ID: <467C3400.1060603@hot.pl> Hi, oscartheduck wrote: > I have a little script that sits in a directory of images and, when > ran, creates thumbnails of the images. It works fine if I call the > function inside the program with something like "thumbnailer("jpg), > but I want to use a regular expression instead of a plain string so > that I can match jpeg, jpg, JPEG etc. Something like this will work: #!/usr/bin/env python #from PIL import Image import glob, os, re size = 128, 128 def thumbnailer(dir, filenameRx): for picture in [ p for p in os.listdir(dir) if os.path.isfile(os.path.join(dir,p)) and filenameRx.match(p) ]: file, ext = os.path.splitext(picture) im = Image.open (picture) im.thumbnail(size, Image.ANTIALIAS) im.save(file + ".thumbnail." + extension) jpg = re.compile(".*\.(jpg|jpeg)", re.IGNORECASE) thumbnailer(".", jpg) Best regards, Jacek. From ai.nature at gmail.com Fri Jun 1 12:31:14 2007 From: ai.nature at gmail.com (ai) Date: Fri, 01 Jun 2007 09:31:14 -0700 Subject: How to clean a module? In-Reply-To: <5cabv5F30c36fU1@mid.uni-berlin.de> References: <1180622824.836459.222090@q19g2000prn.googlegroups.com> <5c87f5F2mg4c1U1@mid.uni-berlin.de> <1180664579.182455.26170@g37g2000prf.googlegroups.com> <5cabv5F30c36fU1@mid.uni-berlin.de> Message-ID: <1180715474.762790.157990@d30g2000prg.googlegroups.com> thx On Jun 1, 6:50 pm, "Diez B. Roggisch" wrote: > ai wrote: > > Yes, you are right. > > But from this problem, could I infer that the statement "del xxx" > > doesn't release the memory which xxx used? > > It just removes the name xxx from the current scope - which will result in a > reference counter decrease. If that was the last reference, the object will > be destroyed. Most times. There are some special cases involving the usage > of __del__-methods on objects. > > Diez From mail at microcorp.co.za Fri Jun 8 02:59:52 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Fri, 8 Jun 2007 08:59:52 +0200 Subject: Bug/Weak Implementation? popen* routines can't handle simultaneousread/write? References: <1181232071.928835.301710@w5g2000hsg.googlegroups.com> Message-ID: <01f101c7a99e$7357a880$03000080@hendrik> "dmoore" wrote: 8< --------------- ------------ > Anybody have any thoughts on this? Do I have my story straight? (the > popen variants can't handle this case and there are no other > alternatives in the standard python distro) Is there some place I can > submit this as a feature request? (Python dev?) I think this is a hassle in the file implementation - I have had it also on serial ports, where it acts as if the file "driver" is inherently half duplex. It manifests as: "My characters don't come out" I don't know if it is python or the underlying stuff. I use fcntl to unblock and generally mess around to solve it, but I don't think my solution is portable. It is a real issue though - you are not imagining the dragon, it is right at the door... - Hendrik From gagsl-py2 at yahoo.com.ar Tue Jun 5 23:44:52 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 06 Jun 2007 00:44:52 -0300 Subject: Embedding Python in C References: <1180969118.795850.15160@w5g2000hsg.googlegroups.com> <1181025679.979188.52960@h2g2000hsg.googlegroups.com> Message-ID: En Tue, 05 Jun 2007 03:41:19 -0300, escribi?: > On 5 Jun., 01:32, "Gabriel Genellina" wrote: >> Yes, it appears that you are building a plain list but your code is >> expecting another kind of object. I'm unfamiliar with Numeric arrays, if >> that is what you need; perhaps someone else can help, or ask again in a >> Numeric-specific list. >> > yeah, i was looking at am array full of numbers. import numpy,scipy, > maybe pylab too while i was testing out the function over at a python > shell, make a linspace, sin it, and then call the function (which also > is from the scipy cookbook). Is numeric arrays (or ndarray) unlike > normal listing then? Since I started off programming in C, I am having > a bit of a confusion identifiying the different type of arrays, > listing and tuples and such... (since it's just "build an array of > type so and so, and pass it over" ^^;;) I've seen that you have already solved your main problem, but anyway I'll try to reduce your confusion a little... Python lists and tuples are "generic" containers: both can contain any kind of object, and each item may be of a different type: (1, 2.0, 3+0j, "four", u"F?nf", file("six")) is a tuple containing 6 items, all of different types. Tuples are immutable, lists can be modified. There is a price for such flexibility: memory and time overhead. When you don't require flexibility, you don't have to pay the price; Python already provides simple array objects (a flat container where ALL items are of the same type) and Numeric&Co support more array types and different floating point numbers. Those arrays are not the same thing as lists/tuples - altough they share a very similar interfase. -- Gabriel Genellina From dummy666 at mail.ru Fri Jun 22 17:23:11 2007 From: dummy666 at mail.ru (askel) Date: Fri, 22 Jun 2007 21:23:11 -0000 Subject: Adding method to a class on the fly In-Reply-To: <1182547065.295969.258820@g37g2000prf.googlegroups.com> References: <1182538969.522044.209560@q19g2000prn.googlegroups.com> <1182543862.369337.36880@z28g2000prd.googlegroups.com> <1182547065.295969.258820@g37g2000prf.googlegroups.com> Message-ID: <1182547391.088804.68260@x35g2000prf.googlegroups.com> On Jun 22, 5:17 pm, 7stud wrote: > On Jun 22, 2:24 pm, askel wrote: > > > class Dummy: > > def method(self, arg): > > print arg > > > def method2(self, arg): > > self.method(arg) > > > Dummy.method2 = method2 > > Dummy.method2('Hello, world!') > > Traceback (most recent call last): > File "test1.py", line 8, in ? > Dummy.method2('Hello, world!') > TypeError: unbound method method2() must be called with Dummy instance > as first argument (got str instance > instead) > > > > >I like that to be the same as: > > >class Dummy: > > def __init__(self): > > return > > > def method_dynamic(self): > > return self.method_static("it's me") > > > def method_static(self, text): > > print text > > return > > >so that I can do: > > >dum=Dummy.method_dynamic() > > >and see "it's me" printed. > > When are you able to see that? sorry, of course last line should be: Dummy().method2('Hello, world!') From gagsl-py2 at yahoo.com.ar Sat Jun 16 23:14:22 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 17 Jun 2007 00:14:22 -0300 Subject: Inserting breakpoints ... References: <1393$4673e30a$d443bb3a$26599@news.speedlinq.nl> Message-ID: En Sat, 16 Jun 2007 10:22:34 -0300, Stef Mientki escribi?: > for the simulation of some micro language (JAL), > the original language is (with a minimal effort) translated into Python, > after which the code is run in Python. > > I want to add a call to a debug routine, > called JSM(linenr), which performs task like wait, update user feedback, > etc. > This works, but doesn't give a nice output > > for xxx in xrange ( 16 * hardware_column ): > JSM(78) > Write_LCD_2Bytes ( write_text , 0 ) ;JSM(79) > Try sys.settrace() -- Gabriel Genellina From paul at boddie.org.uk Thu Jun 7 08:21:51 2007 From: paul at boddie.org.uk (Paul Boddie) Date: Thu, 07 Jun 2007 05:21:51 -0700 Subject: "On Your Desktop": the celebrity posting editorial blog In-Reply-To: References: Message-ID: <1181218911.216588.191370@q69g2000hsb.googlegroups.com> On 7 Jun, 12:09, James Stroud wrote: > Steve Holden wrote: > > The first post comes from Ian Bicking: > > >http://onyourdesktop.blogspot.com/ > > "Linux was a remote possibility: just why is it so bad as a laptop OS?" There are no mysteries about Linux vs. laptop hardware, although lightly-informed pontification on the subject fuels sites like OSNews. With secretive hardware vendors unwilling to tell people how their devices work, yet unwilling to write Linux drivers themselves, it's up to the community to make educated guesses about things like power management and the various mobile chipsets. Anyway, apart from the Python "celebrity" aspect, what's the Python connection? Paul From http Wed Jun 27 04:51:58 2007 From: http (Paul Rubin) Date: 27 Jun 2007 01:51:58 -0700 Subject: Python's "only one way to do it" philosophy isn't good? References: <7x3b0nmkk6.fsf@ruckus.brouhaha.com> <1182750077.570603.160240@q69g2000hsb.googlegroups.com> <7xir9cbm0g.fsf@ruckus.brouhaha.com> <7xejjzmk7u.fsf@ruckus.brouhaha.com> <7xy7i7xjl5.fsf@ruckus.brouhaha.com> Message-ID: <7x4pkt6aq9.fsf@ruckus.brouhaha.com> Douglas Alan writes: > > The thing is there was no standard way in Maclisp to write something > > like Python's "count" function and map over it. This could be done in > > Scheme with streams, of course. > > I'm not sure that you can blame MacLisp for not being object-oriented. > The idea hadn't even been invented yet when MacLisp was implemented > (unless you count Simula). If someone went to make an OO version of > MacLisp, I'm sure they'd get all this more or less right, and people > have certainly implemented dialects of Lisp that are consistently OO. count() has nothing to with OO, it's just the infinite stream 1,2,3,... which can be implemented as a Scheme closure the obvious way. > Right, but implementing generic reference-counted smart pointers is > about a page of code in C++, and nearly every large C++ application > I've seen uses such things. That's because C++ has no GC. > Gee, that's back to the future with 1975 Lisp technology. Destructors > are a much better model for dealing with such things (see not *all* > good ideas come from Lisp -- a few come from C++) and I am dismayed > that Python is deprecating their use in favor of explicit resource > management. Explicit resource management means needlessly verbose > code and more opportunity for resource leaks. And relying on refcounts to free a resource at a particular time is precisely explicit resource management. What if something makes a copy of the pointer that you didn't keep track of? The whole idea of so-called smart pointers is to not have to keep track of them after all. Anything like destructors are not in the spirit of GC at all. The idea of GC is to be invisible, so the language semantics can be defined as if all objects stay around forever. GC should only reclaim something if there is no way to know that it is gone. For stuff like file handles, you can tell whether they are gone or not, for example by trying to unmount the file system. Therefore they should not be managed by GC. > Also, I'm not convinced that it has to be a huge performance hit. > Some Lisp implementations had a 1,2,3, many (or something like that) > reference-counter for reclaiming short-lived objects. This bypassed > the real GC and was considered a performance optimization. (It was > probably on a Lisp Machine, though, where they had special hardware to > help.) That is a common technique and it's usually done with just one bit. > > because putting locks on the refcounts (someone tried in the late > > 90's) to allow multi-cpu parallelism slows the interpreter to a crawl. > > All due to the ref-counter? I find this really hard to believe. > People write multi-threaded code all the time in C++ and also use > smart pointers at the same time. I'm sure they have to be a bit > careful, but they certainly don't require a GIL. Heap allocation in C++ is a relatively heavyweight process that's used sort of sparingly. C++ code normally uses a combination of static allocation (fixed objects and globals), stack allocation (automatic variables), immediate values (fixnums), and (when necessary) heap allocation. In CPython, *everything* is on the heap, even small integers, so saying "x = 3" has to bump the refcount for the integer 3. There is a LOT more refcount bashing in CPython than there would be in something like a Boost application. > > Lisp may always be around in some tiny niche but its use as a > > large-scale systems development language has stopped making sense. > > It still makes perfect sense for AI research. I think most AI research is being done in other languages nowadays. There are some legacy Lisp systems around and some die-hards but I have the impression newer stuff is being done in ML or Haskell. I personally use Emacs Lisp every day and I think Hedgehog Lisp (a tiny functional Lisp dialect intended for embedded platforms like cell phones--the runtime is just 20 kbytes) is a very cool piece of code. But using CL for new, large system development just seems crazy today. > Re Lisp, though, there used to be a joke (which turned out to be > false), which went, "I don't know what the most popular programming > language will be in 20 years, but it will be called 'Fortran'". In > reality, I don't know what the most popular language will be called 20 > years from now, but it will *be* Lisp. Well, they say APL is a perfect crystal--if you add anything to it, it becomes flaws; while Lisp is a ball of mud--you can throw in anything you want and it's still Lisp. However I don't believe for an instant that large system development in 2027 will be done in anything like CL. See: http://www.cs.princeton.edu/~dpw/popl/06/Tim-POPL.ppt http://www.st.cs.uni-sb.de/edu/seminare/2005/advanced-fp/docs/sweeny.pdf (both are the same presentation, the links are the original Powerpoint version and a pdf conversion) for a game developer discussing his experiences with a 500 KLOC C++ program, describing where he thinks things are going. I find it compelling. Mostly he wants a dependently typed, pure functional language with explicit escapes to impurity in places, with a "lenient" evaluation strategy, i.e. sort of a softcore version of Haskell with less polymorphism but with dependent types for stuff like sized arrays. This is in order to get concurrency and parallelism automatically without dealing with threads and locks, which of course are even worse than malloc/free in terms of programmer insanity and pitfalls. Everyone is running dual core x86's on their desktop and 4-core cpu's are starting to appear, but the x86 is so complex that 4 cores per package seems to be the maximum at the moment. But some non-x86 designs are sporting as many as 16 cores on a chip (www.movidis.com) in general purpose computers, to say nothing of specialized ones like the Cell processor. We have run out of megahertz and we are going multicore. And if we don't start adopting languages that support parallelism sanely, we'll be left in the dust by those languages, just as Python (or Lisp or Java or whatever) have left non-GC languages in the dust. From steven at REMOVE.THIS.cybersource.com.au Wed Jun 20 06:29:59 2007 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 20 Jun 2007 10:29:59 GMT Subject: Python's "only one way to do it" philosophy isn't good? References: <1181368143.874341.273140@r19g2000prf.googlegroups.com> <7x3b0nmkk6.fsf@ruckus.brouhaha.com> Message-ID: On Tue, 19 Jun 2007 19:22:33 -0700, Paul Rubin wrote: > Steven D'Aprano writes: >> So, once you've succeeded in your campaign to make Python more like >> Scheme, what language will you use for getting real work done? >> >> And how long will it take before Schemers start agitating for it to >> become more like Scheme? > > While you've dutifully searched the horizon for such intrusion, the rot > has been quietly happening from within ;-). Nested scopes, first-class > functions and closures, internal lambdas, and lazy evaluation streams > (iterators) are all Schemish incursions into Python. List > comprehensions and genexps come from even further in the > functional-programming "beyond". Soon Python will implement a type > system based on the Lambda Cube, well maybe not. :) All of which makes Douglas Alan's accusations of Not Invented Here syndrome about Python seem rather silly. If there was ever a language that cherry-picked the best features of other languages, it was Python. If macros have been left out, it isn't because Guido has an irrational attitude of NIH. The point I was making isn't that Scheme/Lisp features are "bad", but that there is no reason to slavishly follow Scheme just because it is(?) technically the most "pure" programming language. Well, obscurity might be a little harsh. Perhaps a lot harsh. I think so long as there are programmers who want to play with programming, there will be a place for Scheme, and that place will continue to be sneered at by the sort of people who just want the job done, never mind whether it is the purest, most lambda-calculus-esque way of doing it or not. I'm glad somebody understands lambda calculus and closures and meta- classes, and that those people have created Python so I don't have to. And I suspect that for every Douglas Alan enamored with Scheme, there are ten thousand programmers who just want to use a handful of pre-built tools to get the work done, never mind using macros to create the tools they need before they can even start. It sounds all fine and dandy to talk about creating your own control structures with macros. Been there, done that: when I was programming in Forth, I was so excited about the ability to define my own control structures. Great! Why be limited to boring old IF and WHILE and all the others, when I can create my own? But that quickly passed, because, let's be honest, there really aren't that many useful control structures. There is a reason that most languages offer the same old boring IFs and WHILEs and FORs, instead of exciting new ones. As a Python programmer, maybe I'd like to see a CASE statement, but I don't _really_ need it. That's just an optimization. Same for REPEAT UNTIL: it would be a nice to have, not a must have. Same for macros -- if there is a sufficiently compelling use case for macros, one which won't end up with Python code turning into a billion different mini-languages, then I have trust that the Python-dev folk will eventually add it into the language. But "Scheme has macros" isn't a justification for why Python should have them. -- Steven. From josiah.carlson at sbcglobal.net Thu Jun 14 22:44:05 2007 From: josiah.carlson at sbcglobal.net (Josiah Carlson) Date: Fri, 15 Jun 2007 02:44:05 GMT Subject: dynamically generated runtime methods & reflection In-Reply-To: References: Message-ID: Josiah Carlson wrote: > Well, the particular operation is typically called 'currying a > function', and unless you know what to look for, it isn't very easy to > make happen. Replace "make happen" to "discover in the standard library". - Josiah From wgwigw at gmail.com Sun Jun 3 21:02:33 2007 From: wgwigw at gmail.com (momobear) Date: Mon, 04 Jun 2007 01:02:33 -0000 Subject: monitoring the filesystem for changes In-Reply-To: References: <1180796900.356829.31050@i13g2000prf.googlegroups.com> <1180839676.119233.199860@x35g2000prf.googlegroups.com> <1180896861.674525.296550@o11g2000prd.googlegroups.com> Message-ID: <1180918953.338075.123360@n15g2000prd.googlegroups.com> > You could use the ReadDirectoryChangesW in overlapped > mode. I've never tried it, so I don't know how > robust it would be. Why is it a problem to have > "multiple programs" running? And is that simply > multiple threads, or multiple processes? I used overlapped in my program, it runs about 1 week, seems no problems now. FILE_LIST_DIRECTORY = 0x0001 hDir = None def __init__(self, directory): self.hDir = win32file.CreateFile ( directory, self.FILE_LIST_DIRECTORY, win32con.FILE_SHARE_READ | win32con.FILE_SHARE_WRITE, None, win32con.OPEN_EXISTING, win32con.FILE_FLAG_BACKUP_SEMANTICS| win32con.FILE_FLAG_OVERLAPPED, None ) but I didn't try use multiple program do the same action. I think only one thread to do directory monitor is enough. other thread and process can communicate with it use thread or process communication. Wang Wei From hari.siri74 at gmail.com Tue Jun 26 20:48:50 2007 From: hari.siri74 at gmail.com (hari sirigibathina) Date: Tue, 26 Jun 2007 19:48:50 -0500 Subject: Unbound Local error --??? Message-ID: Hi all, Have a question which is making me unrest: -Calling a method say aMethod() from another method where i mistakenly initialised a variable with name same as the called method like aMethod = 'string'. When i run this py script triggered "Unbound Local error". can any one explain me whats going here ? curios to learn from my mistake :) -- Warm Regards, Hari -------------- next part -------------- An HTML attachment was scrubbed... URL: From exhuma at gmail.com Mon Jun 11 08:23:48 2007 From: exhuma at gmail.com (exhuma.twn) Date: Mon, 11 Jun 2007 05:23:48 -0700 Subject: Pasting an image from clipboard in Tkinter? Message-ID: <1181564628.443138.165380@k79g2000hse.googlegroups.com> As many might know, windows allows to copy an image into the clipboard by pressing the "Print Screen" button on the keyboard. Is it possible to paste such an image from the clipboard into a "Text" widget in Tkinter? Here is my first attempt with just trying to print out the image data: ----------------- def pasteImg(tgt): global clipboardEnabled if not clipboardEnabled: return win32clipboard.OpenClipboard(0) print win32clipboard.GetClipboardData() win32clipboard.CloseClipboard() ----------------- This works fine with selecting text, but comes up with the following error when trying to paste an image: ----------------- Exception in Tkinter callback Traceback (most recent call last): File "C:\Python25\lib\lib-tk\Tkinter.py", line 1403, in __call__ return self.func(*args) File "X:\development\testing\tkwiki\tkwiki.py", line 52, in Button( root, command=lambda: pasteImg(txt) ).pack() File "X:\development\testing\tkwiki\tkwiki.py", line 38, in pasteImg print win32clipboard.GetClipboardData() TypeError: Specified clipboard format is not available ----------------- Obviously the clipboard does not know about that format. Does that mean I have to wait until it's implemented or are there other ways to access the image data? From aisaac at american.edu Thu Jun 28 09:27:46 2007 From: aisaac at american.edu (Alan Isaac) Date: Thu, 28 Jun 2007 13:27:46 GMT Subject: guidance needed: best practice for script packaging In-Reply-To: References: Message-ID: My thanks to Gabriel and Josiah. Alan From aleax at mac.com Sat Jun 2 00:21:40 2007 From: aleax at mac.com (Alex Martelli) Date: Fri, 1 Jun 2007 21:21:40 -0700 Subject: Create a new class on the fly References: <1180568447.449581.250500@g37g2000prf.googlegroups.com> <1hyy30j.f4k5tc17kc7ohN%aleax@mac.com> <1180732492.717760.288190@n15g2000prd.googlegroups.com> Message-ID: <1hz1s32.1e0j3ee1fmijbnN%aleax@mac.com> py_genetic wrote: > Alex, thanks for the advise: > > > > class PosRecords(tables.IsDescription): > > > > > class A(object): > > > self.__init__(self, args): > > > > This makes 0 sense; maybe you should learn elementary Python syntax well > > _before_ trying advanced stuff, no? > > I accidently left that erroneous snippet in, however if your offering > a class in smart ass let me know where to sign up. Thanks for snipping all the actual helpful stuff I posted, it makes SO much easier for me to be snide! You can find a few examples of me demonstrating the subject of your interest by searching for my name e.g. on video.google.com; searching for my name on Amazon will show some books using similar techniques, and searching for my name on groups.google.com will find about 50,000 posts many of which exhibit essentially the same approach. Unfortunately, I can't currently offer such courses commercially while staying employed as Uber Tech Lead for Google, Inc, but if the monies on offer make it worth my while for me to drop million bucks worth of stock options, plus a vigorish for my other comp package _and_ the incredible amount of happiness I get every day from my job (where I get to interact with truly brlliant people, who, if and when they "leave an erroneous snippet in", are GRATEFUL to me for pointing it out, rather than RESENTFUL and DEFENSIVE), I'll surely consider that most seriously (as long as the monies in question are in escrow for my personal reassurance). Until such conditions should obtain, I'll just have to keep freely helping the people who are WORTH helping, and poking sarcastic funs at those who prove themselves ot be a waste of oxygen instead. May you have the life you deserve, Alex From doug at alum.mit.edu Wed Jun 27 00:54:21 2007 From: doug at alum.mit.edu (Douglas Alan) Date: Wed, 27 Jun 2007 00:54:21 -0400 Subject: Python's "only one way to do it" philosophy isn't good? References: <1182750077.570603.160240@q69g2000hsb.googlegroups.com> <7xir9cbm0g.fsf@ruckus.brouhaha.com> <7xejjzmk7u.fsf@ruckus.brouhaha.com> <7xy7i7xjl5.fsf@ruckus.brouhaha.com> <1182872972.417776.78650@o11g2000prd.googlegroups.com> <1182873568.454491.302860@e9g2000prf.googlegroups.com> <7xps3iy73h.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin writes: > Andy Freeman writes: >> Compare that with what a programmer using Python 2.4 has to do if >> she'd like the functionality provided by 2.5's with statement. Yes, >> with is "just syntax", but it's extremely useful syntax, syntax that >> can be easily implemented with lisp-style macros. > Not really. The with statement's binding targets all have to support > the protocol, which means a lot of different libraries need redesign. > You can't do that with macros. But that's a library issue, not a language issue. The technology exists completely within Lisp to accomplish these things, and most Lisp programmers even know how to do this, as application frameworks in Lisp often do this kind. The problem is getting anything put into the standard. Standardizing committees just suck. I just saw a presentation today on the Boost library for C++. This project started because the standard library for C++ is woefully inadequate for today's programming needs, but any chance of getting big additions into the standard library will take 5-10 years. Apparently this is true for all computer language standards. And even then, the new standard will be seriously lacking, because it is usually based on armchair thinking rather than real-world usage. So the Boost guys are making a defacto standard (or so they hope) library for C++ that has more of the stuff you want, and then when the standardizing committees get around to revising the actual standard, the new standard will already be in wide use, meaning they just have to sign off on it (and perhaps suggest a few tweaks). Alas, the Lisp standards are stuck in this sort of morass, even while many implementations do all the right things. Python doesn't have this problem because it operates like Boost to begin with, rather than having a zillion implementations tracking some slow moving standard that then mandates things that might be nearly impossible to implement, while leaving out much of what people need. But then again, neither do many dialects of Lisp, which are developed more or less like Python is. But then they aren't standards compliant, and so they don't receive wide adoption. > Macros can handle some narrow special cases such as file-like > objects, handled in Python with contextlib.closing. Macros handle the language part of things in Lisp perfectly well in this regard. But you are right -- they certainly can't make standardizing committees do the right thing. |>oug From srinivas.gundelli at googlemail.com Wed Jun 27 05:38:18 2007 From: srinivas.gundelli at googlemail.com (IT Recruiter) Date: Wed, 27 Jun 2007 09:38:18 -0000 Subject: Searching for Python Talent !! Message-ID: <1182937098.102558.157320@n2g2000hse.googlegroups.com> Hello friends! I am looking for a GUI focused Python developer to help in Website development with some wxpython experience... It's very useful to have other programming languages and paradigms About Client: Software house, fastest growing in the commercial market This is a permanent role in London city, paying as per market rate for the excellent candidate About Me: I am a Resourcing Consultant specialist in recruiting for Open Source Technologies. Please do not hesitate to contact me or write me back! Cheers, Srini From me at privacy.net Sun Jun 17 11:10:01 2007 From: me at privacy.net (mark carter) Date: Sun, 17 Jun 2007 16:10:01 +0100 Subject: sqlite3 bug?? In-Reply-To: <1182091411.108272.286280@o61g2000hsh.googlegroups.com> References: <46752230$0$31685$db0fefd9@news.zen.co.uk> <46753426$0$30325$fa0fcedb@news.zen.co.uk> <1182091411.108272.286280@o61g2000hsh.googlegroups.com> Message-ID: <46754ecc$0$5865$da0feed9@news.zen.co.uk> 7stud wrote: > On Jun 17, 7:16 am, mark carter wrote: >> David Wahler wrote: >>> On 6/17/07, mark carter wrote: >>>> Anyone else getting these problems? >>> Seehttp://www.python.org/dev/peps/pep-0249/(emphasis mine): >>> .commit() >> >> I'm seriously thinking about reporting the commit() thing as a doc bug >> in python, as this isn't mentioned at >> http://docs.python.org/lib/module-sqlite3.html >> and I think it's exactly the kind of thing that should be mentioned in >> the examples. > > Please report the whole docs as a bug. http://sourceforge.net/tracker/index.php?func=detail&aid=1738670&group_id=5470&atid=105470 That will save a few people tearing their hair out! From asincero at gmail.com Wed Jun 20 08:21:30 2007 From: asincero at gmail.com (asincero) Date: Wed, 20 Jun 2007 05:21:30 -0700 Subject: Using a switch-like if/else construct versus a dictionary? In-Reply-To: <1182283903.219689.200420@g37g2000prf.googlegroups.com> References: <1182282008.522677.269730@g4g2000hsf.googlegroups.com> <1182283903.219689.200420@g37g2000prf.googlegroups.com> Message-ID: <1182342090.350359.321520@c77g2000hse.googlegroups.com> Ahh .. yes of course, you are right. I mis-typed. I like how you defined the dictionary all in one statement, though. I didn't think of doing it that way. -- Arcadio On Jun 19, 4:11 pm, heltena wrote: > asincero ha escrit: > > > > > def foo(): > > def doCase1(): > > pass > > def doCase2(): > > pass > > def doCase3(): > > pass > > def doCase4(): > > pass > > def doCase5(): > > pass > > > handle_case = {} > > handle_case[1] = doCase1() > > handle_case[2] = doCase2() > > handle_case[3] = doCase3() > > handle_case[4] = doCase4() > > handle_case[5] = doCase5() > > Sorry, but I think this is not correct. Now, you put the result of the > function call into the dictionary, but you want the function address. > > The correct code is: > handle_case = {} > handle_case[1] = doCase1 > handle_case[2] = doCase2 > handle_case[3] = doCase3 > handle_case[4] = doCase4 > handle_case[5] = doCase5 > > Or: > handle_case = { 1: doCase1, 2: doCase2, 3: doCase3, 4: doCase4, 5: > doCase 5 } > > Or: > try: > { 1: doCase1, 2: doCase2, 3: doCase3, 4: doCase4, 5: doCase 5 } > [c]() > except: > print "Catch the correct exception" > > But this solutions only works fine if the params of the functions are > the same for all calls (in if/else construct you don't need it). > > Bye! > > -- > Helio Tejedor From JoeSalmeri at hotmail.com Fri Jun 1 07:55:50 2007 From: JoeSalmeri at hotmail.com (Joe Salmeri) Date: Fri, 1 Jun 2007 07:55:50 -0400 Subject: Python 2.5.1 broken os.stat module References: <1180648618.295955.68600@x35g2000prf.googlegroups.com> <465fa702$0$2944$9b622d9e@news.freenet.de> Message-ID: ""Martin v. L?wis"" wrote in message news:465fa702$0$2944$9b622d9e at news.freenet.de... >> I created a file and specifically set the created date, last accessed >> date >> and last write date to >> >> 01/02/2003 12:34:56 > > How did you do that? I used a "touch" utility to set the dates but let's try it a different way. Let's use Python 2.5.1 to set the timestamps ---->> set file timestamp import pywintypes import win32file import sys file_name = sys.argv[1] new_timestamp = pywintypes.Time([2003, 1, 2, 12, 34, 56]) f = win32file.CreateFile(file_name, win32file.GENERIC_WRITE, 0, None, win32file.OPEN_EXISTING, 0, 0) win32file.SetFileTime(f, new_timestamp, new_timestamp, new_timestamp) f.Close() Next I created an empty file with notepad. Then I used the above code to set the 3 timestamps. Let's confirm that Windows has the timestamps set to what we set them too. Here are the timestamps as reported by Windows: dir /tc joe.txt 01/02/2003 12:34 PM 0 joe.txt dir /ta joe.txt 01/02/2003 12:34 PM 0 joe.txt dir /tw joe.txt 01/02/2003 12:34 PM 0 joe.txt Looks like the python code worked to correctly set the timestamps (Note you can also verify them using properties on the file in Windows Explorer) Here is some python code to print out the timestamps: import os import stat import sys import time file_name = sys.argv[1] file_stats = os.stat(file_name) print 'Creation Time: %s' % time.strftime('%m/%d/%Y %H:%M:%S', time.localtime(file_stats[stat.ST_CTIME])) print 'Last Access Time: %s' % time.strftime('%m/%d/%Y %H:%M:%S', time.localtime(file_stats[stat.ST_ATIME])) print 'Last Write Time: %s' % time.strftime('%m/%d/%Y %H:%M:%S', time.localtime(file_stats[stat.ST_MTIME])) Now let's see what Python 2.4.2 says about the file Creation Time: 01/02/2003 12:34:56 Last Access Time: 01/02/2003 12:34:56 Last Write Time: 01/02/2003 12:34:56 Looks like Python 2.4.2 is reporting the timestamps correctly Now let's see what Python 2.5.1 says Creation Time: 01/02/2003 11:34:56 Last Access Time: 01/02/2003 11:34:56 Last Write Time: 01/02/2003 11:34:56 All times are off by 1 hour! Let's re-verify that Windows still says the timestamps are 01/02/2003 12:34:56. dir /tc joe.txt 01/02/2003 12:34 PM 0 joe.txt dir /ta joe.txt 01/02/2003 12:34 PM 0 joe.txt dir /tw joe.txt 01/02/2003 12:34 PM 0 joe.txt Windows still says the times are what we set them too. Opening up Windows Explorer also confirms that the times are still 01/02/2003 12:34:56. My text editor has a was to display the file names and timestamp info just like a dir command Let's see what it says: h: joe .txt 0 1/02/03 12:34 \ The text editor is reporting the correct timestamps too. So far everything else I try seems to report the timestamps correctly except for Python 2.5.1. It is difficult for me to believe that EVERYTHING else is wrong and Python 2.5.1 is correct, especially when you consider the fact that the code in Python 2.5.1 that performs this functionality is not the same code that was used in previous Python versions. Normally if something is not working, the biggest suspect is the last thing changed. In my other msg I posted a program that compares the timestamps of a dir /tc, dir /ta, and dir /tw for all files against what Python is reporting. This allows us to easily verify what Windows says the timestamps are versus what Python says they are. Python 2.4.2 ALWAYS got it correct. Python 2.5.1 gets it wrong as much as 50% of the time. So unless you are saying that Windows is wrong, Python 2.5.1 has to be wrong since it does not compare to what Windows reports. Since everything else I have tried matches what Windows reports that leads me to believe that Python 2.5.1 has to be wrong. >> I even found situations where the python timestamp was 1 minute later. >> (I >> know about the 2 second timestamps on FAT, all my filesystems are NTFS). >> I >> just found a situation where the python timestamp was 02:51 PM and the >> windows timestamp was 02:12 PM. DST or timezone changes are not going >> to >> make the results be off by 39 minutes? (My timezone is GMT - 5:00). > > Right. If that is reproducable, it is a bug. Please create a zip file > containing this file, and submit a bug report to sf.net/projects/python. Please see my other msg, I ran the program in that msg against the Python\lib directory: I tried it on multiple machines and found the same problems occurring. I already submitted a bug report with the sample code that demonstrates the problem. All Python 2.4.2 timestamps match what Windows reports The Python 2.5.1 timestamps vary Sometimes python is +1 minute Sometimes python is -1 hour Sometimes python is +59 minutes Sometimes python is +42 minutes Sometimes python is +37 minutes Sometimes python +2 minutes Sometimes python +30 minutes Sometimes python +3 minutes Sometimes python +33 minutes There is no way a timezone difference could explain those variations. Bottom line is that Python should be reporting what Windows reports. Even if it turns out that Windows has a bug and is wrong I still think that Python should be reporting the same thing because what Windows reports is what is expected. If Python reports something different (even if it was correct) the information is not useful if it differs from what everything else is reporting. I hope I have provided enough information for you to reproduce the bug so that a solution can be found. Thanks for your time investigating this. From rw at smsnet.pl Tue Jun 5 10:06:15 2007 From: rw at smsnet.pl (Rob Wolfe) Date: Tue, 05 Jun 2007 07:06:15 -0700 Subject: subprocess leaves child living In-Reply-To: References: Message-ID: <1181052375.551083.117390@p47g2000hsd.googlegroups.com> Thomas Dybdahl Ahle wrote: > Problem is - I can't do that when I get killed. > Isn't it possible to open processes in such a way like terminals? If I > kill the terminal, everything open in it will die too. On POSIX platform you can use signals and ``os.kill`` function. Fo example: import os, signal from subprocess import Popen from time import sleep def handler(signum, frame): print 'Signal handler called' raise KeyboardInterrupt signal.signal(signal.SIGTERM, handler) try: popen = Popen(["ping", "google.com"]) try: sleep(100) except KeyboardInterrupt: pass finally: if popen.poll() is None: print "killing process: %d" % popen.pid os.kill(popen.pid, signal.SIGTERM) -- HTH, Rob From tjreedy at udel.edu Thu Jun 21 20:04:50 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 21 Jun 2007 20:04:50 -0400 Subject: Python's "only one way to do it" philosophy isn't good? References: <1181368143.874341.273140@r19g2000prf.googlegroups.com><7x3b0nmkk6.fsf@ruckus.brouhaha.com> Message-ID: "Steven D'Aprano" wrote in message news:pan.2007.06.21.10.19.47 at REMOVE.THIS.cybersource.com.au... | On Wed, 20 Jun 2007 17:23:42 -0400, Douglas Alan wrote: | > Macros are a way to abstract syntax the way that objects are used to | > abstract data types and that iterators and generators abstract control, | > etc. | | But why is the ability to abstract syntax good? I think this points to where Sussman went wrong in his footnote and Alan in his defense thereof. Flexibility of function -- being able to do many different things -- is quite different from flexibility of syntax -- being to say 'do this' many different ways. An system with a limited repetoire of actions could have multiple ways to invoke each. But it would still be limited and inflexible in respect to what it can do. Sussman's essay advocates functional flexibility. So when he claims that some advocate against 'flexibility', I think it entirely reasonable to read that as 'operational flexibility'. But when he present Peters (and Python) as being against [operational] flexibility, he is wrong. Tim's main sentence is "There should be one obvious way to do it" where 'it' is anything one might sensibly want to do in real-life code. That to me is advocacy of flexibility and not the opposite. The parenthetical insertion '-- and preferably only one --' is advocacy against needless# *semantic* duplication and is in no way a statement against *functional* flexibility. (In particular, the clause is, I believe, meant to differentiate Python from a certain other language which purportedly has a 'many ways is good' philosophy ;-) The followup line is 'Although that way may not be obvious at first unless you're Dutch'. It marks the piece as something other than a serious academic philosophical dissertation. Tim Peters is also Mr. [fractional] Wink. Terry Jan Reedy From __peter__ at web.de Mon Jun 4 05:43:19 2007 From: __peter__ at web.de (Peter Otten) Date: Mon, 04 Jun 2007 11:43:19 +0200 Subject: subexpressions (OT: math) References: <4662675b$1_5@news.bluewin.ch> <1180890214.317409.85100@w5g2000hsg.googlegroups.com> <1180894045.538031.111610@g4g2000hsf.googlegroups.com> <1180895200.108582.313010@k79g2000hse.googlegroups.com> Message-ID: Stebanoid at gmail.com wrote: > sine is a dimensionless value. > if we expand sine in taylor series sin(x) = x - (x^3)/6 + (x^5)/120 > etc. > you can see that sin can be dimensionless only if x is dimensionless > too. With y = x^2 = 1/3 pi^2 - 4(cos x - cos(2x)/2^2 + cos(3x)/3^2 - ...) area is dimensionless, too, I suppose. > I am a professional physicist and a know about what I talk Then you can kindly point me to the flaw in that logic :-) Peter From thomas at jollans.com Wed Jun 27 15:41:36 2007 From: thomas at jollans.com (Thomas Jollans) Date: Wed, 27 Jun 2007 21:41:36 +0200 Subject: Capturing and sending keys {Esperanto} In-Reply-To: References: Message-ID: AJK wrote: > Hello there! > > I've been googleing yet, and suppose it's hopeless to try, but better > ask it... > > I want to write a program which turns Cx to ?, cx to ? et al WHILE > TYPING. (i.e. converting Esperanto x-system to real hats, for those > who know about this.) Therefore I though will need to capture the last > 2 typed characters (from any application), send a double backspace and > after that send the correct letters (back to the same application)... > > However, it seems inpossible to capture those letters, and maybe to > send them too... I'm not quite sure what you want to do. Is this in a Tkinter application or somthing like that ? Do you want this to be hooked into some layer of some operating system to work universally ? Which operating system ? Thomas Jollans -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 260 bytes Desc: OpenPGP digital signature URL: From mclaugb at nospm.yahoo.com Tue Jun 19 11:35:28 2007 From: mclaugb at nospm.yahoo.com (mclaugb) Date: Tue, 19 Jun 2007 16:35:28 +0100 Subject: ctypes pointer References: Message-ID: I answered this one already. from ctypes import * libx = CDLL("small_dll5.dll", RTLD_GLOBAL) libx = cdll.small_dll4 libx.adder.restype = None libx.adder.argtypes = [c_double, c_double, POINTER(c_double)] real=c_double(0) imag=c_double(0) zz=libx.adder(3.342,4,byref(size)) print size "mclaugb" wrote in message news:f58rp6$kig$1 at gemini.csx.cam.ac.uk... >I have a simple function > > void adder(double a, double b, double *c){ > *c = a+b; > } > > i have created a shared dll -- "small_dll4.dll" of it using visual studio. > > now i wish to call it from python. > to do so, i have done the following: > > libx = cdll("small_dll4.dll", RTLD_GLOBAL) > libx.adder.argtypes = [c_double, c_double, POINTER(c_double)] > libx.adder.restype = None > size=c_double() > zz=libd.adder(3.342, 4, byref(size)) > > and the result is an access violation! > > File "", line 0, in __main__ > WindowsError: exception: access violation reading 0x7EF9DB23 > > I cant figure out what is causing this. > thanks in advance, > Bryan > From paddy3118 at googlemail.com Sat Jun 9 03:02:28 2007 From: paddy3118 at googlemail.com (Paddy) Date: Sat, 09 Jun 2007 07:02:28 -0000 Subject: PythonS? In-Reply-To: References: Message-ID: <1181372548.673154.172610@q69g2000hsb.googlegroups.com> On Jun 9, 3:51 am, Michel Claveau wrote: > Hi! > > Python, Iron-Python, Jython, StackLess-Python, Monty-Python, > Movable-Python, etc. > > Shouldn't add a "S" to the end of "Python"? > > See:http://www.jfwilliam.com/Sites/1473/Python.jpg > > The fact of adding a "S" could constitute a PEP. > for classification, I propose: PEP'S > > -- > @-salutations > > Michel Claveau I'd vote for a more serpentine Pythonssss :-) - Paddy. From evan at yelp.com Fri Jun 22 14:20:03 2007 From: evan at yelp.com (Evan Klitzke) Date: Fri, 22 Jun 2007 11:20:03 -0700 Subject: Tailing a log file? Message-ID: Everyone, I'm interested in writing a python program that reads from a log file and then executes actions based on the lines. I effectively want to write a loop that does something like this: while True: log_line = log_file.readline() do_something(log_line) Where the readline() method blocks until a new line appears in the file, unlike the standard readline() method which returns an empty string on EOF. Does anyone have any suggestions on how to do this? Thanks in advance! -- Evan Klitzke From noreply at gcgroup.net Sun Jun 24 13:47:17 2007 From: noreply at gcgroup.net (William Gill) Date: Sun, 24 Jun 2007 13:47:17 -0400 Subject: smtp server simulation using Python In-Reply-To: References: Message-ID: Dave Borne wrote: >> I have a (web) development computer w/o an SMTP server and want to test >> form generated e-mail using a dummy SMTP server that delivers the mail >> message to a file, or better yet, to a text editor instead of actually >> sending it. > > Here's a quick and dirty script I use this for email testing purposes > - it's windows specific, but that's easy enough to change. Actually XP is where I need it. Thanks Bill > > import smtpd, os, time, asyncore > > class mailserver(smtpd.SMTPServer): > def __init__(self): > smtpd.SMTPServer.__init__(self, ('',25), None) > print 'Mailsink listening on port 25' > > def process_message(self, peer, mailfrom, rcpttos, data): > basepath='c:\\.maildump' > > print 'mail from: %s to: %s' %(mailfrom, repr(rcpttos)) > for rcpt in rcpttos: > rcpt = rcpt.split('@')[0] > try: > os.mkdir(basepath+'\\'+rcpt) > except OSError: > pass > > f = > file(basepath+'\\'+rcpt+'\\'+mailfrom+time.strftime('%Y%m%d%H%M%S'), > 'w') > f.write(data) > f.close() > > def loop (): > x = mailserver() > try: > asyncore.loop(timeout=2) > except KeyboardInterrupt: > print'interrupt' > x.close() > > if __name__=='__main__': > loop() From jeremy+complangpython at jeremysanders.net Mon Jun 18 05:20:39 2007 From: jeremy+complangpython at jeremysanders.net (Jeremy Sanders) Date: Mon, 18 Jun 2007 10:20:39 +0100 Subject: Matrix Multiplication References: <1182113543.957069.135240@k79g2000hse.googlegroups.com> <1182118748.755871.267780@u2g2000hsc.googlegroups.com> Message-ID: sturlamolden wrote: > Use numpy: www.scipy.org > > NumPy has a matrix type that overloads the * operator. Just a tiny followup, which may be important unless you carefully read the documentation. The "*" operator doesn't do matrix multiplication for normal numpy arrays - you do need to use its special matrix type to get this. You can use the dot function to get matrix multiplication with its normal arrays. Jeremy -- Jeremy Sanders http://www.jeremysanders.net/ From gagsl-py2 at yahoo.com.ar Sat Jun 9 01:57:47 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 09 Jun 2007 02:57:47 -0300 Subject: Dealing with dictionary like strings References: <457848.7849.qm@web54506.mail.re2.yahoo.com> Message-ID: En Fri, 08 Jun 2007 19:23:38 -0300, Mr SZ escribi?: > I'm using the urllib module to fetch pages from the web.The returned > response is in the structure of a dictionary .For eg: > > {"":"","label": [ > ] > ,"torrents": [ > > ["F0666BDCCBFD01A52535759C044485E2E1CCE3C3",136,"AAA",1250164864,651,646185088,606208,0,0,0,-1,"",0,0,0,0,33564,7,342884352], > ["46683EA1C950CB020DD6DD3007120EAB9966FA79",201,"tpg",4153995264,305,841170944,758087680,901,0,0,103109046,"",4,23,0,0,64080,2,2887053312]] > ,"torrentc": "2001899868"} > > This response as we can see is not just like a dictionary but it's > values are in the form of lists.Now,is there a way I can deal with this > string as a dictionary .I'm only interested in the value field of > torrents key which again is a list of lists. See this Cookbook recipe: safe eval http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/364469 -- Gabriel Genellina From martin at v.loewis.de Thu Jun 28 16:07:42 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Thu, 28 Jun 2007 22:07:42 +0200 Subject: Vista 64 + Python2.5 + wxpython 28 issue In-Reply-To: References: Message-ID: <4684150e$0$24850$9b622d9e@news.freenet.de> > I have installed python 2.5 (AMD64) on Vista (64), also installed wx 2.8 > but I'm getting this error: > > """" > Traceback (most recent call last): > File "mymodule.py", line 39, in > import wx > File "C:\Python25\Lib\site-packages\wx-2.8-msw-unicode\wx\__init__.py", > line 4 > 5, in > from wx._core import * > File "C:\Python25\Lib\site-packages\wx-2.8-msw-unicode\wx\_core.py", > line 4, i > n > import _core_ > ImportError: DLL load failed with error code 193 > """ > > I have set python.exe to run under admin but that do not fix the problem. > > Any ideas ? 193 means ERROR_BAD_EXE_FORMAT. Could it be that you are using a 32-bit extension DLL? How precisely did you "install" wx 2.8? Did you rebuild it from source? Regards, Martin From josiah.carlson at sbcglobal.net Thu Jun 14 22:43:27 2007 From: josiah.carlson at sbcglobal.net (Josiah Carlson) Date: Fri, 15 Jun 2007 02:43:27 GMT Subject: save class In-Reply-To: <1181847914.603957.174200@n15g2000prd.googlegroups.com> References: <1181784016.454693.42340@o11g2000prd.googlegroups.com> <1181787082.712869.72770@z28g2000prd.googlegroups.com> <1181847914.603957.174200@n15g2000prd.googlegroups.com> Message-ID: nik wrote: > of having to keep track of a separate dictionary file. I am new to > this, but I thought that this would be a regular thing to do in > python, because people must make classes in the interactive console > and then export them somehow for later use. Create a file. Put your code in it. Run your code. Occasionally copy/paste your code into the console for testing and/or learning about how Python works. If you write something you want to keep in the console, copy it out of the console and paste it into your source file(s). - Josiah From waldemar.osuch at gmail.com Mon Jun 4 01:10:39 2007 From: waldemar.osuch at gmail.com (Waldemar Osuch) Date: Sun, 03 Jun 2007 22:10:39 -0700 Subject: excel library without COM In-Reply-To: <1180918791.467050.186520@r19g2000prf.googlegroups.com> References: <1180918791.467050.186520@r19g2000prf.googlegroups.com> Message-ID: <1180933839.041293.104720@g37g2000prf.googlegroups.com> On Jun 3, 6:59 pm, james_027 wrote: > is there any library to help me write excel files without using win > com? One option is: https://secure.simplistix.co.uk/svn/xlwt/trunk From zapman449 at gmail.com Mon Jun 25 14:50:06 2007 From: zapman449 at gmail.com (Jason Zapman II) Date: Mon, 25 Jun 2007 11:50:06 -0700 Subject: How to save initial configuration? (program installation) In-Reply-To: <1182788059.409235.243380@m36g2000hse.googlegroups.com> References: <1182783746.718276.209460@w5g2000hsg.googlegroups.com> <1182784231.530101.258640@q75g2000hsh.googlegroups.com> <1182784412.829377.265320@q75g2000hsh.googlegroups.com> <1182787082.740937.98590@n2g2000hse.googlegroups.com> <1182788059.409235.243380@m36g2000hse.googlegroups.com> Message-ID: <1182797406.221323.66270@p77g2000hsh.googlegroups.com> On Jun 25, 12:14 pm, kyoso... at gmail.com wrote: > > usersChosenPath = /usr/Path/to/Config > > > Kind of redundant, but I would think it would still work. Ok... How do I tell the program where the INI file lives? (What I want is to be able to ask the user Where do you want the datafile to live? [/usr/local/etc]: and save that answer somewhere, so future invocations of the program just *KNOW* the answer. I'm going to just have to write an 'install' program which just substitutes the default assignment for the new one in the code... almost a $PREFIX from ./configure or something like it. From bj_666 at gmx.net Mon Jun 4 04:19:17 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Mon, 04 Jun 2007 10:19:17 +0200 Subject: magic names in python References: <1180939436.862957.127810@p77g2000hsh.googlegroups.com> <1180943167.241208.37080@q75g2000hsh.googlegroups.com> Message-ID: In <1180943167.241208.37080 at q75g2000hsh.googlegroups.com>, per9000 wrote: > On Jun 4, 9:11 am, Marc 'BlackJack' Rintsch wrote: >> In <1180939436.862957.127... at p77g2000hsh.googlegroups.com>, per9000 wrote: >> > >> > [...] >> > >> > So another question emerges: >> > * is the use of magic names encouraged and/or part of good coding >> > practice. >> >> What do you mean by "use"? Implement them to override behavior? Yes, >> that's their purpose. Invent new magic names? No of course not, they are >> special for a reason: preventing name clashes with the user's names. >> > > [in my taste: UGLY] > I think of something like this: Perhaps I create a class that works > with a lot of files, and with inheritance new types of files can be > opened and worked with. > > When it is time for an instance of this class to die the files need to > be closed - perhaps "right now" and not when it is suitable for the > garbage collector. To facilitate this I create a number of functions > with names like close_*_file (f.x. close_indata_file, > close_outdata_file, close_error_file etc). (compare with [PyTest| > unittest] "test*" names.) > > If this class has been inherited to some other class that works with > more than one indata file perhaps we want to magically close all files > that are open by calling all function in this instance that has names > matching "close_*_file". > > I would consider this an ugly way of solving it. > > [in my taste: NICER] > I'd perhaps add file-handles to some list (and encourage inherited > classes to use this list) and close everything in the list. I would > not use magic wildcard names. > > So in other words: Do I need to go to yellow alert, and watch out for > magic names in non-core add-on packages to python? Or should I just > RTFM a little more? (I hate RTFM'ing.) Now I'm a little confused. What does this have to do with magic names? I thought you are talking about names that start and end with two underscores (`__magic__`)!? Ciao, Marc 'BlackJack' Rintsch From timr at probo.com Mon Jun 11 02:37:12 2007 From: timr at probo.com (Tim Roberts) Date: Mon, 11 Jun 2007 06:37:12 GMT Subject: updating db with csv References: <1181234515.502945.43770@q66g2000hsg.googlegroups.com> Message-ID: moishyyehuda at gmail.com wrote: > >#1 If any one familiar with godaddy hosting. They have apparently have >a hosing server i.e.(scripts, html files etc.), and a server for >databases. How can I import from my script, with a csv. if the db is >on a different server than the script server. What does this have to do with either Python or MySQL? When you connect to the database, you have to specify a hostname. As long as you provide the right one, it doesn't matter where your script runs. >#2 I would like to update and insert with the same csv file. Is there >a way to tell the database for some lines to update, and for some >lines to insert. Not in standard SQL. MySQL supports a REPLACE extension that does an UPDATE if the key already exists, and an INSERT if it does not. There is also an extension clause to the INSERT statement called "ON DUPLICATE KEY UPDATE xxx" that might do what you want. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From paul at subsignal.org Tue Jun 26 11:22:20 2007 From: paul at subsignal.org (paul) Date: Tue, 26 Jun 2007 17:22:20 +0200 Subject: PEP 3107 and stronger typing (note: probably a newbie question) In-Reply-To: <467a22d0$0$28538$426a74cc@news.free.fr> References: <1182369568.941307.316260@p77g2000hsh.googlegroups.com> <467a22d0$0$28538$426a74cc@news.free.fr> Message-ID: Bruno Desthuilliers schrieb: > Stephen R Laniel a ?crit : >> On Wed, Jun 20, 2007 at 09:41:09PM +0100, Michael Hoffman wrote: >>> If you asked Java programmers why you couldn't turn *off* Java's static >>> type checking if you wanted to, you'd probably get a similar response. >> Perhaps it would help for me to explain what I'd like. >> >> Under both Perl and Python, I've found myself >> having/wanting to write things like so: >> >> def my_func( int_arg, str_arg ): >> try: >> int_arg = int( int_arg ) >> str_arg = str( str_arg ) >> except ValueError: >> sys.stderr.write( "Args are not of the right type\n" ) >> sys.exit(1) >> > > Just a question : what will happen if you get rid of the try/except > block ?-) > The error will remain unnoticed and the argument might survive another few function calls but eventually fails deep down somewhere with: TypeError: cannot concatenate 'str' and 'list' objects then you have to examine the traceback and hope the real error is visible somewhere (an argument not conforming to the specification of the function prototype, or the lack thereof). cheers Paul From jeff at jmcneil.net Mon Jun 18 16:57:02 2007 From: jeff at jmcneil.net (Jeff McNeil) Date: Mon, 18 Jun 2007 16:57:02 -0400 Subject: avoid script running twice In-Reply-To: <9afea2ac0706181248l6bdd1606x2a3916609f6d4c14@mail.gmail.com> References: <4676AB35.7060500@chamonix.reportlab.co.uk> <9afea2ac0706181248l6bdd1606x2a3916609f6d4c14@mail.gmail.com> Message-ID: <82d28c40706181357h387a72y28108b57bc163a78@mail.gmail.com> I've got a rather large log processing job here that has the same requirement. I process and sort Apache logs from an 8-way cluster. I sort and calculate statistics in 15-minute batch jobs. Only one copy should run at once. I open a file and lock it via something like this: import fcntl fhandle = file("ourlockfile.txt", "w") try: fcntl.lockf(fhandle.fileno(), fcntl.LOCK_EX|fcntl.LOCK_NB) except IOError, e: if e.errno == errno.EAGAIN: print >>sys.stderr, "exiting, another copy currently running" else: raise I've got it wrapped in a 'FileBasedLock' class that quacks like Lock objects in the threading module. If the system bombs and reboots, the locks are cleared. If the first process dies via 'kill -XX', the locks it owns are released. Of course, external influences can screw it all up, but that's not so much a concern in our environment. While I have no idea how portable this is, it works great for what I'm doing on RHES 5. -Jeff On 6/18/07, Tim Williams wrote: > On 18/06/07, Nick Craig-Wood wrote: > > Tim Williams wrote: > > > You can also do this by holding a file open in write mode until the > > > script has finished. > > > > > > try: > > > open('lock.txt','w') > > > my_script() > > > except: > > > #print script is already running > > > > That only works under windows > > > > >>> f=open('lock.txt','w') > > >>> g=open('lock.txt','w') > > >>> f.write('hi') > > >>> g.write('ho') > > >>> f.close() > > >>> g.close() > > >>> open('lock.txt').read() > > 'ho' > > >>> > > > > The best cross platform way to create a lock is creating a directory. > > It is atomic on both windows and linux anyway. > > > > try: > > os.mkdir("lock") > > except OSError: > > print "locked!" > > else: > > try: > > do_stuff() > > finally: > > os.rmdir("lock") > > > > (untested) > > > > Being a windows-only person, I didn't know that :) > > Actually I think I did, this thread has happened before - a few months ago :) > > I would be worried with the directory-exists option for the same > reason I don't use the file-exists method currently. It is possible > for the directory to exist when the script isn't running, thus > preventing the script from running again until someone notices. > > On Windows the open-a-file-for-writing method works well, but as *nix > doesn't work the same way then maybe the socket solution is the best > cross-platform option. The socket can't exist when the script isn't > running, and if you try and create a duplicate socket you catch the > exception and exit. > > IMHO of course. > > :) > -- > http://mail.python.org/mailman/listinfo/python-list > From __peter__ at web.de Tue Jun 12 06:42:48 2007 From: __peter__ at web.de (Peter Otten) Date: Tue, 12 Jun 2007 12:42:48 +0200 Subject: Floating Number format problem References: <1181632259.217684.144180@d30g2000prg.googlegroups.com> <1181632572.643572.154690@n15g2000prd.googlegroups.com> <1181637985.191649.280250@x35g2000prf.googlegroups.com> <466e6fbc$0$6400$9b4e6d93@newsspool2.arcor-online.net> Message-ID: Marc Christiansen wrote: > Gabriel Genellina wrote: >> En Tue, 12 Jun 2007 05:46:25 -0300, escribi?: >> >>> On 6 12 , 3 16 , ici wrote: >>>> On Jun 12, 10:10 am, wrote: >>>> >>>> > How could I format the float number like this: (keep 2 digit >>>> > precision) >>>> > 1.002 => 1 >>>> > 1.12 => 1.12 >>>> >>> print "%.02f" % (2324.012) >>>> 2324.01 > Or: > > def my_other_formatter_ommitting_trailing_zeroes(value): > result = '%.2f' % value > return result.rstrip('0.') Make that result.rstrip("0").rstrip("."), or it may fail: >>> ("%.2f" % 100.0).rstrip(".0") '1' # wrong >>> ("%.2f" % 100.0).rstrip("0").rstrip(".") '100' Peter From f.guerrieri at gmail.com Mon Jun 11 11:14:20 2007 From: f.guerrieri at gmail.com (Francesco Guerrieri) Date: Mon, 11 Jun 2007 17:14:20 +0200 Subject: with as a reserved word In-Reply-To: <1181574196.682123.291010@a26g2000pre.googlegroups.com> References: <1181574196.682123.291010@a26g2000pre.googlegroups.com> Message-ID: <79b79e730706110814y572168c4v7b58cc014f05b6a4@mail.gmail.com> Within gnuplot you can shorten "with" to "w", don't know if it can work inside a call to Gnuplot.Data().... francesco On 6/11/07, BBands wrote: > I gather that 'with' is on its way to becoming a reserved word. Is > this something that will break? > > import Gnuplot > gp = Gnuplot.Gnuplot(debug=1) > data = Gnuplot.Data([1,2,3,4,3,2,3,4,3,2,1], with='linespoints') > gp.plot(data) > > >>> :3: Warning: 'with' will become a reserved keyword in Python 2.6 > > http://www.gnuplot.info/ > http://gnuplot-py.sourceforge.net/ > > This was run by PyScripter 1.8.7.1 with Python 2.5. > > jab > > -- > http://mail.python.org/mailman/listinfo/python-list > -- "Voil?! In view, a humble vaudevillian veteran, cast vicariously as both victim and villain by the vicissitudes of fate. This visage, no mere veneer of vanity, is a vestige of the vox populi, now vacant, vanished. However, this valorous visitation of a bygone vexation stands vivified, and has vowed to vanquish these venal and virulent vermin vanguarding vice and vouchsafing the violently vicious and voracious violation of volition. The only verdict is vengeance; a vendetta held as a votive, not in vain, for the value and veracity of such shall one day vindicate the vigilant and the virtuous. Verily, this vichyssoise of verbiage veers most verbose vis-?-vis an introduction, so let me simply add that it's my very good honor to meet you and you may call me V." -- V's introduction to Evey From deets at nospam.web.de Wed Jun 20 18:09:52 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 21 Jun 2007 00:09:52 +0200 Subject: PEP 3107 and stronger typing (note: probably a newbie question) In-Reply-To: References: <1182369568.941307.316260@p77g2000hsh.googlegroups.com> Message-ID: <5dtmtnF36t3pfU1@mid.uni-berlin.de> > > Of course I understand the virtue of writing code with good > doctests, etc. But my question is why we can't get some more > static typing as well. Given the tools that'll be in Python > 3.0, that doesn't seem unreasonable to ask. That is exactly the problem - there is no "some more" static typing. There is static typing - or not. You can't have it "just a bit". You can have type annotations to create guarding statements and then allow better optimized code below that - if everything is "safe". But static analysis that will allow for compiletime typing error checks will need _all_ code to be statically typed. And still not catch all runtime errors, which is basically an instance of the halting problem. The somewhat grumpy response you might have gotten is simply because the whole subject has been discussed about a bazillion times - but never ever somebody _created_ something that would work. Just asking for it with vague ideas how that would create a better world. Diez From joostkremers at yahoo.com Mon Jun 25 18:01:44 2007 From: joostkremers at yahoo.com (Joost Kremers) Date: 25 Jun 2007 22:01:44 GMT Subject: The Modernization of Emacs: terminology buffer and keybinding References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182453375.531950.141460@m36g2000hse.googlegroups.com> <1182456618.763414.219080@g4g2000hsf.googlegroups.com> <5ear80F36ga72U3@mid.individual.net> Message-ID: [Followup-To: header set to comp.emacs] blmblm myrealbox.com wrote: > Eclipse has something that generates "import" statements with > a few keystrokes, and for me that's almost in the "killer app > [feature]" class. (Why do I strongly suspect that with the > right plug-ins emacs can do this too? :-) because emacs exposes its lisp system to the user, allowing one to add basically any functionality one can come up with? ;-) -- Joost Kremers joostkremers at yahoo.com Selbst in die Unterwelt dringt durch Spalten Licht EN:SiS(9) From kyosohma at gmail.com Tue Jun 26 13:08:33 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Tue, 26 Jun 2007 10:08:33 -0700 Subject: popen and a long running process in a wx.python application In-Reply-To: <1182870983.001851.156960@q75g2000hsh.googlegroups.com> References: <1182870983.001851.156960@q75g2000hsh.googlegroups.com> Message-ID: <1182877713.920580.166800@g4g2000hsf.googlegroups.com> On Jun 26, 10:16 am, Doru Moisa wrote: > Hello, > > How can I capture the output of a long runnning process which I open > with popen() ? > I tried reading line by line, char by char, but the result always > comes when the process finishes. > (I am trying to make a wx.python program that opens some "make ..." > with popen). How can I receive the output of the program immediatly, > so that I can show a progressbar in my application ? > I always get the program's output after it finished executing. > Is this the right place, or should I post this to wx.python ? > > Thank you in advance. When talking about anything advanced with wxPython, you usually want to submit it to the wxPython user's group. Lots of advanced users (including the author of wxPython) answer questions there. I would recommend looking at the following link as this will probably be one of the first suggestions: http://wiki.wxpython.org/index.cgi/LongRunningTasks?highlight=%28task%29%7C%28longrunning%29 wxPython mailing list: http://www.wxpython.org/maillist.php I used a variation of one of the threading example in the LongRunningTasks page to send output to a text widget, through stdout redirection. Good luck! Mike From andre.roberge at gmail.com Mon Jun 11 19:10:21 2007 From: andre.roberge at gmail.com (=?iso-8859-1?B?QW5kcuk=?=) Date: Mon, 11 Jun 2007 23:10:21 -0000 Subject: SimplePrograms challenge In-Reply-To: References: Message-ID: <1181603421.476263.102740@m36g2000hse.googlegroups.com> On Jun 11, 6:56 pm, Steve Howell wrote: > Hi, I'm offering a challenge to extend the following > page by one good example: > > http://wiki.python.org/moin/SimplePrograms > > Right now the page starts off with 15 examples that > cover lots of ground in Python, but they're still > scratching the surface. (There are also two Eight > Queens implementations, but I'm looking to fill the > gap in lines-of-code, and they're a little long now.) > > I'm looking for a good 16-line code example with the > following qualities: > > 1) It introduces some important Python concept that > the first 15 programs don't cover. > > 2) It's not too esoteric. Python newbies are the > audience (but you can assume they're not new to > programming in general). > > 3) It runs on Python 2.4. > > 4) It doesn't just demonstrate a concept; it solves > a problem at face value. (It can solve a whimsical > problem, like counting rabbits, but the program itself > should be "complete" and "suitably simple" for the > problem at hand.) > > 5) You're willing to have your code reviewed by the > masses. > > 6) No major departures from PEP 8. > > Any takers? Ok, doctest-based version of the Unit test example added; so much more Pythonic ;-) Andr? P.S. Congrats for starting this! > > -- Steve > > ____________________________________________________________________________________ > Looking for a deal? Find great prices on flights and hotels with Yahoo! FareChase.http://farechase.yahoo.com/ From gagsl-py2 at yahoo.com.ar Sun Jun 10 19:32:44 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 10 Jun 2007 20:32:44 -0300 Subject: Dynamic subclassing ? References: <1178976888.443891.116090@y80g2000hsf.googlegroups.com> <1181510172.627390@smirk> Message-ID: En Sun, 10 Jun 2007 18:16:12 -0300, James T. Dennis escribi?: > When I try something like this I run into a little problem: > > class Foo: > def foo(self): > return "foo" > class Bar: > def bar(self): > return "bar" > > f = Foo() > f.__dict__.update(Bar.__dict__) > > ... the problem is that while f now has a "bar" method it doesn't > work quite like a normal instance method: > > >>> f.bar() > Traceback (most recent call last): > File "", line 1, in ? > TypeError: bar() takes exactly 1 argument (0 given) > >>> > > ... though I can get by with f.bar(f) Bar.__dict__ contains *unbound* methods - that is, methods not linked to any particular instance. If you copy them directly into f.__dict__ you lose the "magic" that binds methods to instances. You could store a bound method into the instance but it's not a good idea (there are cyclic references). I think the easiest way is to define a dynamic class (as the subject on this old thread suggests): py> f = Foo() py> Foo2 = type("Foo2", (Foo,Bar), {}) py> f.__class__ = Foo2 py> f.bar() 'bar' The code above changes the object class once it was created, but you don't have to. Also, you don't have to use a different class name (altough it may be confusing...): py> f = type("Foo", (Foo,Bar), {})() py> f.bar() 'bar' > This "new" module seems to be the key to it all; It's almost useless now that types are callable. > but the only docs I have for that say: > >>>> help(new) > Help on module new: > [...] > MODULE DOCS > http://www.python.org/doc/current/lib/module-new.html Did you follow the above link? -- Gabriel Genellina From steve at REMOVE.THIS.cybersource.com.au Sat Jun 23 14:36:12 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sun, 24 Jun 2007 04:36:12 +1000 Subject: Python's "only one way to do it" philosophy isn't good? References: <1181368143.874341.273140@r19g2000prf.googlegroups.com> <7x3b0nmkk6.fsf@ruckus.brouhaha.com> Message-ID: On Sat, 23 Jun 2007 12:39:51 -0400, Douglas Alan wrote: > One of the things that annoys me when coding in Python (and this is a > flaw that even lowly Perl has a good solution for), is that if you do > something like > > longVarableName = foo(longVariableName) > > You end up with a bug that can be very hard to track down. So one use > for macros would be so that I can define "let" and "set" statements so > that I might code like this: > > let longVariableName = 0 > set longVarableName = foo(longVariableName) > > Then if longVarableName didn't already exist, an error would be > raised, rather than a new variable being automatically created for me. So "let" is the initial declaration, and "set" modifies the existing variable? What happens is you declare a variable twice? let longVariableName = 0 let longVariableName = foo(longVariableName) # oops I meant set How long did it take you to write the macros, and use them, compared to running Pylint or Pychecker or equivalent? But if you really want declarations, you can have them. >>> import variables >>> variables.declare(x=1, y=2.5, z=[1, 2, 4]) >>> variables.x = None >>> variables.w = 0 Traceback (most recent call last): File "", line 1, in File "variables.py", line 15, in __setattr__ raise self.DeclarationError("Variable '%s' not declared" % name) variables.DeclarationError: Variable 'w' not declared The variables module isn't part of the standard library. Here's the code for it: import sys class _variable: class DeclarationError(TypeError): pass def __setattr__(self, name, value): if self.__dict__.has_key(name): self.__dict__[name] = value else: raise self.DeclarationError("Variable '%s' not declared" % name) self.__dict__[name]=value def declare(self, **args): for name, value in args.items(): self.__dict__[name] = value sys.modules[__name__]=_variable() It took me less than five minutes starting from Alex Martelli's code here http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65207 No special syntax or macros or magic powers were needed. I could extend the variables functionality to (say) make sure the same variable isn't declared twice, or be case-insensitive, or have multiple namespaces, none of which need special syntax. -- Steven. From newsgroups at debain.org Wed Jun 6 11:10:34 2007 From: newsgroups at debain.org (Samuel) Date: Wed, 6 Jun 2007 15:10:34 +0000 (UTC) Subject: which "GUI module" you suggest me to use? References: <136bvigp2ps99bc@corp.supernews.com> Message-ID: On Wed, 06 Jun 2007 09:45:48 -0500, Chris Mellon wrote: > On 6/6/07, Samuel wrote: > In the general case, wxWidgets wraps (not emulates) Gtk. I don't believe > that there are any common controls left which are still emulated (maybe > the list control? I'm not sure - I don't follow the bleeding edge of wx > anymore). See my other response. Also, the fact that Gtk widgets are used does not necessarily mean that the behavior is the same - you can still do all kinds of weird stuff by hooking into the callbacks. Some of the differences to Gtk were probably introduced to wx in order to have more consistent behavior over different platforms. > wxPython (as opposed to wxWidgets, the C++ core) has a sizeable library > of custom controls as part of its standard lib. Most of these are > owner-drawn for various reasons and often won't appear native (Andrea > Gavin, probably the most prolific custom control author, works primarily > on Windows). This affects the C++ core as well. aMule (which is written in CPP) is one particular complex example that exposes many of those problems when used on Linux. >> > PyGTK works under Linux and Windows, but doens't use native widgets >> > under Windows, so it won't look like a "normal" windows app. >> >> Gtk on Win32 can be themed to looked like Windows, AFAIK the Win32 >> installer does this by default since a couple of months. >> >> > That stretches the truth rather significantly. While the win32 theme > does use the windows theme apis for drawing, it still has slightly > different colors (especially window backgrounds and menus), and (more > importantly) vastly and notably different behavior. Well, I have only tried Gaim on windows and could not tell the difference. But then, I am not a regular Windows user. > Shortcuts are > different, renderings are different, the Gtk drawing model is used > instead of the windows one (leads to quite jarring repainting > differences), different fonts, etc, etc. It looks okay in a screenshot > but is clearly non-native and foreign in use. Sounds bad. It also sounds much like what I experienced with wx on Linux. I guess there is no perfect solution, you always have to target one primary platform. (Well, there's SWT, but the Gtk emulation too has it's drawbacks...) -Samuel From stargaming at gmail.com Fri Jun 22 11:45:51 2007 From: stargaming at gmail.com (Stargaming) Date: Fri, 22 Jun 2007 17:45:51 +0200 Subject: try/except with multiple files In-Reply-To: <1182453111.391374.279490@e9g2000prf.googlegroups.com> References: <1182452425.793305.193370@u2g2000hsc.googlegroups.com> <1182453111.391374.279490@e9g2000prf.googlegroups.com> Message-ID: <467beeb4$0$3039$9b622d9e@news.freenet.de> Matimus wrote: > It depends, what are you going to do if there is an exception? If you > are just going to exit the program, then that works fine. If you are > going to just skip that file, then the above wont work. If you are > going to return to some other state in your program, but abort the > file opening, you might want to close any files that were opened. The > closing can be taken care if in the except block, but you will have to > know which ones opened successfully. > > In general I would do something like this for multiple files: > > [code] > filenames = ["fname1","fname2","fname3"] > for fn in filenames: > try: > f = open(fn) > except IOError: > # handle exception > #do something with f > [/code] > > But, that might not work for you if the files aren't homogeneous (each > have similar contents). If the files have distinctly different > purposes, I would just wrap them each in their own try/except block. > > I rambled a bit there, but I hope it helps. > > Matt > Heh, reminded me of http://worsethanfailure.com/Articles/Code-Reuse.aspx at the first glance. SCNR. To add something on-topic, I'd just stick with the "one try for all files" option if your need is really "Try to open all files, if *at least one* of them fails, recover/abort/foobar/...". From noah at noah.org Thu Jun 7 20:59:40 2007 From: noah at noah.org (Noah) Date: Thu, 07 Jun 2007 17:59:40 -0700 Subject: Bug/Weak Implementation? popen* routines can't handle simultaneous read/write? In-Reply-To: <1181232071.928835.301710@w5g2000hsg.googlegroups.com> References: <1181232071.928835.301710@w5g2000hsg.googlegroups.com> Message-ID: <1181264380.441881.38570@i13g2000prf.googlegroups.com> On Jun 7, 9:01 am, dmoore wrote: popen and friends will never do what you want it to do. Down that path lies bitter disappointment. You need pseduo-ttys and non-blocking IO. I don't know how to do this on Windows, but I know it's possible. Cygwin does it. > Anybody have any thoughts on this? Do I have my story straight? (the > popen variants can't handle this case and there are no other > alternatives in the standard python distro) Is there some place I can > submit this as a feature request? (Python dev?) Try Pexpect http://pexpect.sourceforge.net/ It's been around for a long time and is quite complete and stable. The catch is that it's UNIX-only. If you want to tease out the magic code from wxProcess that does non-blocking reads on win32 then I'd be happy to integrate that into the current development branch of Pexpect. If someone can provide a pure Python drop-in replacement for the read_nonblocking() function I use for UNIX systems then it would be easy. I have a whole test framework that I can run it through to see if it performs the same as the UNIX flavor. I'm sure this is feasible without any C extensions -- it might require some ctypes hacking. I know Windows has pretty decent async IO, but I don't know what they have as an equivalent for a pty. Maybe it isn't necessary. A pty is only necessary on UNIX because the standard c library, stdio, behaves differently when it's talking to a plain pipe versus a terminal -- it switches buffering between block and line oriented buffer. You don't want block buffering on interactive applications. This is why popen eventually breaks down. No, there is no way to select this behavior from the calling side... unless you can trick it into dynamically linking to your specially hacked libc. But that's getting ahead because that's what happens on UNIX -- it might be a non-issue on Windows. The read_nonblocking() function I use has an interface like this:

          def read_nonblocking (self, size = 1, timeout = -1):
      
              """This reads at most size characters from the child
      application. It
              includes a timeout. If the read does not complete within the
      timeout
              period then a TIMEOUT exception is raised. If the end of file
      is read
              then an EOF exception will be raised. If a log file was set
      using
              setlog() then all data will also be written to the log file.
      
              If timeout is None then the read may block indefinitely. If
      timeout is -1
              then the self.timeout value is used. If timeout is 0 then the
      child is
              polled and if there was no data immediately ready then this
      will raise
              a TIMEOUT exception.
      
              The timeout refers only to the amount of time to read at least
      one
              character. This is not effected by the 'size' parameter, so if
      you call
              read_nonblocking(size=100, timeout=30) and only one character
      is
              available right away then one character will be returned
      immediately.
              It will not wait for 30 seconds for another 99 characters to
      come in.
      
              This is a wrapper around os.read(). It uses select.select() to
              implement the timeout. """
      
      Yours, Noah From chris.atlee at gmail.com Thu Jun 14 08:46:18 2007 From: chris.atlee at gmail.com (Chris AtLee) Date: Thu, 14 Jun 2007 12:46:18 -0000 Subject: Help with PAM and ctypes In-Reply-To: <4Djbi.21568$nx3.19208@edtnps89> References: <1181219321.236803.111180@g4g2000hsf.googlegroups.com> <4Djbi.21568$nx3.19208@edtnps89> Message-ID: <1181825178.653648.223160@i13g2000prf.googlegroups.com> On Jun 11, 6:01 pm, Lenard Lindstrom wrote: [snip snip snip] > > if __name__ == "__main__": > > import getpass, os, sys > > @conv_func > > def my_conv(nMessages, messages, pResponse, appData): > > # Create an array of nMessages response objects > > # Does r get GC'ed after we're all done? > > r = (pam_response * nMessages)() > > The memory allocated to r is garbage collected immediately after my_conv > returns. You need to allocate it explicitly using C's calloc or such. > This assumes pam_start will free the memory for you. > > addr = calloc(sizeof(pam_response), nMessages) > > addr is the memory address as a Python integer. > > > pResponse.contents = cast(r, POINTER(pam_response)) > > pResponse.contents changes the actual value of pResponse, a value on the > stack. You want to change the value of the pointer pResponse points to: > > pResponse[0] = cast(addr, POINTER(pam_response)) > > The cast creates a POINTER(pam_reponse) instance with value addr. Ahhh, thank you! I never understood how ctypes' pointer.contents related to C pointers. So, the following are equivalent? int v = 42; v = 42 int *p = 0; p = cast(0, POINTER(c_int)) p = &v; p.contents = v *p = 123; p[0] = 123 Using "pResponse[0] = cast(...)" got me part of the way to fixing my problem. PAM started either crashing or saying authentication had failed. The crash was in free(), and some digging around revealed that PAM tries to free the response sent by the application, which makes sense. My initial attempt to fix this involved wrapping strdup to allocate a new copy of a string to send back to PAM. Here's how I wrapped it: strdup = libc.strdup strdup.argstypes = [c_char_p] strdup.restype = c_char_p This still crashed in free(). I took a look at some of the ctypes regression tests and something made me try this: strdup = libc.strdup strdup.argstypes = [c_char_p] strdup.restype = POINTER(c_char) # NOT c_char_p !!!! This works like a charm. Not sure why though...Does ctypes do something special with c_char_p return types? It seems as if Python was freeing the result of strdup() when the string was GC'ed, and then PAM would fail when trying to free the same memory. My working code is pasted below. Thanks, Chris from ctypes import * libpam = CDLL("libpam.so") libc = CDLL("libc.so.6") calloc = libc.calloc calloc.restype = c_void_p calloc.argtypes = [c_uint, c_uint] strdup = libc.strdup strdup.argstypes = [c_char_p] strdup.restype = POINTER(c_char) # NOT c_char_p !!!! # Various constants PAM_PROMPT_ECHO_OFF = 1 PAM_PROMPT_ECHO_ON = 2 PAM_ERROR_MSG = 3 PAM_TEXT_INFO = 4 class pam_handle(Structure): _fields_ = [ ("handle", c_void_p) ] def __init__(self): self.handle = 0 class pam_message(Structure): _fields_ = [ ("msg_style", c_int), ("msg", c_char_p), ] def __repr__(self): return "" % (self.msg_style, self.msg) class pam_response(Structure): _fields_ = [ ("resp", c_char_p), ("resp_retcode", c_int), ] def __repr__(self): return "" % (self.resp_retcode, self.resp) conv_func = CFUNCTYPE(c_int, c_int, POINTER(POINTER(pam_message)), POINTER(POINTER(pam_response)), c_void_p) class pam_conv(Structure): _fields_ = [ ("conv", conv_func), ("appdata_ptr", c_void_p) ] pam_start = libpam.pam_start pam_start.restype = c_int pam_start.argtypes = [c_char_p, c_char_p, POINTER(pam_conv), POINTER(pam_handle)] pam_authenticate = libpam.pam_authenticate pam_authenticate.restype = c_int pam_authenticate.argtypes = [pam_handle, c_int] if __name__ == "__main__": import getpass, os, sys @conv_func def my_conv(nMessages, messages, pResponse, appData): # Create an array of nMessages response objects addr = calloc(nMessages, sizeof(pam_response)) pResponse[0] = cast(addr, POINTER(pam_response)) for i in range(nMessages): if messages[i].contents.msg_style == PAM_PROMPT_ECHO_OFF: p = strdup(getpass.getpass(messages[i].contents.msg)) pResponse.contents[i].resp = cast(p, c_char_p) pResponse.contents[i].resp_retcode = 0 else: print "Unknown message type" return 0 handle = pam_handle() c = pam_conv(my_conv, 0) retval = pam_start("login", getpass.getuser(), pointer(c), pointer(handle)) if retval != 0: print "Couldn't start pam session" sys.exit(-1) retval = pam_authenticate(handle, 0) if retval == 21: print "Authentication information cannot be recovered" sys.exit(-1) elif retval == 7: print "Authentication failure" elif retval == 0: print "Ok!" else: print retval From steven.bethard at gmail.com Tue Jun 19 15:34:50 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 19 Jun 2007 13:34:50 -0600 Subject: Reference current module? In-Reply-To: <4678201b$0$16340$88260bb3@free.teranews.com> References: <4678201b$0$16340$88260bb3@free.teranews.com> Message-ID: Tobiah wrote: > Can I do: > > getattr(current_module, 'foo') > > where 'current_module' is a handle the the one > that the code is in? Just like > > getattr(self, 'foo') > > in a class, but for the current module instead? You can try __import__() with __name__:: >>> foo = 42 >>> mod = __import__(__name__) >>> getattr(mod, 'foo') 42 STeVe From fff at sss.com Thu Jun 14 08:27:03 2007 From: fff at sss.com (desktop) Date: Thu, 14 Jun 2007 14:27:03 +0200 Subject: IndentationError: unexpected indent Message-ID: I have this class: class case(blop.case): def __init__(self, n, a, b): blop.case.__init__(self) print 'Monty Python's Flying Circus has a ' within it...' ... ... But I get an error when I run the .py script from shell saying: print 'Monty Python's Flying Circus has a ' within it...' ^ IndentationError: unexpected indent I have tried to indent the print statement 8 blanks but that does not help. Any hints? From mkb at incubus.de Wed Jun 27 12:05:38 2007 From: mkb at incubus.de (Matthias Buelow) Date: Wed, 27 Jun 2007 18:05:38 +0200 Subject: The Modernization of Emacs: terminology buffer and keybinding In-Reply-To: References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182272495.990807.99110@a26g2000pre.googlegroups.com> <87tzt3ihev.fsf@kobe.laptop> <1182370216.961241.6960@n60g2000hse.googlegroups.com> <85zm2ufjpb.fsf@lola.goethe.zz> <1182372592.803332.288260@u2g2000hsc.googlegroups.com> <1182373919.262388.100740@c77g2000hse.googlegroups.com> <85r6o6fhkb.fsf@lola.goethe.zz> <1182375045.626510.188170@m36g2000hse.googlegroups.com> <1182546050.465987.115740@q19g2000prn.googlegroups.com> <871wg3k8c8.fsf@thalassa.lan.informatimago.com> <1182546979.295368.146110@q19g2000prn.googlegroups.com> <87wsxviqol.fsf@thalassa.lan.informatimago.com> <1182552172.406571.116390@i38g2000prf.googlegroups.com> Message-ID: <5efg6iF38nuukU1@mid.dfncis.de> Bjorn Borud wrote: > I was told by a lot of people I consider to be intelligent that this > book would change how I think about writing software. it didn't. I > didn't really know what to expect, but after reading it I did feel > that its importance was greatly exaggerated. I think it's basically a course book, for some CS courses at MIT that it was originally used with, and that's it. It's not superb but ok, as far as "lecture notes" go, a bit pretentious and a bit idiosyncratic, probably due to being targeted mainly at students visiting a particular course of lectures. I don't think it's supposed to be a general "how to learn good programming"-style book although I don't think you've wasted time reading it. F'up-to: c.l.lisp. From george.sakkis at gmail.com Sat Jun 2 14:03:52 2007 From: george.sakkis at gmail.com (George Sakkis) Date: Sat, 02 Jun 2007 18:03:52 -0000 Subject: Python rocks In-Reply-To: References: <4661700a$0$19261$da0feed9@news.zen.co.uk> Message-ID: <1180807432.351720.123860@p47g2000hsd.googlegroups.com> On Jun 2, 12:31 pm, Steve Howell wrote: > --- Mark Carter wrote: > > > Well, I know I'm preaching to the converted - but > > Python rocks. > > [...] > > A few questions from the choir: > > As a recent newcomer to the language, did you > encounter any traps or pitfalls while you were > learning? I had probably stumbled on many/most of the common pitfalls usually mentioned (e.g. http://www.ferg.org/projects/python_gotchas.html, http://zephyrfalcon.org/labs/python_pitfalls.html) while learning, but picked them up easily after the first or second time. Off the top of my head, two errors that keep coming back even years after are: - Comparing instances of (semantically) incomparable types (http:// www.ibm.com/developerworks/library/l-python-elegance-1.html). Thankfully this will be fixed in Py3k. - Strings being iterable; unfortunately this will stay in Py3K. > Also, could you single out anything in > particular about Python that started making you more > productive, or was it just the overall design? If I were to pick a single feature, this would be the triplet iterators-generators-itertools, not only for the productivity gains but perhaps even more for changing the way of thinking about programming, making Python worth learning [1]. But in general it's the overall design, making the right tradeoffs in most cases. George [1] "A language that doesn't affect the way you think about programming, is not worth knowing." - Alan Perlis From devicerandom at gmail.com Thu Jun 28 08:22:45 2007 From: devicerandom at gmail.com (massimo s.) Date: Thu, 28 Jun 2007 05:22:45 -0700 Subject: problem with hack using multiple inheritance for plugins In-Reply-To: <46839f4c$0$22380$426a74cc@news.free.fr> References: <1183026288.857294.91620@q69g2000hsb.googlegroups.com> <1183028051.940679.145680@q69g2000hsb.googlegroups.com> <46839f4c$0$22380$426a74cc@news.free.fr> Message-ID: <1183033365.183481.143310@n60g2000hse.googlegroups.com> On 28 Giu, 13:45, Bruno Desthuilliers wrote: > massimo s. a ?crit : > > >> At this point, it seems too much a deep object-oriented hell to be > >> able to dig it myself. Would you help me getting some cue on the > >> problem? > > > Update. Now I know that: > > - every sane Python class should return after > > type(self) > > Certainly not, unless you're using a pretty old Python version. > 'instance' type means old-style classes - the legacy Python object > model, replaced some years ago with a *much* better one ('new-style' > classes). IIRC, this (now dying) legacy object model should disappear > with Py3K. Oops. That's probably the problem. I always followed the class syntax found in Section 9 of the tutorial, and Python code I've seen uses the same syntax. Where can I find the syntax of new-style classes? > > - when disabling the multiple-inheritance-hack, the situation comes > > back to normal > > I may be wrong here - I don't use old-style classes, and I avoid > multiple inheritance whenever I can - but I think this may has to do > with mixing old-style and new-style classes. Probably it is. > > wrt/ this snippet: I'll try it ASAP. About logging the error, yes, I figured it out how to do it some time ago but didn't have time (sigh). Thanks, m. From s.mientki at id.umcn.nl Wed Jun 6 06:09:55 2007 From: s.mientki at id.umcn.nl (stef) Date: Wed, 06 Jun 2007 12:09:55 +0200 Subject: PATH or PYTHONPATH under Windows ??? In-Reply-To: References: <90155$4665db45$d443bb3a$16812@news.speedlinq.nl> Message-ID: Thorsten Kampe wrote: > * Stef Mientki (Tue, 05 Jun 2007 23:57:15 +0200) > >> after cleaning up a PC, >> > > Uou purposely deleted things you had no clue about?! > Yes, but you should have seen what a "professional" package like LabView / LabWindows, all had installed on my PC ;-) > >> Python can't find any libraries anymore. >> But happily I've still one PC, where Python is running perfect. >> Now I always read about the environment variable "PYTHONPATH". >> But on neither PC there exists a "PYTHONPATH". >> > > That's totally normal. > but why is everybody alwasy talking about the "environment variable PYTHONPATH" ?? > > >> On the PC that works ok, >> there is the standard "PATH" environment variable, >> and indeed there are all the Python Library references. >> > > That's not okay. At the best it's completely useless. > ??? > > >> Please enlighten me. >> > > Use common sense: reinstalling Python is likely the fastest way. > Yes I know, But the point is, I want to promote Python to colleagues, show them that it's equally well suited as MatLab, installation of Scipy + wxPython + a few other packages is terrible difficult. So I can not even past the front door ;-) Therefor I'm trying to understand the search path problem, to make a "1-button" install (through Inno Setup), and yesterday I was forced to try that 1-button install myself :-( cheers, Stef Mientki > Thorsten > From martin at v.loewis.de Sun Jun 17 03:48:30 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 17 Jun 2007 09:48:30 +0200 Subject: Comparing UTF-8 into USC-2 and vice versa (newbie :-) ) In-Reply-To: <1182064058.292960.319970@p77g2000hsh.googlegroups.com> References: <1182064058.292960.319970@p77g2000hsh.googlegroups.com> Message-ID: <4674E74E.1080406@v.loewis.de> > I recently rewrote a .net application in python. > The application is basically gets streams via TCP socket and handle > operations against an existing database. > The Database is SQLite3 (Encoded as UTF-8). > The Networks streams are encoded as UCS-2. > > Since in UCS-2, 'A' = '0041' and when I check with the built-in > functions I get for unicode("A", "utf-8") = u'A' = u'\u0041'. I > wonder what is the difference, and how can I safely encode/decode > UCS-2 streams and match them with the UTF-8 representation In unicode("A", "utf-8"), the "utf-8" parameter does *not* mean that the output is in UTF-8, but the *input*. So "A" = '41' != '0041'. In UCS-2, the A consumes two bytes; in UTF-8, it consumes only one byte. For different letters, that's different: For example, for u'\xf6', the UCS-2 representation (big-endian) is '00F6', for UTF-8, it is 'C3B6'. For u'\u20AC', the UCS-2 is '20AC', the UTF-8 is 'E282AC' (i.e. three bytes). You should use Unicode objects in your program always, and encode to or from UCS-2 or UTF-8 only when interfacing with the network/database. HTH, Martin From Darren.Weber at radiology.ucsf.edu Wed Jun 13 20:28:19 2007 From: Darren.Weber at radiology.ucsf.edu (DarrenWeber) Date: Thu, 14 Jun 2007 00:28:19 -0000 Subject: native python matrix class (2D list), without inverse Message-ID: <1181780899.613685.91500@x35g2000prf.googlegroups.com> # Copyright (C) 2007 Darren Lee Weber # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA # 02111-1307, USA. __version__ = "$Revision: 1.9 $" # $Date: 2007/06/14 00:24:57 $ class Matrix: """ Create and manipulate a matrix object Matrix(data, dim) data = list of lists (currently only 2D) dim=(row,col) tuple of int For example, #data = [[0.0] * c for i in xrange(r)] data = [[0.0,0.1],[1.0,1.1],[2.0,2.1]] rowN =len(data) colN =len(data[0]) m = Matrix(data) m = Matrix(data,dim=(rowN, colN)) d1 = [[0.0, 0.1], [1.0, 1.1], [2.0, 2.1]] # 3x2 matrix d2 = [[0.0, 0.1, 0.2], [1.0, 1.1, 1.2]] # 2x3 matrix m1 = Matrix(d1) m2 = Matrix(d2) #m3 = m1 + m2 # dimension error m3 = m1 + m2.transpose() m3 = m1 - m2.transpose() m3 = m1 * m2 # 3x3 m3 = m2 * m1 # 2x2 m1[2,:] m1[:,2] """ def __init__(self, data=None, dim=None): """ create a matrix instance. m = Matrix([data [, dim]]) is a 2D matrix comprised of a nested list of floats is a tuple of int values for the row and column size (r,c) eg: data = [[0.0,0.1],[1.0,1.1],[2.0,2.1]] dim = (3,2) # or (len(data),len(data[0])) """ if data != None: # check data for the cell types (ensure float)? self.data = data r = len(data) c = len(data[0]) # Are all the rows the same length? rowLenCheck = sum([len(data[i]) != c for i in range(r)]) if rowLenCheck > 0: raise ValueError else: self.dim = (r,c) if dim != None: if (dim[0] == r) and (dim[1] == c): self.dim = (r,c) else: # over-ride the dim input, do not reshape data! # print a warning? self.dim = (r,c) else: if dim != None: if len(dim) == 2: self.dim = tuple(dim) r = dim[0] c = dim[1] else: # maybe a new exception type? arg = ("len(dim) != 2: ", dim) raise ValueError, arg # BEGIN ALT ---------------------------------------- # Does this give unique memory for each element? # self.data = [[0.0] * c for i in xrange(r)] # It seems that the initialization does not generate # unique memory elements because all list elements # refer to the same number object (0.0), but # modification of any element creates a unique value, # without changing any other values, eg: ##>>> x = [[0.0] * 3 for i in xrange(2)] ##>>> id(x) # 3079625068L # >>> id(x[0][0]) # 136477300 # >>> id(x[0][1]) # 136477300 # >>> id(x[1][1]) # 136477300 # >>> x[0][0] = 1.0 # >>> x # [[1.0, 0.0, 0.0], [0.0, 0.0, 0.0]] # >>> # END ALT ---------------------------------------- # create a zero row vector, with unique memory for each element self.data = [[x * 0.0 for x in range(c)]] for i in range(1,r): self.data.append([x * 0.0 for x in range(c)]) else: self.data = [] self.dim = (0,0) #print self.__doc__ def __getitem__(self, i): """ matrix[r,c] returns values from matrix.data, eg: data = [[0.0,0.1],[1.0,1.1],[2.0,2.1]] m = Matrix(data) m[2,:] >> [2.0, 2.1000000000000001] """ r = i[0] c = i[1] #print "index: (%s, %s)" % (r,c) #print "value: ", self.data[r][c] return self.data[r][c] def reshape(self, newdim=None): 'reshape a matrix object: matrix.reshape(newdim)' print "something to implement later" pass def transpose(self): 'transpose a matrix: m2 = m1.transpose()' m = Matrix(dim=(self.dim[1],self.dim[0])) for r in range(self.dim[0]): for c in range(self.dim[1]): m.data[c][r] = self.data[r][c] return m def __add__(self, q): ''' matrix addition: m3 = matrix1 + matrix2 m3 = matrix1 + float m3 = matrix1 + int ''' if isinstance(q, Matrix): if self.dim != q.dim: arg = ("p.dim != q.dim", self.dim, q.dim) raise IndexError, arg else: # do the addition m = Matrix(dim=self.dim) for r in range(self.dim[0]): # rows of p and q m.data[r] = map(lambda x, y: x + y, self.data[r], q.data[r]) return m elif isinstance(q, float) or isinstance(q, int): # add a scalar value m = Matrix(dim=self.dim) for r in range(self.dim[0]): # rows m.data[r] = map(lambda x: x + q, self.data[r]) return m else: arg = ("q is not a matrix, float or int", q) raise TypeError, arg def __sub__(self, q): ''' matrix subtraction: m3 = matrix1 - matrix2 m3 = matrix1 - float m3 = matrix1 - int ''' if isinstance(q, Matrix): if self.dim != q.dim: arg = ("p.dim != q.dim", self.dim, q.dim) raise IndexError, arg else: # do the subtraction m = Matrix(dim=self.dim) for r in range(self.dim[0]): # rows of p and q m.data[r] = map(lambda x, y: x - y, self.data[r], q.data[r]) return m elif isinstance(q, float) or isinstance(q, int): # subtract a scalar value m = Matrix(dim=self.dim) for r in range(self.dim[0]): # rows m.data[r] = map(lambda x: x - q, self.data[r]) return m else: arg = ("q is not a matrix, float or int", q) raise TypeError, arg def __mul__(self, q): """ multiply two matrices: m = p * q # p.dim[1] == q.dim[0] multiply a matrix with a scalar: m = p * q # where q is a float or int value """ if isinstance(q, Matrix): if self.dim[1] != q.dim[0]: arg = ("p.dim[1] != q.dim[0]", self.dim[1], q.dim[0]) raise IndexError, arg else: # do the multiplication m = Matrix(dim=(self.dim[0], q.dim[1])) for r in range(self.dim[0]): # rows of p for c in range(q.dim[1]): # cols of q # get the dot product of p(r,:) with q(:,c) pRowVec = self.data[r] qColVec = [q.data[a][c] for a in xrange(q.dim[0])] m.data[r][c] = sum(map(lambda x, y: x * y, pRowVec, qColVec)) return m elif isinstance(q, float) or isinstance(q, int): # subtract a scalar value m = Matrix(dim=self.dim) for r in range(self.dim[0]): # rows m.data[r] = map(lambda x: x * q, self.data[r]) return m else: arg = ("q is not a matrix, float or int", q) raise TypeError, arg def __div__(self, q): """ Divide a matrix with a scalar, eg: m = p / q # where q is a float or int value This operator will not return a matrix inverse """ if isinstance(q, Matrix): # let's not do matrix divide in python, leave the inverse # to a c/c++ library arg = ("q is a matrix: will not calculate inverse", q) raise TypeError, arg elif isinstance(q, float) or isinstance(q, int): # divide a scalar value m = Matrix(dim=self.dim) for r in range(self.dim[0]): # rows m.data[r] = map(lambda x: x / q, self.data[r]) return m else: arg = ("q is not a matrix, float or int", q) raise TypeError, arg def __len__(self): return self.dim[0] * self.dim[1] def __str__(self): # print the matrix data s = "" for r in range(self.dim[0]): for c in range(self.dim[1]): s += "%f " % (self.data[r][c]) s += "\n" return s def printFormat(self, format): """ print the matrix data nicely formatted, eg: matrix.printFormat("%8.4f") """ for r in range(self.dim[0]): for c in range(self.dim[1]): print format % (self.data[r][c]), print def __repr__(self): # return something that will recreate the object return "Matrix(%s, %s)" % (self.data, self.dim) # -------------------------------------------------------------------------------- # Explore the functionality - should be unit testing testing = 0 if testing: d1 = [[0.0, 0.1], [1.0, 1.1], [2.0, 2.1]] # 3x2 matrix d2 = [[0.0, 0.1, 0.2], [1.0, 1.1, 1.2]] # 2x3 matrix m1 = Matrix(d1) m2 = Matrix(d2) #m3 = m1 + m2 # "dimension" error m3 = m1 + m2.transpose() m3 = m1 - m2.transpose() m3 = m1 * m2 # 3x3 m3 = m2 * m1 # 2x2 m3 += 10.0 m3 -= 10.0 m3 += 10 m3 -= 10 m3 /= 10.0 m3 *= 10.0 m3 /= 10 m3 *= 10 From 1960_j at operamail.com Sat Jun 23 19:29:25 2007 From: 1960_j at operamail.com (1960_j at operamail.com) Date: Sat, 23 Jun 2007 16:29:25 -0700 Subject: trouble installing numpy 1.0.2 and scipy.0.5.2 Message-ID: <1182641365.761718.20680@u2g2000hsc.googlegroups.com> I have tried to install numpy and scipy on python 5.2. Using gcc 2.95.3, lapack 3.1.1 and ATLAS 3.6.0. When installin numpy it seems to work but when I try to run test get error no test for numpy. When I try to Install scipy only get error. Any ideas on how to install would be appreciated. Thanks From nebulous99 at gmail.com Fri Jun 22 18:44:14 2007 From: nebulous99 at gmail.com (nebulous99 at gmail.com) Date: Fri, 22 Jun 2007 22:44:14 -0000 Subject: The Modernization of Emacs In-Reply-To: References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182370894.001918.36590@k79g2000hse.googlegroups.com> <1182372821.298343.316860@g4g2000hsf.googlegroups.com> <1182375321.067664.190780@o61g2000hsh.googlegroups.com> <86hcp1l6hb.fsf@lola.quinscape.zz> Message-ID: <1182552254.233679.180790@o11g2000prd.googlegroups.com> On Jun 21, 10:48 am, Lew wrote: > Bjorn Borud writes: > >> so if the context was system administration, I'd vote for vi as > >> well. if the context was programming I'd vote Emacs. > David Kastrup wrote: > > You know you can use something like > > C-x C-f /su::/etc/fstab RET > > (or /sudo::/etc/fstab) in order to edit files as root in a normal > > Emacs session? > > I've been using emacs for something like twenty years and never knew that before. > > I like the built-in therapist in emacs. I think both of Lew's sentences here speak volumes. One about the difficulty even supposed expert users can have with tasks and finding things out from the help system. (I take it unix has also still not caught up to the windows world in the concept of a "tip of the day"?) And both of them, though especially the latter, regarding what a feeping creature emacs is. I don't suppose there's also a kitchen sink in there somewhere? Or is that just nethack? PS you'll have to stop posting such a high volume here. I'm getting BS from Google Groups about posting limits being exceeded again. Apparently they've lowered it still further, from 25 in a 24 hour period to 12 or so in a 24 hour period. Fuckers. From richardjones at optushome.com.au Mon Jun 18 17:53:10 2007 From: richardjones at optushome.com.au (Richard Jones) Date: Tue, 19 Jun 2007 07:53:10 +1000 Subject: using Mac OS X CoreGraphics via ctypes References: <1181876264.097017.283110@n15g2000prd.googlegroups.com> <5deo7iF34h5s2U1@mid.uni-berlin.de> <1181909161.373930.134660@k79g2000hse.googlegroups.com> <5dn3qjF35ha5iU1@mid.uni-berlin.de> <1182172472.714403.8790@q69g2000hsb.googlegroups.com> Message-ID: <4676fec6$0$21518$afc38c87@news.optusnet.com.au> Daniel wrote: > Thanks Diez. I'll try that if I decide to keep going with ctypes. I > got a bit further but had some problems with memory management (i.e. > retaining and releasing object references). It seemed like Python/ > ctypes was accessing referenced objects after I had released them, > which caused segfaults. I would be unlikely that this is the case. Much more likely is that you've got some memory allocated by Python which is being passed on to a C library and is subsequently freed by Python before the C library is finished with it. Happens all the time. Just make sure you keep a reference in Python land to any objects you've handed over to C for the lifetime that the C library is likely to use it. Having said that, it doesn't look like that's what's happening with your CGPDFDocumentRelease call, though perhaps you needed to clean up the page or rect that you obtained in the loop? "k" constants defined as strings are 32-bit numbers derived from 4 character strings. You'll need to convert those strings to the correct number. Once you've done that I believe your CGColorSpaceCreateWithName call will work. Richard From felciano at gmail.com Fri Jun 22 14:04:53 2007 From: felciano at gmail.com (felciano) Date: Fri, 22 Jun 2007 11:04:53 -0700 Subject: What was that web interaction library called again? In-Reply-To: <1182521949.813529.75140@w5g2000hsg.googlegroups.com> References: <1182521949.813529.75140@w5g2000hsg.googlegroups.com> Message-ID: <1182535493.241900.166040@m37g2000prh.googlegroups.com> Maybe http://twill.idyll.org/ From anamax at earthlink.net Thu Jun 28 11:32:01 2007 From: anamax at earthlink.net (Andy Freeman) Date: Thu, 28 Jun 2007 08:32:01 -0700 Subject: Python's "only one way to do it" philosophy isn't good? In-Reply-To: References: <7xir9cbm0g.fsf@ruckus.brouhaha.com> <7xejjzmk7u.fsf@ruckus.brouhaha.com> <7xy7i7xjl5.fsf@ruckus.brouhaha.com> Message-ID: <1183044721.683930.131920@x35g2000prf.googlegroups.com> On Jun 27, 11:41 pm, John Nagle wrote: > One right answer would be a pure reference counted system where > loops are outright errors, and you must use weak pointers for backpointers. > ... The general > idea is that pointers toward the leaves of trees should be strong > pointers, and pointers toward the root should be weak pointers. While I agree that weak pointers are good and can not be an afterthought, I've written code where "back" changed dynamically, and I'm pretty sure that Nagle has as well. Many programs with circular lists have an outside pointer to the current element, but the current element changes. All of the links implementing the list have to be strong enough to keep all of the list alive. Yes, one can implement a circular list as a vector with a current index, but that has space and/or time consequences. It's unclear that that approach generalizes for more complicated structures. (You can't just pull all of the links out into such lists.) In short, while disallowing loops with strong pointers is "a" right answer, it isn't always a right answer, so it can't be the only answer. -andy From mccredie at gmail.com Wed Jun 20 16:27:03 2007 From: mccredie at gmail.com (Matimus) Date: Wed, 20 Jun 2007 20:27:03 -0000 Subject: need help with re module In-Reply-To: <1182362532.927017.20760@d30g2000prg.googlegroups.com> References: <1182362532.927017.20760@d30g2000prg.googlegroups.com> Message-ID: <1182371223.260611.286370@j4g2000prf.googlegroups.com> Here is an example: >>> s = "Helloworldok" >>> matchtags = re.compile(r"<[^>]+>") >>> matchtags.findall(s) ['', '', ''] >>> matchtags.sub('',s) 'Helloworldok' I probably shouldn't have shown you that. It may not work for all HTML, and you should probably be looking at something like BeautifulSoup. Matt From nikbaer at gmail.com Sun Jun 10 23:52:28 2007 From: nikbaer at gmail.com (nik) Date: Mon, 11 Jun 2007 03:52:28 -0000 Subject: read 9 bytes Message-ID: <1181533948.427220.14650@j4g2000prf.googlegroups.com> Hi, I need to read a 9 byte response from a device on the serial port. >From reading the pySerial documentation it appears that I can only read in characters at a time. If I do: serialport.read(4) I would get 8 bytes, and if I did serialport.read(5) I think the port will block until a time out, since there Is there a trick to read 9 bytes off of a serial port? Thanks, Nik From mail at microcorp.co.za Thu Jun 7 01:46:05 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Thu, 7 Jun 2007 07:46:05 +0200 Subject: Python for industrial control (was: Who uses Python?) References: <1180985830.288414.208850@q69g2000hsb.googlegroups.com> Message-ID: <008601c7a8c7$3f7d8f20$03000080@hendrik> "Cameron Laird" wrote: > In article , > Hendrik van Rooyen wrote: > > "walterbyrd" wrote: > > > >> Anything else? Finance? Web-analytics? SEO? Digital art? > > > >Industrial control and alarm annunciation > . > . > . > Python can be *great* in these roles. A couple of us launched > to promote > co-operation in the area. While the Wiki has been moribund this > year, it would take little to bring it alive again. Thanks - had a quick look around and will have a decent look later - seems a good idea - Hendrik From siona at chiark.greenend.org.uk Fri Jun 1 10:14:11 2007 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 01 Jun 2007 15:14:11 +0100 (BST) Subject: unknown host References: <1180703347.753746.17070@o5g2000hsb.googlegroups.com> Message-ID: abcd wrote: >I have a linux machine (ip = 10.10.10.8), which can ping other >machines on the same subnet...such as > [ ... ] >If I use socket.gethostbyaddr() I get back results when ip is >10.10.10.1 and 10.10.10.254 but for the other IP addresses >(10.10.10.5, .6, etc) I get back "unknown host". In fact I get >"unknown host" for the linux machine that I run the gethostbyaddr >from. > >If perform the same operation from a windows machine (ip = 10.10.10.5) >it returns data for the other IP addresses as expected. > >any ideas? Almost certainly it's a name resolution configuration problem -- check that on the Linux machine 'host 10.10.10.x' gives the same results as Python, then go and look at what you've got in /etc/hosts and /etc/resolv.conf . -- \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 nogradi at gmail.com Thu Jun 21 02:30:24 2007 From: nogradi at gmail.com (Daniel Nogradi) Date: Thu, 21 Jun 2007 08:30:24 +0200 Subject: Python live environment on web-site? In-Reply-To: <1182405635.091199.180950@i13g2000prf.googlegroups.com> References: <46794396.442103@news.netcologne.de> <1182405635.091199.180950@i13g2000prf.googlegroups.com> Message-ID: <5f56302b0706202330g69ebad6eub9bab4dd9f3da26f@mail.gmail.com> > > I was wondering if there was a python-live-environment available on a > > public web-site similar to the ruby-live-tutorial on > > > > http://tryruby.hobix.com/ > > > > I would prefer something which allows to paste small scripts into a > > text-field, to run them on the server, and to be able to read the > > produced output of the script. > > > > I searched using google but didn't come across such a site. However, I > > imagine there must be at least one.... > > > Crunchy. > As far as I remember the pypy people also put together a publicly available python console in javascript. Actually it's a whole xterm I think and one can start python in there. HTH, Daniel From john106henry at hotmail.com Sat Jun 23 15:31:39 2007 From: john106henry at hotmail.com (John Henry) Date: Sat, 23 Jun 2007 12:31:39 -0700 Subject: Adding method to a class on the fly In-Reply-To: References: <1182538969.522044.209560@q19g2000prn.googlegroups.com> <1182543862.369337.36880@z28g2000prd.googlegroups.com> <1182547065.295969.258820@g37g2000prf.googlegroups.com> <1182547724.690874.279230@g37g2000prf.googlegroups.com> <1182548694.545515.81060@e9g2000prf.googlegroups.com> <1182582129.462036.84560@m37g2000prh.googlegroups.com> <1182614796.146337.290300@x35g2000prf.googlegroups.com> Message-ID: <1182627099.634025.37430@m37g2000prh.googlegroups.com> On Jun 23, 10:56 am, Steven D'Aprano wrote: > On Sat, 23 Jun 2007 09:06:36 -0700, John Henry wrote: > > >> > But then how do I create the on_Button1_mouseClick function? > > >> That depends on what it is supposed to do, but in general you want a > >> factory function -- a function that returns functions. Here's a simple > >> example: > > > > > > Steven, > > > May be I didn't explain it clearly: the PythonCard package expects to > > see a function by the name of on_Button1_mouseClick. I don't do > > anything to register the callback function. The package assumes that > > there is a function by that name whenever I create a button named > > Button1. So, if I don't use exec, how can I create a function by that > > exact name? > > def mouseclick_factory(name): > def function(self, event): > print "You clicked '%s'." % name > function.name = "on_%s_mouseClick" % name > return function > > class Parrot: > def __init__(self, name): > function = mouseclick_factory(name) # as before > method = new.instancemethod(function, self, self.__class__) > setattr(self, function.name, method) > > And here it is in action: > > >>> p = Parrot("Button1") > >>> p.on_Button1_mouseClick("event") > > You clicked 'Button1'. > > -- > Steven. Wouldn't it be nice if it works right away? :=) I tried the above method and this is what I have: #!/usr/bin/python """ __version__ = "$Revision: 1.6 $" __date__ = "$Date: 2004/08/17 19:46:06 $" """ import new from PythonCard import model rsrc = {'application':{'type':'Application', 'name':'Minimal', 'backgrounds': [ {'type':'Background', 'name':'bgMin', 'title':'Minimal PythonCard Application', 'size':(200, 300), 'components': [ ] # end components } # end background ] # end backgrounds } } def mouseclick_factory(parent, name): id_num=int(name[-1:]) parent.components[name] = {'type':'Button', 'name':name, 'label':name, 'position':(5, 5+id_num*30), 'text':name} def function(self, event): print "You clicked '%s'." % name function.name = "on_%s_mouseClick" % name return function class Minimal(model.Background): def on_initialize(self, event): self.components['field1'] = {'type':'TextField','name':'field1','position':(5, 5),'size':(150, -1),'text':'Hello PythonCard'} name = "Button1" function = mouseclick_factory(self, name) # as before method = new.instancemethod(function, self, self.__class__) setattr(self, function.name, method) if __name__ == '__main__': app = model.Application(Minimal, None, rsrc) app.MainLoop() When I click on the button, nothing happens. However, if I call the function directly (like right after the setattr line: self.on_Button1_mouseClick(event) it works fine but PythonCard isn't calling this function when I clicked on the button. From andre.roberge at gmail.com Tue Jun 26 13:52:38 2007 From: andre.roberge at gmail.com (=?iso-8859-1?B?QW5kcuk=?=) Date: Tue, 26 Jun 2007 17:52:38 -0000 Subject: problem mixing gettext and properties Message-ID: <1182880358.100599.139120@j4g2000prf.googlegroups.com> I've encountered a problem using gettext with properties while using a Python interpreter. Here's a simple program that illustrate the problem. ============== # i18n_test.py: test of gettext & properties import gettext fr = gettext.translation('i18n_test', './translations', languages=['fr']) fr.install() help = _("Help me!") class Test_i18n(object): def get(self): __help = _("HELP!") return __help help_prop = property(get, None, None, 'help') test = Test_i18n() print help print test.help_prop #### end of file To run the above program, you need to have the strings translated and the proper ".po" and ".mo" files created. (for those interested, I can send the whole lot in a zip file) If I run the program as is, the output is: Aidez-moi! AIDE!!! Ok, let's try with the Python interpreter: ActivePython 2.4.2 Build 248 (ActiveState Corp.) based on Python 2.4.2 (#67, Oct 30 2005, 16:11:18) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import i18n_test Aidez-moi! AIDE!!! # No surprise there so far. >>> print i18n_test.help Aidez-moi! >>> print i18n_test.test.help_prop AIDE!!! >>> i18n_test.help 'Aidez-moi!' # all of the above are as expected; now for the first surprise >>> i18n_test.test.help_prop Traceback (most recent call last): File "", line 1, in ? File "i18n_test.py", line 12, in get __help = _("HELP!") TypeError: 'str' object is not callable # and a second surprise where we try to repeat something that used to work >>> print i18n_test.test.help_prop Traceback (most recent call last): File "", line 1, in ? File "i18n_test.py", line 12, in get __help = _("HELP!") TypeError: 'str' object is not callable #============= Dare I say: "Help!" I really need to use the above at the interpreter prompt. Andr? From timr at probo.com Fri Jun 15 02:29:05 2007 From: timr at probo.com (Tim Roberts) Date: Fri, 15 Jun 2007 06:29:05 GMT Subject: Convert to C/C++? References: <1181852202.897976.312280@j4g2000prf.googlegroups.com> Message-ID: SpreadTooThin wrote: > >I am wondering if someone who knows the implemention of python's time >could help converting this to c/c++.... If you are running on Windows, you can replace this entire thing with one call to CoCreateGuid, possibly with a call to StringFromGUID to make it printable. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From python at jayloden.com Fri Jun 22 02:12:00 2007 From: python at jayloden.com (Jay Loden) Date: Fri, 22 Jun 2007 02:12:00 -0400 Subject: Error in following code In-Reply-To: <1182491886.184746.104640@x35g2000prf.googlegroups.com> References: <1182491886.184746.104640@x35g2000prf.googlegroups.com> Message-ID: <467B6830.7060001@jayloden.com> zaperaj at gmail.com wrote: > [root at localhost root]# python t4.py > enter number: 6 > [root at localhost root]# > > i.e it takes the input but doesn't print anything. If anybody can > help... Thanx! You're creating a function called "f" in the first line, but the script never does anything with it, so it never gets executed. You need to actually call your function after creating it: ----- #! usr/bin/env/python def f(n=int(raw_input("enter number: "))): print 'n=',n if n>1: return n*f(n-1) else: print 'end' return 1 f() ----- That should do the trick. From balu.vemu at gmail.com Thu Jun 21 11:47:30 2007 From: balu.vemu at gmail.com (Bala Subramanyam vemu) Date: Thu, 21 Jun 2007 11:47:30 -0400 Subject: unable to execute to a python script Message-ID: Hi All Firstly i am new to pythong and I am stuck with the following problem dont really know whether it has been posted previously in the mailing list( pardon me if its so ) I have written (found in the net ) a small program to list the rpms in the linux box ------------Starts here ------------ #!/usr/bin/python2.5 import rpm ts=rpm.TransactionSet() mi=ts.dbMatch() for h in mi: print h['name'] --------Ends Here----------------- It executes fine in the python shell, but the problem is in when i execute as a python script i get the following error DCA-TestMachine:~/python_scripts # python2.5 -v rpmqa.py # installing zipimport hook import zipimport # builtin # installed zipimport hook # /usr/local/lib/python2.5/site.pyc matches /usr/local/lib/python2.5/site.py import site # precompiled from /usr/local/lib/python2.5/site.pyc # /usr/local/lib/python2.5/os.pyc matches /usr/local/lib/python2.5/os.py import os # precompiled from /usr/local/lib/python2.5/os.pyc import posix # builtin # /usr/local/lib/python2.5/posixpath.pyc matches /usr/local/lib/python2.5/posixpath.py import posixpath # precompiled from /usr/local/lib/python2.5/posixpath.pyc # /usr/local/lib/python2.5/stat.pyc matches /usr/local/lib/python2.5/stat.py import stat # precompiled from /usr/local/lib/python2.5/stat.pyc # /usr/local/lib/python2.5/UserDict.pyc matches /usr/local/lib/python2.5/UserDict.py import UserDict # precompiled from /usr/local/lib/python2.5/UserDict.pyc # /usr/local/lib/python2.5/copy_reg.pyc matches /usr/local/lib/python2.5/copy_reg.py import copy_reg # precompiled from /usr/local/lib/python2.5/copy_reg.pyc # /usr/local/lib/python2.5/types.pyc matches /usr/local/lib/python2.5/types.py import types # precompiled from /usr/local/lib/python2.5/types.pyc import _types # builtin # /usr/local/lib/python2.5/warnings.pyc matches /usr/local/lib/python2.5/warnings.py import warnings # precompiled from /usr/local/lib/python2.5/warnings.pyc # /usr/local/lib/python2.5/linecache.pyc matches /usr/local/lib/python2.5/linecache.py import linecache # precompiled from /usr/local/lib/python2.5/linecache.pyc import encodings # directory /usr/local/lib/python2.5/encodings # /usr/local/lib/python2.5/encodings/__init__.pyc matches /usr/local/lib/python2.5/encodings/__init__.py import encodings # precompiled from /usr/local/lib/python2.5/encodings/__init__.pyc # /usr/local/lib/python2.5/codecs.pyc matches /usr/local/lib/python2.5/codecs.py import codecs # precompiled from /usr/local/lib/python2.5/codecs.pyc import _codecs # builtin # /usr/local/lib/python2.5/encodings/aliases.pyc matches /usr/local/lib/python2.5/encodings/aliases.py import encodings.aliases # precompiled from /usr/local/lib/python2.5/encodings/aliases.pyc # /usr/local/lib/python2.5/encodings/utf_8.pyc matches /usr/local/lib/python2.5/encodings/utf_8.py import encodings.utf_8 # precompiled from /usr/local/lib/python2.5/encodings/utf_8.pyc Python 2.5.1 (r251:54863, Jun 21 2007, 10:46:46) [GCC 4.1.0 (SUSE Linux)] on linux2 Type "help", "copyright", "credits" or "license" for more information. # /root/python_scripts/rpm.pyc matches /root/python_scripts/rpm.py import rpm # precompiled from /root/python_scripts/rpm.pyc Traceback (most recent call last): File "rpmqa.py", line 1, in import rpm File "/root/python_scripts/rpm.py", line 10, in main() File "/root/python_scripts/rpm.py", line 3, in main tss= rpm.TransactionSet() AttributeError: 'module' object has no attribute 'TransactionSet' # clear __builtin__._ # clear sys.path # clear sys.argv # clear sys.ps1 # clear sys.ps2 # clear sys.exitfunc # clear sys.exc_type # clear sys.exc_value # clear sys.exc_traceback # clear sys.last_type # clear sys.last_value # clear sys.last_traceback # clear sys.path_hooks # clear sys.path_importer_cache # clear sys.meta_path # restore sys.stdin # restore sys.stdout # restore sys.stderr # cleanup __main__ # cleanup[1] site # cleanup[1] encodings # cleanup[1] _codecs # cleanup[1] zipimport # cleanup[1] warnings # cleanup[1] encodings.utf_8 # cleanup[1] codecs # cleanup[1] types # cleanup[1] _types # cleanup[1] signal # cleanup[1] linecache # cleanup[1] posix # cleanup[1] encodings.aliases # cleanup[1] exceptions # cleanup[2] copy_reg # cleanup[2] posixpath # cleanup[2] os.path # cleanup[2] stat # cleanup[2] UserDict # cleanup[2] os # cleanup sys # cleanup __builtin__ [7359 refs] # cleanup ints: 7 unfreed ints in 1 out of 7 blocks # cleanup floats I dont know what path I should set the PYTHONHOME PYTHONPATH .etc.. variables Thanks in advance for your help -- Regards Subramanyam -------------- next part -------------- An HTML attachment was scrubbed... URL: From kyosohma at gmail.com Mon Jun 25 09:00:00 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Mon, 25 Jun 2007 06:00:00 -0700 Subject: Which XML? In-Reply-To: <467F8109.2000900@web.de> References: <1182733291.251144.211760@k79g2000hse.googlegroups.com> <467F8109.2000900@web.de> Message-ID: <1182776400.009587.34940@n2g2000hse.googlegroups.com> On Jun 25, 3:47 am, Stefan Behnel wrote: > kyoso... at gmail.com wrote: > > On Jun 24, 7:04 pm, Bruno Barberi Gnecco > > wrote: > >> I've found a lot of XML libraries for Python. Any advices on which > >> one to use (or *not* to use)? My requirements are: support for XPath, > >> stability (a must, segfaults are not an option), with DOM API and good > >> performance desirable. > > > I use the minidom module for most of my XML work, but I don't think it > > has much in the way of XPath. I think lxml might work better for that > > sort of thing and I think it's part of ElementTree: > > >http://codespeak.net/lxml/dev/objectify.html > > lxml is not part of ElementTree (only mostly compatible), but it's a must if > you want to have a simple API *and* XPath *and* good performance. > > http://codespeak.net/lxml/ > > The API is not W3C-DOM compatible, but that's rather a plus IMHO. > > Stefan Oops, sorry about the mis-information. I mis-read http://effbot.org/zone/element-index.htm Mike From steve at holdenweb.com Sat Jun 9 07:39:04 2007 From: steve at holdenweb.com (Steve Holden) Date: Sat, 09 Jun 2007 07:39:04 -0400 Subject: how to convert a bitmap file to an array ? In-Reply-To: <3da6e$466554b7$83aef404$11190@news1.tudelft.nl> References: <3da6e$466554b7$83aef404$11190@news1.tudelft.nl> Message-ID: stef wrote: > Stefan Sonnenberg-Carstens wrote: >> stef schrieb: >>> hello >>> >>> I can find all kind of procedures to convert an array to a bitmap >>> (wxPython, PIL), >>> but I can't find the reverse, >>> either >>> - convert a bitmap to an array >>> or >>> - read a bitmap file to an array >>> >>> thanks, >>> Stef Mientki >>> >> Take a look at the "struct" module. >> There you fill find pack/unpack, which can do what you need. > thanks Stefan, > > but using struct, I need to know how a bitmap file is build, > I don't know that (and I rather don't want to know that ;-) > > Any better solutions (I'm a spoiled Delphi user ;-) > I can offer the code below, but I can't guarantee you won't need to play with it. You can almost certainly ignire the fonty bits! def _setupContext(memory, font=None, color=None): if font: memory.SetFont(font) else: memory.SetFont(wx.NullFont) if color: memory.SetTextForeground(wx.Colour(*color)) def write( text, bitmap, pos=(0,0), font=None, color=None): """Simple write into a bitmap doesn't do any checking.""" memory = wx.MemoryDC() _setupContext(memory, font, color) memory.SelectObject(bitmap) width, height = memory.GetTextExtent(text) try: memory.DrawText(text, pos[0],pos[1],) finally: memory.SelectObject(wx.NullBitmap) return width def bitmapToPil(bitmap): return imageToPil(bitmapToImage(bitmap)) def bitmapToImage(bitmap): return wx.ImageFromBitmap(bitmap) def pilToBitmap(pil): return imageToBitmap(pilToImage(pil)) def pilToImage(pil): image = wx.EmptyImage(pil.size[0], pil.size[1]) image.SetData(pil.convert('RGB').tostring()) return image def imageToPil(image): pil = Image.new('RGB', (image.GetWidth(), image.GetHeight())) pil.fromstring(image.GetData()) return pil def imageToBitmap(image): return image.ConvertToBitmap() regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From martin at v.loewis.de Tue Jun 26 23:33:23 2007 From: martin at v.loewis.de (=?UTF-8?B?Ik1hcnRpbiB2LiBMw7Z3aXMi?=) Date: Wed, 27 Jun 2007 05:33:23 +0200 Subject: Chroot Jail Not Secure for Sandboxing Python? In-Reply-To: References: <1182748892.916068.146780@p77g2000hsh.googlegroups.com> <467f55f7$0$20850$9b622d9e@news.freenet.de> <1182782910.811850.284350@u2g2000hsc.googlegroups.com> <1182787116.717732.35390@q75g2000hsh.googlegroups.com> <1182831792.579644.296820@q75g2000hsh.googlegroups.com> Message-ID: <4681DA83.8070203@v.loewis.de> > To launch a child process in a chroot you can easily just fork and > then make the chroot syscall in the child process immediately after > the fork. It's not so easy. On Linux, you need to have the CAP_SYS_CHROOT capability to invoke the syscall; on other systems, you may have to be root. Regards, Martin From nszabolcs at gmail.com Fri Jun 8 02:32:31 2007 From: nszabolcs at gmail.com (Szabolcs Nagy) Date: Thu, 07 Jun 2007 23:32:31 -0700 Subject: Bragging about Python In-Reply-To: References: Message-ID: <1181284351.818451.250380@q69g2000hsb.googlegroups.com> Steve Howell wrote: > --- Georg Brandl wrote: > > >> > > >> 15 small programs here: > > >> > > >> http://wiki.python.org/moin/SimplePrograms > > >> > > > > > > IMHO a few python goodies are missing there. > > > > "It's a Wiki." ;) > > > > Yes indeed. Please feel free to add to the page, or > make your own fork. See link above. the title of a program shouldn't be part of the code (or it should at least start with #) sorry i'm too lazy now to fix it, but imho it needs nicer layout to be used as 'bragging about python' site btw nice idea a good example worth a 100 pages of documentation From DPhillips at cybergroup.com Sun Jun 10 23:01:39 2007 From: DPhillips at cybergroup.com (Doug Phillips) Date: Sun, 10 Jun 2007 22:01:39 -0500 Subject: Are there any python jobs worked at home from the internet? In-Reply-To: Message-ID: <9A9D5186629F3D428E3C7CBA92A66E47D2F293@mail-26ps.atlarge.net> > I know of http://www.rentacoder.com/ but I've never actually used it. http://www.guru.com and http://www.getafreelancer.com are also good sites (in fact I got my current employment starting off as a contractor on guru.com) There are others, but these are the three I've worked with and felt comfortable working with. Hope this helps. -Doug From henhiskan at gmail.com Tue Jun 12 12:01:01 2007 From: henhiskan at gmail.com (Richard Rossel) Date: Tue, 12 Jun 2007 16:01:01 -0000 Subject: how to kill a process Message-ID: <1181664061.381917.41270@a26g2000pre.googlegroups.com> Hi Fellows, I have a problem with process termination. I have a python code that apache runs through a django interface. The code is very simple, first, it creates a process with the subprocess.Popen call, and afterwards, (using a web request) the python code uses the PID of the previously created process(stored in a db) and kills it with an os.kill call using the SIGKILL signal. The creation of the process is ok, apache calls the python code, this code creates the process and exits leaving the process up and running :) But when the python code is called to kill the created process, the process is left in a zombie state. The kill code that I'm using is: os.kill(pid, signal.SIGKILL) and I also tried: kill_proc = Popen("kill -9 " + pid, shell=true) but with no success. I suppose that the reason maybe that the python code exits before the kill call has finished, so I tried with a while loop until kill_proc.poll() != None, but without success too :( do you know what is what I'm doing wrong? thanks very much.- From bbxx789_05ss at yahoo.com Sun Jun 17 10:43:31 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: Sun, 17 Jun 2007 07:43:31 -0700 Subject: sqlite3 bug?? In-Reply-To: <46753426$0$30325$fa0fcedb@news.zen.co.uk> References: <46752230$0$31685$db0fefd9@news.zen.co.uk> <46753426$0$30325$fa0fcedb@news.zen.co.uk> Message-ID: <1182091411.108272.286280@o61g2000hsh.googlegroups.com> On Jun 17, 7:16 am, mark carter wrote: > David Wahler wrote: > > On 6/17/07, mark carter wrote: > >> Anyone else getting these problems? > > > Seehttp://www.python.org/dev/peps/pep-0249/(emphasis mine): > > > .commit() > > OK, I tried that, and I appear to be cooking. The funny thing is, I > could have sworn that I tried that a few days ago, and it didn't work. > Weird. Appears to be working now, though, so I guess I must have been > doing something kooky. > > Should I also explicitly close the cursor and connection, or is that > taken care of "automagically"? > > I'm seriously thinking about reporting the commit() thing as a doc bug > in python, as this isn't mentioned athttp://docs.python.org/lib/module-sqlite3.html > and I think it's exactly the kind of thing that should be mentioned in > the examples. Please report the whole docs as a bug. From claird at lairds.us Mon Jun 11 11:52:09 2007 From: claird at lairds.us (Cameron Laird) Date: Mon, 11 Jun 2007 15:52:09 +0000 Subject: Tkinter - resize tkMessageBox References: <1180988981.634298.38830@o11g2000prd.googlegroups.com> <1181026856.261957.207570@q75g2000hsh.googlegroups.com> <0v0hj4-pip.ln1@lairds.us> Message-ID: <9m70k4-3mh.ln1@lairds.us> In article <0v0hj4-pip.ln1 at lairds.us>, I wondered: >In article <1181026856.261957.207570 at q75g2000hsh.googlegroups.com>, >Glenn Hutchings wrote: >>On 4 Jun, 21:29, rahulna... at yahoo.com wrote: >>> Is there a way to resize the width of the "tkMessageBox.askyesno" >>> dialog box, so that the text does not wrap to the next line. >> >>You can use the Tk option database, either explicitly or from a file. >>For example, to set the wrap length of all dialogs to 10 inches, try >>this: >> >> root = Tk() >> root.option_add("*Dialog.msg.wrapLength", "10i") > . > . > . >But that does *not* affect the MessageBoxes under MacOS and Windows, right? I apologize for my coyness. I'll be explicit: current MessageBoxes under MacOS and Windows (but NOT X11-based MessageBoxes, as with Linux) do NOT respect Dialog options. Tkinter will presumably build in Tile capabilities in the future; then the default appearances may change again. From JoeSalmeri at hotmail.com Tue Jun 5 11:13:05 2007 From: JoeSalmeri at hotmail.com (Joe Salmeri) Date: Tue, 5 Jun 2007 11:13:05 -0400 Subject: Python 2.5.1 broken os.stat module References: <466140A6.1090100@v.loewis.de><-aOdnbFdroD_gP_bnZ2dnUVZ_uKknZ2d@comcast.com><4662750b$0$29898$9b622d9e@news.freenet.de><4662F98C.8070709@v.loewis.de><466472C8.9020003@v.loewis.de> Message-ID: > But that perspective is not directly relevant to *your* topic line. When > you make a claim that os.stat is 'broken' and bugged, you are making a > claim about the *programmer* experience -- in particular, experiencing a > discrepancy between performance and reasonable expectation based on the > manuals. Martin and I are both concerned about that particular claim > (which now appears to be resolved in the negative). The subject line reflects what *originally* appeared to be the source of the problem since a comparison of the results did not match previous Python versions. For other developers that run into this difference (which did not occur before) I believe it is benefitial to them to understand why the difference is now occurring and why BOTH Python and Windows are displaying CORRECT results even though they do NOT match what they display. For those same developers, I also posted a localtime_windows much which allows them to massage the values returned by Python localtime so that they match the values that Windows displays if they have the need and/or requirement to do so. Often times in development what "appears" to be the source of the problem turns out that it is not the actual problem that is occurring. It is still beneficial to have that link from what "appears" to be the problem to the details of what "actually" is the source of the problem. For another developer that runs into this difference their most likely initial conclusion would be that something in Python 2.5.1 is broke especially when they research the changes in Python 2.5.1 and find that os.stat was changed. As a general rule, when something is broke, suspect the last thing that you did even if it does not seem like it should be the source of the problem. > Python developers cannot fix that. Besides which, Python is a > cross-platform language, originally developed on *nix. Really, I thought they could fix anything :-) From ed at leafe.com Sat Jun 2 18:10:33 2007 From: ed at leafe.com (Ed Leafe) Date: Sat, 2 Jun 2007 18:10:33 -0400 Subject: PythonCard or Dabo? In-Reply-To: <1180783340.405317.89630@w5g2000hsg.googlegroups.com> References: <1174326003.145538.113010@y80g2000hsf.googlegroups.com> <2fv163d2lv8gd9g3qqfbh91a7hraqbbi7v@4ax.com> <1180783340.405317.89630@w5g2000hsg.googlegroups.com> Message-ID: <96E46598-A202-4627-91C7-C059F20208A1@leafe.com> On Jun 2, 2007, at 7:22 AM, SPE - Stani's Python Editor wrote: > Another alternative are GUI designers such as wxGlade or XRCed, both > of which ship with SPE (http://pythonide.stani.be). Dabo is especially > usefull (but not limited to) developping database applications as it > is an open source alternative to Visual Fox pro. Sorry for coming into this discussion late; I was away celebrating our 21st anniversary with my wife! I think that the most important thing to consider in deciding between one or the other is what it is you want to do. PythonCard is much easier if you want to create a simple GUI app. In fact, when I first started working with Python, I used PythonCard to develop my first GUI apps, and we've paid homage to PythonCard in Dabo by incorporating some of their better ideas. :-). The problem I found was that I quickly ran into a wall where I needed to do something that PythonCard didn't do, and the workaround was more complex than if I had started with plain wxPython in the first place. Since at that time PythonCard didn't support sizers, and I needed cross- platform apps, it really didn't handle the hard stuff like sizers very well. When I started with the Dabo Class Designer, I made it sizer-centric from the start, since I felt then that sizers are a necessity in UI design. Yes, we also support fixed-position/size controls, but I think that the investment in grokking sizers pays off many times over, especially when you can see exactly how something will look up front, rather than guessing in code and then modifying your code when the result isn't what you wanted. The other thing I would point out is that the Dabo Class Designer is written in 100% Dabo code: no raw wxPython or external libraries are used. The Class Designer is probably one of the most complex applications I have ever written in my 20+ years as a developer, and Dabo can handle it just fine. To me, that demonstrates that not only is the UI class library rich and robust, but the event model that we wrote is also very powerful. If you have an app that requires a more complex UI than the Dabo Class Designer, I'd sure like to see it! So if you ask me which product to use, I would naturally be inclined to say Dabo, but really, the main question is just how complex is your app. If you need to work with a backend database, well, then it's a no-brainer - Dabo is designed to handle data as well as any free or commercial tool on the market. But for a simple UI app, such as many of the PythonCard demos, I'd have to say that you should look at both and see which one feels more comfortable to you, and go with that. -- Ed Leafe -- http://leafe.com -- http://dabodev.com From jdh2358 at gmail.com Tue Jun 5 13:40:13 2007 From: jdh2358 at gmail.com (jdh2358 at gmail.com) Date: Tue, 05 Jun 2007 17:40:13 -0000 Subject: ANN: matplotlib 0.90.1 graphing package Message-ID: <1181065213.520719.143870@q75g2000hsh.googlegroups.com> matplotlib-0.90.1 has just been released. matplotlib is a graphing package for python which can be used interactively from the python shell ala Mathematica or Matlab, embedded in a GUI application, or used in batch mode to generate graphical hardcopy, eg in a web application server. Many raster and vector outputs are supported (PNG, SVG, PDF, PS, and more). You can get the source release, eggs and binary builds for OS X and windows at the download link below homepage: http://matplotlib.sourceforge.net/ what's new: http://matplotlib.sourceforge.net/whats_new.html screenshots: http://matplotlib.sourceforge.net/screenshots.html tutorial: http://matplotlib.sourceforge.net/tutorial.html mailing list: http://sourceforge.net/mailarchive/forum.php?forum_name=matplotlib-users downloads: http://sourceforge.net/project/showfiles.php?group_id=80706&package_id=82474 The CHANGELOG entries for the 0.90.1 release are below -- see the what's new link above for an overview Thanks, John Hunter ============================================================== 2007-06-02 Released 0.90.1 at revision 3352 2007-06-02 Display only meaningful labels when calling legend() without args. - NN 2007-06-02 Have errorbar follow the color cycle even if line is not plotted. Suppress plotting of errorbar caps for capsize=0. - NN 2007-06-02 Set markers to same alpha value as line. - NN 2007-06-02 Fix mathtext position in svg backend. - NN 2007-06-01 Deprecate Numeric and numarray for use as numerix. Props to Travis -- job well done. - ADS 2007-05-18 Added LaTeX unicode support. Enable with the 'text.latex.unicode' rcParam. This requires the ucs and inputenc LaTeX packages. - ADS 2007-04-23 Fixed some problems with polar -- added general polygon clipping to clip the lines a nd grids to the polar axes. Added support for set_rmax to easily change the maximum radial grid. Added support for polar legend - JDH 2007-04-16 Added Figure.autofmt_xdate to handle adjusting the bottom and rotating the tick labels for date plots when the ticks often overlap - JDH 2007-04-09 Beginnings of usetex support for pdf backend. -JKS 2007-04-07 Fixed legend/LineCollection bug. Added label support to collections. - EF 2007-04-06 Removed deprecated support for a float value as a gray- scale; now it must be a string, like '0.5'. Added alpha kwarg to ColorConverter.to_rgba_list. - EF 2007-04-06 Fixed rotation of ellipses in pdf backend (sf bug #1690559) -JKS 2007-04-04 More matshow tweaks; documentation updates; new method set_bounds() for formatters and locators. - EF 2007-04-02 Fixed problem with imshow and matshow of integer arrays; fixed problems with changes to color autoscaling. - EF 2007-04-01 Made image color autoscaling work correctly with a tracking colorbar; norm.autoscale now scales unconditionally, while norm.autoscale_None changes only None-valued vmin, vmax. - EF 2007-03-31 Added a qt-based subplot-adjustment dialog - DSD 2007-03-30 Fixed a bug in backend_qt4, reported on mpl-dev - DSD 2007-03-26 Removed colorbar_classic from figure.py; fixed bug in Figure.clf() in which _axobservers was not getting cleared. Modernization and cleanups. - EF 2007-03-26 Refactored some of the units support -- units now live in the respective x and y Axis instances. See also API_CHANGES for some alterations to the conversion interface. JDH 2007-03-25 Fix masked array handling in quiver.py for numpy. (Numeric and numarray support for masked arrays is broken in other ways when using quiver. I didn't pursue that.) - ADS 2007-03-23 Made font_manager.py close opened files. - JKS 2007-03-22 Made imshow default extent match matshow - EF 2007-03-22 Some more niceties for xcorr -- a maxlags option, normed now works for xcorr as well as axorr, usevlines is supported, and a zero correlation hline is added. See examples/xcorr_demo.py. Thanks Sameer for the patch. - JDH 2007-03-21 Axes.vlines and Axes.hlines now create and returns a LineCollection, not a list of lines. This is much faster. The kwarg signature has changed, so consult the docs. Modified Axes.errorbar which uses vlines and hlines. See API_CHANGES; the return signature for these three functions is now different 2007-03-20 Refactored units support and added new examples - JDH 2007-03-19 Added Mike's units patch - JDH 2007-03-18 Matshow as an Axes method; test version matshow1() in pylab; added 'integer' Boolean kwarg to MaxNLocator initializer to force ticks at integer locations. - EF 2007-03-17 Preliminary support for clipping to paths agg - JDH 2007-03-17 Text.set_text() accepts anything convertible with '%s' - EF 2007-03-14 Add masked-array support to hist. - EF 2007-03-03 Change barh to take a kwargs dict and pass it to bar. Fixes sf bug #1669506. 2007-03-02 Add rc parameter pdf.inheritcolor, which disables all color-setting operations in the pdf backend. The idea is that you include the resulting file in another program and set the colors (both stroke and fill color) there, so you can use the same pdf file for e.g. a paper and a presentation and have them in the surrounding color. You will probably not want to draw figure and axis frames in that case, since they would be filled in the same color. - JKS 2007-02-26 Prevent building _wxagg.so with broken Mac OS X wxPython. - ADS 2007-02-23 Require setuptools for Python 2.3 - ADS 2007-02-22 WXAgg accelerator updates - KM WXAgg's C++ accelerator has been fixed to use the correct wxBitmap constructor. The backend has been updated to use new wxPython functionality to provide fast blit() animation without the C++ accelerator. This requires wxPython 2.8 or later. Previous versions of wxPython can use the C++ acclerator or the old pure Python routines. setup.py no longer builds the C++ accelerator when wxPython >= 2.8 is present. The blit() method is now faster regardless of which agg/ wxPython conversion routines are used. 2007-02-21 Applied the PDF backend patch by Nicolas Grilly. This impacts several files and directories in matplotlib: - Created the directory lib/matplotlib/mpl-data/fonts/ pdfcorefonts, holding AFM files for the 14 PDF core fonts. These fonts are embedded in every PDF viewing application. - setup.py: Added the directory pdfcorefonts to package_data. - lib/matplotlib/__init__.py: Added the default parameter 'pdf.use14corefonts'. When True, the PDF backend uses only the 14 PDF core fonts. - lib/matplotlib/afm.py: Added some keywords found in recent AFM files. Added a little workaround to handle Euro symbol. - lib/matplotlib/fontmanager.py: Added support for the 14 PDF core fonts. These fonts have a dedicated cache (file pdfcorefont.cache), not the same as for other AFM files (file .afmfont.cache). Also cleaned comments to conform to CODING_GUIDE. - lib/matplotlib/backends/backend_pdf.py: Added support for 14 PDF core fonts. Fixed some issues with incorrect character widths and encodings (works only for the most common encoding, WinAnsiEncoding, defined by the official PDF Reference). Removed parameter 'dpi' because it causes alignment issues. -JKS (patch by Nicolas Grilly) 2007-02-17 Changed ft2font.get_charmap, and updated all the files where get_charmap is mentioned - ES 2007-02-13 Added barcode demo- JDH 2007-02-13 Added binary colormap to cm - JDH 2007-02-13 Added twiny to pylab - JDH 2007-02-12 Moved data files into lib/matplotlib so that setuptools' develop mode works. Re-organized the mpl-data layout so that this source structure is maintained in the installation. (I.e. the 'fonts' and 'images' sub-directories are maintained in site-packages.) Suggest removing site-packages/matplotlib/mpl-data and ~/.matplotlib/ttffont.cache before installing - ADS 2007-02-07 Committed Rob Hetland's patch for qt4: remove references to text()/latin1(), plus some improvements to the toolbar layout - DSD From itkovian at gmail.com Thu Jun 14 09:44:55 2007 From: itkovian at gmail.com (itkovian) Date: Thu, 14 Jun 2007 06:44:55 -0700 Subject: xmlrpclib hangs execution In-Reply-To: <1181826648.471177.124170@d30g2000prg.googlegroups.com> References: <45AC0631.8080601@ctw.utwente.nl><465A9DC7.2010708@gmail.com> <465d9040$0$326$e4fe514c@news.xs4all.nl> <1181826648.471177.124170@d30g2000prg.googlegroups.com> Message-ID: <1181828695.224886.48380@o11g2000prd.googlegroups.com> On Jun 14, 3:10 pm, itkov... at gmail.com wrote: > Hi, > > > 2. The Python implementation ofxmlrpcis not very robust. It just waits for > > the connection to close. A well-written client (like your Java client) > > would detect the presence of a Content-Length header and use that. > > I'm facing a similar ordeal here. I think the right thing to do would > be to adjust the xmlrpc library to parse the header and check for the > Content-Length. Right now, the socket seems to read 1024 bytes, so > naturally, when the connection closes, the socket throws an error, > because it thinks that more bytes are coming. Which sounds rather > weird to me, given the fact that in rare cases the reply will be a > multiple of 1024 bytes :-) > > -- Andy Georges For now, these changes helped me out. It probably (read: certainly) needs some cleanup, and I'm probably not taking everything into account as I should: --- xmlrpclib.py 2007-06-14 15:42:36.000000000 +0200 +++ /sw/lib/python2.5/xmlrpclib.py 2006-11-29 02:46:38.000000000 +0100 @@ -1184,11 +1184,6 @@ errcode, errmsg, headers = h.getreply() - expected_payload_length = 1024 - if headers.has_key('content-length'): - expected_payload_length = int(headers['content-length']) - - if errcode != 200: raise ProtocolError( host + handler, @@ -1203,7 +1198,7 @@ except AttributeError: sock = None - return self._parse_response(h.getfile(), sock, expected_payload_length) + return self._parse_response(h.getfile(), sock) ## # Create parser. @@ -1323,23 +1318,21 @@ # could not be accessed). # @return Response tuple and target method. - def _parse_response(self, file, sock, size=1024): + def _parse_response(self, file, sock): # read response from input file/socket, and parse it p, u = self.getparser() while 1: if sock: - response = sock.recv(size) + response = sock.recv(1024) else: - response = file.read(size) + response = file.read(1024) if not response: break if self.verbose: print "body:", repr(response) p.feed(response) - if len(response) == size: - break file.close() p.close() -- Andy Georges From Envelope.Salad at gmail.com Thu Jun 7 21:06:45 2007 From: Envelope.Salad at gmail.com (Pomato) Date: Thu, 07 Jun 2007 18:06:45 -0700 Subject: pickling problem In-Reply-To: References: Message-ID: <1181264805.279023.121220@q66g2000hsg.googlegroups.com> Brian Blais wrote: > Hello, > > I have a somewhat nested dict that I want to pickle, but it (sometimes) contains some > no-no's (specifically, in this case, functions). I know I can't pickle them, but I > would like to be able to pickle the rest of the dict. Is there a good way to be able > to walk through a dict, and take out all of the non-pickleable objects? I could > replace them with something else (a tag of some sort, for me to reconstruct things > later). > > > thanks, > > Brian Blais > > -- > ----------------- > > bblais at bryant.edu > http://web.bryant.edu/~bblais One way to do that could be: >> d = {1:functionA, 2:functionB, 3:"String"} >> for key in d: >> if callable(key): d[key] = "tag" That would work for the functions in your dictionary. From doug at alum.mit.edu Sat Jun 23 14:56:35 2007 From: doug at alum.mit.edu (Douglas Alan) Date: Sat, 23 Jun 2007 14:56:35 -0400 Subject: Python's "only one way to do it" philosophy isn't good? References: <1181368143.874341.273140@r19g2000prf.googlegroups.com> <7x3b0nmkk6.fsf@ruckus.brouhaha.com> Message-ID: Steven D'Aprano writes: >> So one use for macros would be so that I can define "let" and "set" >> statements so that I might code like this: >> >> let longVariableName = 0 >> set longVarableName = foo(longVariableName) >> >> Then if longVarableName didn't already exist, an error would be >> raised, rather than a new variable being automatically created for me. > So "let" is the initial declaration, and "set" modifies the existing > variable? Yes. > What happens is you declare a variable twice? The same thing that would happen in Perl or any other language that supports this type of variable declaration and setting: it would raise an error. The big debate you get next, is then whether you should be allowed to shadow variables in nested scopes with new variables of the same name. Given that Python already allows this, my guess is that the answer should be yes. > How long did it take you to write the macros, and use them, compared > to running Pylint or Pychecker or equivalent? An hour? Who cares? You write it once and then you have it for the rest of your life. You put it in a widely available library, and then *every* programmer also has it for the rest of their lives. The amortized cost: $0.00. The value: priceless. > But if you really want declarations, you can have them. >>>> import variables >>>> variables.declare(x=1, y=2.5, z=[1, 2, 4]) >>>> variables.x = None >>>> variables.w = 0 > Traceback (most recent call last): > File "", line 1, in > File "variables.py", line 15, in __setattr__ > raise self.DeclarationError("Variable '%s' not declared" % name) > variables.DeclarationError: Variable 'w' not declared Thanks, but that's just too syntactically ugly and verbose for me to use. Not only that, but my fellow Python programmers would be sure to come and shoot me if I were to code that way. One of the reasons that I want to use Python is because I like reading and writing code that is easy to read and looks good. I don't want to bend it to my will at the expense of ugly looking code. |>oug From walterbyrd at iname.com Tue Jun 26 09:15:04 2007 From: walterbyrd at iname.com (walterbyrd) Date: Tue, 26 Jun 2007 06:15:04 -0700 Subject: Collections of non-arbitrary objects ? In-Reply-To: <46801791$0$32172$426a34cc@news.free.fr> References: <1182449993.223262.229500@z28g2000prd.googlegroups.com> <87k5twx4hf.fsf@benfinney.id.au> <1182559502.069773.321620@i38g2000prf.googlegroups.com> <87wsxvrzsj.fsf@benfinney.id.au> <1182620734.940718.196520@e16g2000pri.googlegroups.com> <467ed491$0$27132$426a34cc@news.free.fr> <1182780863.067601.89320@d30g2000prg.googlegroups.com> <46801791$0$32172$426a34cc@news.free.fr> Message-ID: <1182863704.364272.5950@i13g2000prf.googlegroups.com> > > On Jun 24, 10:31 pm, Bruno Desthuilliers > > wrote: > > You perhaps don't know this, but most statically typed languages have > the notion of either pointers or references, that can cause similar - > and usually worse - problems. > Yes, but those languages also have the notion of structures that do not allow arbitrary collections. That is what I was wondering about when I started the thread. It's fine that python has four different ways of creating collections of arbitrary data types, but I thought it might be helpful if python had, at least, one way of a creating a collection of non-arbitrary data. > > You do program carefully, don't you ?-) > I try. But things like typos are a normal part a life. > > Now did you actually had any effective problem with Python's dynamism ? > Or are you just scared ? > Just scared. > You know, Python is now something like 17 years old, and is used by a > *lot* of peoples for a *lot* of programs - some of them far from > trivial. I think you can be confident in this experience. IOW, just > write your code, and you'll find out that the kind of problems you seem > to fear so much will not happens that often. > Of course, BASIC is over 40 years old, also used by a *lot* of people. A lot of non-trivial apps have been written in BASIC. But, BASIC is often criticized for it's lack of structure. A language's longevity, and/or popularity, don't mean there isn't room for improvement. Guido must think python has a lot of room for improvement since he's completely throwing out backward compatibility with python 3000. > > You don't use tuples "instead of" lists. Lists are collections, tuples > are structured data. > It seems to me that tuple are essentially immutable lists. So why impose that immutability restriction on a data collection? Why not just have lists and not tuples? What can a tuple do that a list can not do? Why was python designed so that tuples could be used for dictionary indexes, but not lists? Could it be because imposing that restriction on a data collection insures a certain degree of integrity? My point is: sometimes imposing some restrictions can give a degree in built-in integrity. Maybe you don't need that integrity insurance, if you code carefully enough, but can you always count on that? BTW: I'm not assuming that it will always be me running my own app. Sure, if an exception occureed while I was running my own app, I'd probably know what to do. But if somebody else (who - god forbid - didn't know python was running the app, things might be more difficult. From CleaningTips at gmail.com Fri Jun 22 12:01:04 2007 From: CleaningTips at gmail.com (CleaningTips at gmail.com) Date: Fri, 22 Jun 2007 16:01:04 -0000 Subject: I need some cleanings tips and advice. Message-ID: <1182528064.446459.49420@n2g2000hse.googlegroups.com> Me and my buddy made a website called www.CleaningTips.com, its basically a free forum and free blog driven web site dedicated as a source people can goto to find out how to clean and remove stains from pretty much anything. Problem is, as of yet, you couldn't find out how to clean anything right now cause the site is new and no one has found it yet. We don't know enough about cleaning and tips and tricks to really fill the site. Were looking to get more useful content so that the website eventually shows up in search results. If anyone here is interested, visit www.CleaningTips.com/forum.html, and if there is anything you could add to the site please feel free to do so. Email me at CleaningTips at gmail.com if you find anything that could improve the site or if something doesn't seem to be working properly. From NikitaTheSpider at gmail.com Fri Jun 15 21:21:42 2007 From: NikitaTheSpider at gmail.com (Nikita the Spider) Date: Fri, 15 Jun 2007 21:21:42 -0400 Subject: Html parser References: <1181916716.258484.74070@p77g2000hsh.googlegroups.com> Message-ID: In article , Stephen R Laniel wrote: > On Fri, Jun 15, 2007 at 07:11:56AM -0700, HMS Surprise wrote: > > Could you recommend an html parser that works with python (jython > > 2.2)? > > I'm new here, but I believe BeautifulSoup is the canonical > answer: > http://www.crummy.com/software/BeautifulSoup/ It is, but personally I'm a fan of Connelly Barnes' htmldata module: http://oregonstate.edu/~barnesc/htmldata/ Much easier to use than BeautifulSoup IMO. -- Philip http://NikitaTheSpider.com/ Whole-site HTML validation, link checking and more From richie at entrian.com Thu Jun 21 09:32:15 2007 From: richie at entrian.com (Richie Hindle) Date: Thu, 21 Jun 2007 14:32:15 +0100 Subject: strip() 2.4.4 In-Reply-To: <20070621133006.GQ6145@slaniel-laptop.itasoftware.com> References: <1182432181.050589.5800@n2g2000hse.googlegroups.com> <20070621133006.GQ6145@slaniel-laptop.itasoftware.com> Message-ID: [Nick] > Why is there a apostrophe still at the end? [Stephen] > Is it possible that you actually have whitespace at the end > of the line? It's the newline - reading lines from a file doesn't remove the newlines: from cStringIO import StringIO DATA = """\ 'AF':'AFG':'004':'AFGHANISTAN':'Afghanistan' 'AL':'ALB':'008':'ALBANIA':'Albania' 'DZ':'DZA':'012':'ALGERIA':'Algeria' 'AS':'ASM':'016':'AMERICAN SAMOA':'American Samoa' """ f1 = StringIO(DATA) for line in f1: print repr(line.rsplit(':')[4].strip("'")) # repr shows the error # This prints: # # "Afghanistan'\n" # "Albania'\n" # "Algeria'\n" # "American Samoa'\n" # # Do this instead: f1.seek(0) for line in f1: print line.strip().rsplit(':')[4].strip("'") # This prints: # # Afghanistan # Albania # Algeria # American Samoa -- Richie Hindle richie at entrian.com From tjreedy at udel.edu Mon Jun 11 18:07:54 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 11 Jun 2007 18:07:54 -0400 Subject: Python's "only one way to do it" philosophy isn't good? References: <1181368143.874341.273140@r19g2000prf.googlegroups.com> <1181475395.749525.185520@m36g2000hse.googlegroups.com> <466d09c7$0$30852$426a74cc@news.free.fr> Message-ID: |> | > Terry Reedy wrote: |> | > > In Python, you have a choice of recursion (normal or tail) Bruno > | I'm afraid Terry is wrong here, at least if he meant that CPython had > | tail recursion *optimization*. | Terry Reedy a ?crit : | > NO!!! | > I did not mean that or imply that in any way. Bruno | I understand you didn't mean it, but since the whole point of | tail-recursion is allowing optimisation Wrong again. That is a reason, even a primary reason, for some people some of the time, but not at all the only reason anyone would ever write linear recursion in tail rather than body (my term) form. So nothing follows from this false premise. | (else tail-recursion is nothing else than a subset of recursion) So? Body-recursion (non-tail-recursion) is also nothing else than a subset of recursion. | you somehow implied it, even while that was not your intention. False in its own right. Any langauge that allow recursion allows the subset that happen to constitute tail recursion. Most do not *mandate* that compilers specially recognize and optimize that subset. So there is pragmatically no implication that the latter follows from the former. The reason I specifically mentioned tail recursion is because Prof. Sussman, who complained about There should be one-- and preferably only one --obvious way to do it. -- to quote Brother Tim accurately -- co-developed Scheme. To me, Scheme promotes tail recursion as the one true way as much or more as anything is similarly promoted in Python. That mention had nothing in itself to do with the separate issue of optimizing tail calls. What Sussman apparently missed is that Tim's main point is that there should be some rather than no obvious way to do things. The parenthetical optional secondary desiderata is just that -- optional and secondary. Terry Jan Reedy From rh00667 at gmail.com Tue Jun 12 08:09:12 2007 From: rh00667 at gmail.com (rhXX) Date: Tue, 12 Jun 2007 12:09:12 -0000 Subject: httplib / connection Message-ID: <1181650152.610857.70210@i13g2000prf.googlegroups.com> hi all, i'm using this tutorial example import httplib h = httplib.HTTP("www.python.org") h.putrequest('GET','/index.html') h.putheader('User-Agent','Lame Tutorial Code') h.putheader('Accept','text/html') h.endheaders() errcode,errmsg, headers = h.getreply() f = h.getfile() # Get file object for reading data data = f.read() f.close() but always i get this tracing error, a timeout in h.endheaders() File "ejemplo.py", line 331, in testA h.endheaders() File ".../lib/python2.4/httplib.py", line 795, in endheaders self._send_output() File ".../lib/python2.4/httplib.py", line 676, in _send_output self.send(msg) File ".../lib/python2.4/httplib.py", line 643, in send self.connect() File ".../lib/python2.4/httplib.py", line 627, in connect raise socket.error, msg socket.error: (110, 'Connection timed out') must i do something about network before???? i would appreciate ur commenst From asma61 at dsl.pipex.com Mon Jun 4 18:08:54 2007 From: asma61 at dsl.pipex.com (DaveM) Date: Mon, 04 Jun 2007 23:08:54 +0100 Subject: Who uses Python? References: <1180985830.288414.208850@q69g2000hsb.googlegroups.com> Message-ID: <203963d72d3c17g16igfrlf4pmcm6fgdsm@4ax.com> On Mon, 04 Jun 2007 12:37:10 -0700, walterbyrd wrote: >I mean other than sysadmins, programmers, and web-site developers? > >I have heard of some DBAs who use a lot of python. > >I suppose some scientists. I think python is used in bioinformatics. I >think some math and physics people use python. > >I suppose some people use python to learn "programming" in general. >Python would do well as a teaching language. > >I would think that python would be a good language for data analysis. > >Anything else? Finance? Web-analytics? SEO? Digital art? I'm a hobbyist. No, that's not right - I run a course and I learnt the language writing a program to allocate tutors and students to tutorial groups over a three day course I run. I don't know what that makes me - and, no, I don't want any helpful answers! DaveM From rajenpn at gmail.com Sun Jun 17 04:06:23 2007 From: rajenpn at gmail.com (Rajendran) Date: Sun, 17 Jun 2007 08:06:23 -0000 Subject: Database Access using pyodbc. I've a problem In-Reply-To: <1182008006.091353.194490@e9g2000prf.googlegroups.com> References: <1181997323.384882.149020@i13g2000prf.googlegroups.com> <1182008006.091353.194490@e9g2000prf.googlegroups.com> Message-ID: <1182067583.976439.180170@z28g2000prd.googlegroups.com> Hi Robert, Thanks for your response. The problem I've mentioned comes up only with the Python but not with the PHP. Is it because PHP has been integrated with Apache and Python isn't? I mean, we have included these # For PHP 5 do something like this: LoadModule php5_module "c:/php/php5apache2_2.dll" AddType application/x-httpd-php .php # configure the path to php.ini PHPIniDir "C:/php" lines in the httpd.conf for Apache to understand PHP and no corresponding lines for Python? Does this make Apache to run PHP with the permissions same as user? Don't we have this option for Python? Thanks in Advance. Rajen From bruno.42.desthuilliers at wtf.websiteburo.oops.com Fri Jun 29 05:37:31 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Fri, 29 Jun 2007 11:37:31 +0200 Subject: Collections of non-arbitrary objects ? In-Reply-To: <1183046497.377835.125290@e16g2000pri.googlegroups.com> References: <1182449993.223262.229500@z28g2000prd.googlegroups.com> <87k5twx4hf.fsf@benfinney.id.au> <1182559502.069773.321620@i38g2000prf.googlegroups.com> <87wsxvrzsj.fsf@benfinney.id.au> <1182620734.940718.196520@e16g2000pri.googlegroups.com> <467ed491$0$27132$426a34cc@news.free.fr> <1182780863.067601.89320@d30g2000prg.googlegroups.com> <46801791$0$32172$426a34cc@news.free.fr> <1182863704.364272.5950@i13g2000prf.googlegroups.com> <46812159$0$24920$426a74cc@news.free.fr> <1182961835.134162.311670@x35g2000prf.googlegroups.com> <4682ca40$0$14981$426a74cc@news.free.fr> <1183046497.377835.125290@e16g2000pri.googlegroups.com> Message-ID: <4684d2c3$0$25876$426a74cc@news.free.fr> walterbyrd a ?crit : >> Did you try to sort a tuple ? >> >> >>> (1, "aaa").sort() >> Traceback (most recent call last): >> File "", line 1, in ? >> AttributeError: 'tuple' object has no attribute 'sort' > > I can do this: > >>>> x = (3,2,1) >>>> x = tuple(sorted(list(x))) > > Which, although senseless, effectively sorts the x tuple. Err... > But, you are > right, I am not really sorting the tuple, Indeed. > I'm sorting a list, which > has been made from the tuple, then changing it back to a tuple. Exactly. You're in fact *creating* a new tuple - how you do it is somewhat irrelevant. This is certainly not the same thing as in-place sorting. From a purely practical POV, using tuples as "frozen lists" can sometimes make sens - be it for micro-optimization (tuples are cheaper than lists). But still, you'll find that in most cases(with most==almost always), tuples are used for (eventually heterogenous) data *where the order is significant* (fields in a db row, argument list, base classes lists, 2D or 3D points, etc), and can not be changed without changing the semantic of the data, while lists are used to collect (more or less) homogenous data where the order doesn't impact the semantic of the data (which is one of the reasons why list can be sorted and tuples cannot). As a matter of fact, a dict can be build from a list of (key,value) tuples - and it's obvious that the order of the elements in each tuple is significant, while the order of tuples in the list is not. HTH From harald.luessen at gmx.de Mon Jun 25 16:48:58 2007 From: harald.luessen at gmx.de (Harald Luessen) Date: Mon, 25 Jun 2007 22:48:58 +0200 Subject: Internals and complexity of types, containers and algorithms Message-ID: Hi, I am new to python and I miss some understanding of the internals of some types and containers. With my C/C++ background I hope to get some hints to chose the best data structure for my programs. Here are some questions: - Is there a brief description (not source) how the types tuple, string, list and dict are represented internally. Is a list behind the scenes just a double linked list or an array or a mixture of these things? Is a dict a tree or a hash array and what is the collision mechanism? Is the string an array with some header info? - What is the big-O complexity of the most common algorithms for these types and containers? Is it O(n), O(n*log(n)) or O(n**2)? I mean inserting, appending (front or back), finding something and so on. - The same questions for important and common library containers if you can name some. - Is this information somewhere in the web? Why is it not written in the documentation? - When I want to use a representation of a game board like chess in C/C++ I use an array[64] or bigger of int or char for the pieces. What data structure or type would be useful in Python when the performance ist most important? Is it list or string or an array from a library or what else? Harald From arkanes at gmail.com Tue Jun 12 16:26:34 2007 From: arkanes at gmail.com (Chris Mellon) Date: Tue, 12 Jun 2007 15:26:34 -0500 Subject: List sequential initialization In-Reply-To: <1181675079.553239.43010@d30g2000prg.googlegroups.com> References: <1181670619.086709.116730@g37g2000prf.googlegroups.com> <466ee02b$0$10192$9b4e6d93@newsspool4.arcor-online.net> <1181675079.553239.43010@d30g2000prg.googlegroups.com> Message-ID: <4866bea60706121326k25215c12l6a6578138d840242@mail.gmail.com> On 6/12/07, HMS Surprise wrote: > Thanks for the explaination. It didn't seem natural and from the > tutorial I read: > > A value can be assigned to several variables simultaneously: > > >>> x = y = z = 0 # Zero x, y and z > > > Maybe I infer too much.... > And yet, your answer is right there. "A value can be assigned to several variables simultaneously" When you say want a value assigned to several variables, Python doesn't assume that you actually mean you want 2 different values assigned to them. From stefan.behnel-n05pAM at web.de Wed Jun 20 04:06:57 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Wed, 20 Jun 2007 10:06:57 +0200 Subject: caseless dictionary howto ? In-Reply-To: <4dc64$46782a84$d443bb3a$4629@news.speedlinq.nl> References: <4dc64$46782a84$d443bb3a$4629@news.speedlinq.nl> Message-ID: <4678E021.9040709@web.de> Stef Mientki wrote: > I need to search a piece of text and make all words that are equal > (except their case) also equal in their case, based on the first > occurrence. > So I'm using a dictionary to store names and attributes of objects. > As as I need to search on the caseless name (so I've choosen lowercase), > My dictionairy looks like this: > > self.procs [ "serial_hw_read" ] = ( "Serial_HW_Read", "F", "++", T) I have no idea what the "F", "++", "T" means at the end (if it's some kind of flags or attributes, maybe a class to hold them would look better), but that's a good solution to the problem IMHO. Stefan From python at jayloden.com Sat Jun 23 01:22:53 2007 From: python at jayloden.com (Jay Loden) Date: Sat, 23 Jun 2007 01:22:53 -0400 Subject: high performance/threaded applications in Python - your experiences? Message-ID: <467CAE2D.7080409@jayloden.com> All, In studying Python, I have predictably run across quite a bit of talk about the GIL and threading in Python. As my day job, I work with a (mostly Java) application that is heavily threaded. As such our application takes good advantage of multiple processors and we can often scale through simply adding processing power to a server. I was hoping for some experiences that some of you on the list may have had in dealing with Python in a high performance and/or threaded environment. In essence, I'm wondering how big of a deal the GIL can be in a real-world scenario where you need to take advantage of multiple processor machines, thread pools, etc. How much does it get in the way (or not), and how difficult have you found it to architect applications for high performance? I have read a number of articles and opinions on whether or not the GIL is a good thing, and how it affects threaded performance on multiple processor machines, but what I haven't seen is experiences of people who have actually done it and reported back "it was a nightmare" or "it's no big deal" ;) Your thoughts and opinions are welcome, especially those with relevant experiences. Thanks! -Jay From cam.ac.uk at mh391.invalid Wed Jun 20 16:41:09 2007 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Wed, 20 Jun 2007 21:41:09 +0100 Subject: PEP 3107 and stronger typing (note: probably a newbie question) In-Reply-To: References: <1182369568.941307.316260@p77g2000hsh.googlegroups.com> Message-ID: Stephen R Laniel wrote: > On Wed, Jun 20, 2007 at 12:59:28PM -0700, bruno.desthuilliers at gmail.com wrote: >> Then you should use another language. > > This is what I meant about knowing how Internet discussions > go. You originally said "Before I ask anything, let me note that this is surely an old question that has inspired its share of flame wars; I'm new to Python, but not new to how Internet discussions work." In that context, there is no way that this response was a flame. I find that Pythoneers want to use the right tool for the job. This isn't always Python. It might be Perl, or OCaml, or Java, or C, or JCL. If you want static type checking, Python definitely isn't the right tool for you. If you asked Java programmers why you couldn't turn *off* Java's static type checking if you wanted to, you'd probably get a similar response. -- Michael Hoffman From joe at incomps.com Fri Jun 8 16:33:26 2007 From: joe at incomps.com (Joe) Date: Fri, 8 Jun 2007 14:33:26 -0600 Subject: Case-Insensitive Sorting of Multi-Dimensional Lists In-Reply-To: <8c7f10c60706081327p5c6acae7p8fe8d15606df9e01@mail.gmail.com> References: <020e01c7a94c$a7970750$0f01a8c0@desktop9> <8c7f10c60706080618m2fabe683i5cf4d9659471c1e1@mail.gmail.com> <02bc01c7a9e6$ad4f8330$0f01a8c0@desktop9> <8c7f10c60706081327p5c6acae7p8fe8d15606df9e01@mail.gmail.com> Message-ID: <030701c7aa0c$44ed7290$0f01a8c0@desktop9> > > Now, I would like to be able to specify which index to sort by. I am > not > > able to pass in external variables like: > > > > List.sort(key=lambda el: el[indexNumber].lower()) > > Why ever not? Sorry, I should have written back with my findings. I had run into the problem described in this email: http://mail.python.org/pipermail/python-list/2001-June/090863.html. See, I was using bare execs elsewhere in the program. It had nothing to do with the lambda, which ended up working perfectly once I fixed the exec. Thanks! Jough From etienne.hilson at gmail.com Thu Jun 7 01:58:23 2007 From: etienne.hilson at gmail.com (Etienne Hilson) Date: Thu, 7 Jun 2007 07:58:23 +0200 Subject: Why Python? In-Reply-To: <4662EEF4.4080606@gmail.com> References: <4662EEF4.4080606@gmail.com> Message-ID: <194d520c0706062258s46347d04v43f7a34e3c6f9bb9@mail.gmail.com> > > IMO Python is a powerful language and a fast-develop one. > IMO Python and java are very similar in the way that they are powerful and fast-develop one, even if java is a bit heavier to program with. But IMO the VERY goo point for python is the available graphical interfaces (Tkinter, wxPython, Pygame, ...), because I remember to have lost half of my hair trying to do a VERY simple stupid graphical application with java. my two cents :-) Etienne -- (\__/) (='.'=) Ceci est un petit lapin. Copiez/collez-le dans (")_(") votre signature pour l'aider ? dominer le monde From malaclypse2 at gmail.com Fri Jun 8 11:34:18 2007 From: malaclypse2 at gmail.com (Jerry Hill) Date: Fri, 8 Jun 2007 11:34:18 -0400 Subject: Binary In-Reply-To: <564043.51460.qm@web27904.mail.ukl.yahoo.com> References: <564043.51460.qm@web27904.mail.ukl.yahoo.com> Message-ID: <16651e80706080834r6cce073elde730d5ed7196975@mail.gmail.com> On 6/8/07, Brain Murphy wrote: > I need it to show the remainder. like remainder 1 or 0 the put all of them > in a list that is backwards. Take a look at the divmod() function. It take the numerator and denominator and returns a tuple of the quotient and remainder. For example: >>> divmod(5, 2) (2, 1) >>> divmod(6, 2) (3, 0) >>> -- Jerry From gagsl-py2 at yahoo.com.ar Mon Jun 25 14:52:58 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 25 Jun 2007 15:52:58 -0300 Subject: listing all property variables of a class instance References: <1182789455.818944.227660@g37g2000prf.googlegroups.com> Message-ID: En Mon, 25 Jun 2007 15:10:25 -0300, Marc 'BlackJack' Rintsch escribi?: > In , Jay Loden wrote: >> Neil Cerutti wrote: >>>> Is there a way to write a method that would list automatically >>>> all the variables defined as a property (say by printing their >>>> docstring and/ or their value), and only those variables? >>> >>> This is off the cuff. There's likely a better way. >>> >>> for k, v in MyClass.__dict__.iteritems(): >>> if isinstance(v, property): >>> print k, v.__doc__ >>> >> >> The only way I could get this to work was to change the way the >> properties were defined/initalized: > > That's because you iterate over the instance's `__dict__` and not over > the > *class* `__dict__` like Neil does. I would iterate over dir(MyClass) instead - only because I prefer to hide such implementation details. -- Gabriel Genellina From carsten at uniqsys.com Thu Jun 21 15:34:45 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Thu, 21 Jun 2007 15:34:45 -0400 Subject: sqlite newbie questions In-Reply-To: <1182453849.251898.127630@d30g2000prg.googlegroups.com> References: <1182453849.251898.127630@d30g2000prg.googlegroups.com> Message-ID: <1182454485.3376.127.camel@dot.uniqsys.com> On Thu, 2007-06-21 at 19:24 +0000, kf9150 at gmail.com wrote: > Hello, > > I have a sqlite database table which has a table named "Transmittal". > Before inserting a new record into the database, i'd like to perform > some checking. How do i select all records with certain value (say > "Smith") for a column (say "Last_Name")? Knowing almost nothing about > SQL, i just selected everything and process the returned list. > > cur.execute('select * from Transmittal') > records = cur.fetchall() Use a where clause not unlike the one you're using in the delete statement below. > Also, how do i delete records with certain value for centain column. I > was thining of something like > cur.execute('delete * from Transmittal where Last_Name=?', "Smith") > but the syntax it's not correct. You're close. Drop the '*' and put your parameter into a singleton tuple or one-element list: cur.execute('delete from Transmittal where Last_Name=?', ("Smith",) ) HTH, -- Carsten Haese http://informixdb.sourceforge.net From http Fri Jun 22 19:51:32 2007 From: http (Paul Rubin) Date: 22 Jun 2007 16:51:32 -0700 Subject: Portable general timestamp format, not 2038-limited References: <1182544384.709759.235300@o11g2000prd.googlegroups.com> Message-ID: <7xhcozeeez.fsf@ruckus.brouhaha.com> James Harris writes: > I have a requirement to store timestamps in a database. Simple enough > you might think but finding a suitably general format is not easy. The > specifics are > > 1) subsecond resolution - milliseconds or, preferably, more detailed > ... There are subtle issues that have been messed up many times. See: http://cr.yp.to/time.html particularly the TAI stuff for some info. From steve at holdenweb.com Wed Jun 6 21:52:37 2007 From: steve at holdenweb.com (Steve Holden) Date: Wed, 06 Jun 2007 21:52:37 -0400 Subject: =?windows-1252?Q?=93On_Your_Desktop=94=3A_the_celebrity_?= =?windows-1252?Q?posting_editorial_blog?= Message-ID: The first post comes from Ian Bicking: http://onyourdesktop.blogspot.com/ Whose desktop would /you/ like to know about? regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From carsten at uniqsys.com Fri Jun 15 10:44:50 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Fri, 15 Jun 2007 10:44:50 -0400 Subject: MySQL - Jython2.2 In-Reply-To: <1181917879.186507.176140@u2g2000hsc.googlegroups.com> References: <1181917879.186507.176140@u2g2000hsc.googlegroups.com> Message-ID: <1181918690.3387.7.camel@dot.uniqsys.com> On Fri, 2007-06-15 at 07:31 -0700, HMS Surprise wrote: > I thought I had a winner mySql-python but it require2 python 2.3-5 and > the tool I am using (maxq) is based on jython 2.2. Is there another > way that I could perform queries from python? The low version number is not your main problem. The main problem is that Jython is based on Java, and it can not use CPython modules such as MySQL-python. You'll need JDBC: http://dev.mysql.com/downloads/connector/j/5.0.html http://www.jython.org/docs/zxjdbc.html I have not tried this combination myself, so your mileage may vary, but in theory this should work. Good luck, -- Carsten Haese http://informixdb.sourceforge.net From paul at boddie.org.uk Fri Jun 1 16:28:42 2007 From: paul at boddie.org.uk (Paul Boddie) Date: Fri, 01 Jun 2007 13:28:42 -0700 Subject: subexpressions In-Reply-To: References: <1180699443.822567.256680@g4g2000hsf.googlegroups.com> Message-ID: <1180729722.156674.242990@q75g2000hsh.googlegroups.com> Steve Howell wrote: > > The compiler doesn't know the types up front, but if > you wanted to do this kind of optimization (and you > believed that 95% of x*x cases would benefit from it, > and you're willing to sacrifice performance for the 5% > of folks that overload multiply), then the compiler > could generate bytecode that set the stage for later > conditional caching of the first execution of x*x. True. > You'd then need the execution of the bytecodes at > runtime (ceval.c or something called by it) to work in > such a way that they only cache the result when side > effects are not an issue. At runtime you can reliably > detect whether something is still a virgin builtin, > correct? I've no idea, but I imagine that psyco knows whether or not it has a proper built-in number object when it generates specialised code for similar cases. > To my disclaimer, you would only undertake such an > optimization if multiplication were really, really > expensive (which I don't think is even true for floats > today), and even then you'd proceed cautiously. Indeed. Some believe that for "full Python" you can only introduce such measures at run-time, although extensive enough analysis of the code could perhaps suggest suitable specialisations in advance, as presumably demonstrated by Shed Skin. Paul From jimbomaan at gmail.com Wed Jun 13 00:54:03 2007 From: jimbomaan at gmail.com (why?) Date: Wed, 13 Jun 2007 04:54:03 -0000 Subject: for ... else ? In-Reply-To: <1181684152.300967.319390@i13g2000prf.googlegroups.com> References: <1181622331.955264.31610@i38g2000prf.googlegroups.com> <1181640889.439145.60020@g37g2000prf.googlegroups.com> <4866bea60706120641j2fa1fb09r89f937d75f5bd1b6@mail.gmail.com> <1181684152.300967.319390@i13g2000prf.googlegroups.com> Message-ID: <1181710443.125448.187160@z28g2000prd.googlegroups.com> > > > On 6/12/07, Gabriel Genellina wrote: > > >> for x in iterable: > > >> do something with x > > >> else: > > >> do something when there are no more x > > > > >> You can think the above as: > > > > >> while there are still values in iterable: > > >> do something with the next value > > >> else: > > >> do something when there are no more items @Gabriel--Hey thanx a lot! I had seen a similar 'for-else' clause somewhere else as well and i was left wondering that how an 'else' got coupled with 'for'. Anyways now am ok! This post clears a lot of doubts. From arkanes at gmail.com Fri Jun 29 10:09:43 2007 From: arkanes at gmail.com (Chris Mellon) Date: Fri, 29 Jun 2007 09:09:43 -0500 Subject: Python's "only one way to do it" philosophy isn't good? In-Reply-To: References: <7xy7i7xjl5.fsf@ruckus.brouhaha.com> Message-ID: <4866bea60706290709t1d1c29afwd093e924ead800b@mail.gmail.com> On 6/29/07, Douglas Alan wrote: > "Chris Mellon" writes: > > > You're arguing against explicit resource management with the argument > > that you don't need to manage resources. Can you not see how > > ridiculously circular this is? > > No. It is insane to leave files unclosed in Java (unless you know for > sure that your program is not going to be opening many files) because > you don't even know that the garbage collector will ever even run, and > you could easily run out of file descriptors, and hog system > resources. > > On the other hand, in Python, you can be 100% sure that your files > will be closed in a timely manner without explicitly closing them, as > long as you are safe in making certain assumptions about how your code > will be used. Such assumptions are called "preconditions", which are > an understood notion in software engineering and by me when I write > software. > Next time theres one of those "software development isn't really engineering" debates going on I'm sure that we'll be able to settle the argument by pointing out that relying on *explicitly* unreliable implementation details is defined as "engineering" by some people. From martin at see.sig.for.address Tue Jun 26 16:21:01 2007 From: martin at see.sig.for.address (Martin Gregorie) Date: Tue, 26 Jun 2007 21:21:01 +0100 Subject: Portable general timestamp format, not 2038-limited In-Reply-To: <1182836388.204373.231220@g37g2000prf.googlegroups.com> References: <1182544384.709759.235300@o11g2000prd.googlegroups.com> <20070625133843.9e25d0ab.steveo@eircom.net> <82b5l4-tvh.ln1@zoogz.gregorie.org> <7xbqf3lc7i.fsf@ruckus.brouhaha.com> <1182836388.204373.231220@g37g2000prf.googlegroups.com> Message-ID: sla29970 at gmail.com wrote: > On Jun 25, 6:46 pm, Paul Rubin wrote: >> TAI really does seem like the most absolute--if you are a user in >> orbit or on Mars, then UTC timestamps will seem pretty meaningless and >> artificial. > > TAI makes sense for clocks on the surface of the earth (at least until > ion trap clocks and picosecond intercomparison become routine, at > which point not even TAI tells what time it is for you), but clocks > off the surface of the earth tick at rates which already differ > nonlinearly from TAI by measurable amounts. > True. The first direct demonstration of relativistic time dilation was made in 1971 with three HP cesium beam atomic clocks. One stayed in the lab, while the other were shipped round the world in opposite directions on commercial jet flights. When the clocks were compared afterwards the errors in the traveling clocks agreed with theory within experimental error. See: http://hyperphysics.phy-astr.gsu.edu/hbase/relativ/airtim.html for more detail. This shows the clocks don't have to be moving at interplanetary speeds to be significantly affected. -- martin@ | Martin Gregorie gregorie. | Essex, UK org | From 2007 at jmunch.dk Sun Jun 10 07:34:03 2007 From: 2007 at jmunch.dk (Anders J. Munch) Date: Sun, 10 Jun 2007 13:34:03 +0200 Subject: Where can I suggest an enchantment for Python Zip lib? In-Reply-To: <1181287080.398800.194140@q75g2000hsh.googlegroups.com> References: <46684DB8.6080900@websafe.com> <1181287080.398800.194140@q75g2000hsh.googlegroups.com> Message-ID: <466be1c1$0$4154$ba624c82@nntp02.dk.telia.net> durumdara wrote: > Only one way I have to control this: if I modify the ZipFile module. Since you already have the desired feature implemented, why don't you submit a patch. See http://www.python.org/patches/ - Anders From justin.mailinglists at gmail.com Mon Jun 25 01:17:57 2007 From: justin.mailinglists at gmail.com (Justin Ezequiel) Date: Mon, 25 Jun 2007 05:17:57 -0000 Subject: regular expressions eliminating filenames of type foo.thumbnail.jpg In-Reply-To: <1182747645.092002.68800@x35g2000prf.googlegroups.com> References: <1182746933.413693.103860@p77g2000hsh.googlegroups.com> <1182747645.092002.68800@x35g2000prf.googlegroups.com> Message-ID: <1182748677.373396.243070@d30g2000prg.googlegroups.com> On Jun 25, 1:00 pm, Justin Ezequiel wrote: > [ p for p in os.listdir(dir) > if os.path.isfile(os.path.join(dir,p)) > and p.lower().find('.thumbnail.')==-1 ] if you really want a regexp solution, the following seems to work (?i)(? Message-ID: In , Roy Smith wrote: > In article <1180751587.951837.191480 at h2g2000hsg.googlegroups.com>, > snorble at hotmail.com wrote: >> 7. How many Z80 assembly language programmers does it take to equal >> one Python guru? > > Trick question, the Z80 was a figment of your imagination. http://en.wikipedia.org/wiki/Zilog_Z80 >> Essay: "C++ is better than C", agree or disagree? (four word maximum) > > STL compile error diagnostics. So do you agree or disagree!? ;-) Ciao, Marc 'BlackJack' Rintsch From hat at se-126.se.wtb.tue.nl Fri Jun 1 06:51:18 2007 From: hat at se-126.se.wtb.tue.nl (A.T.Hofkamp) Date: Fri, 01 Jun 2007 12:51:18 +0200 Subject: subexpressions References: Message-ID: On 2007-06-01, Sergey Dorofeev wrote: > Hello all! > > Please help, is there way to use sub-expressions in lambda? > For example, if I want to calculate sin(x^2)+cos(x^2) I must code: > lambda x: sin(x*x)+cos(x*x) > How to make x*x to be evaluated once? lambda x: (lambda y: sin(y) + cos(y))(x*x) Albert From gnewsg at gmail.com Thu Jun 14 17:03:52 2007 From: gnewsg at gmail.com (billiejoex) Date: Thu, 14 Jun 2007 14:03:52 -0700 Subject: os.path.normpath bug? In-Reply-To: References: <1181852812.831695.183610@i13g2000prf.googlegroups.com> Message-ID: <1181855032.112149.241400@n15g2000prd.googlegroups.com> On 14 Giu, 22:35, Michael Hoffman wrote: > Intentional. > > http://en.wikipedia.org/wiki/Path_(computing)#Universal_Naming_Conven... > -- > Michael Hoffman Got it. Thank you. From tcrane at REMOVETHISuiuc.edu Fri Jun 8 11:54:23 2007 From: tcrane at REMOVETHISuiuc.edu (T. Crane) Date: Fri, 08 Jun 2007 15:54:23 GMT Subject: interating over single element array References: <4Beai.13210$5j1.6184@newssvr21.news.prodigy.net> Message-ID: > >> any suggestions are appreciated, > > Yes, don't try iterating over objects that are not iterable. ;-) Ah, yes... I hadn't thought of that :) thanks, trevis > > What you *can* do is iterating over lists, tuples or other iterables with > just one element in them. Try ``a = [1]``. > > Ciao, > Marc 'BlackJack' Rintsch From Shihpin.Lin at gmail.com Sun Jun 3 20:23:10 2007 From: Shihpin.Lin at gmail.com (Shihpin) Date: Sun, 03 Jun 2007 17:23:10 -0700 Subject: example: 40286 -> 68204 Message-ID: <1180916590.000664.249810@z28g2000prd.googlegroups.com> Hi all, Is there a fuction that reverse the digits of a number? Many thanks, Shihpin Lin From sla29970 at gmail.com Tue Jun 26 17:40:03 2007 From: sla29970 at gmail.com (sla29970 at gmail.com) Date: Tue, 26 Jun 2007 21:40:03 -0000 Subject: Portable general timestamp format, not 2038-limited In-Reply-To: <7x645al8kc.fsf@ruckus.brouhaha.com> References: <1182544384.709759.235300@o11g2000prd.googlegroups.com> <20070625133843.9e25d0ab.steveo@eircom.net> <82b5l4-tvh.ln1@zoogz.gregorie.org> <7xbqf3lc7i.fsf@ruckus.brouhaha.com> <70c7l4-2gp.ln1@zoogz.gregorie.org> <7xlke6y6y1.fsf@ruckus.brouhaha.com> <7x645al8kc.fsf@ruckus.brouhaha.com> Message-ID: <1182894003.920335.317620@a26g2000pre.googlegroups.com> On Jun 26, 2:17 pm, Paul Rubin wrote: > Martin Gregorie writes: > > > Same one already given:http://cr.yp.to/proto/utctai.html > > > > Nope - you referencedleap seconds, not TAI and not that URL > > Oh whoops, I thought I put that url further up in the thread. > I remember grumbling to myself about having to look for it twice. > Maybe I'm just confused. Anyway it's pretty interesting stuff, > as is the Wikipedia article someone else linked to. Keep in mind that TAI is not legal time anywhere. It is also not practical, for the TAI now is not available until next month. >From a legal standpoint, either UTC or GMT (or both, if you read different languages in the EU documents) as kept by your national metrology lab is is the official time. Despite the way the math looks and the way the physics seems like it ought to dictate, TAI is derived from UTC, not the other way around. The national metrology labs are tasked to provide GMT or UTC as part of their charter, so that is *procedurally* the primary time scale. Also note the "discussion" link on wikipedia's TAI page before believing it too much. From JoeSalmeri at hotmail.com Mon Jun 4 07:24:55 2007 From: JoeSalmeri at hotmail.com (Joe Salmeri) Date: Mon, 4 Jun 2007 07:24:55 -0400 Subject: Python 2.5.1 broken os.stat module References: <466140A6.1090100@v.loewis.de> <-aOdnbFdroD_gP_bnZ2dnUVZ_uKknZ2d@comcast.com> <4662750b$0$29898$9b622d9e@news.freenet.de> <4662F98C.8070709@v.loewis.de> Message-ID: There is a conflict with the answers that you and Terry have given. The original issue I raised was that I Python 2.5.1 and Windows did not have the same textual represenation for a localize date. You have stood true to the statements that Python 2.5.1 is correct and that previous versions were wrong. I agree with you that Python 2.5.1 is correct which means that Windows is showing the incorrect dates. Since that point in time you and Terry have disagreed with my statements regarding timezones and DST. All dates in my below comments are the textual representation of those dates from Windows or from Python 2.5.1 For the test file created at 01/02/2007 07:00 PM. >From that date up until just before DST starts both Windows AND Python 2.5.1 will report that date as 01/02/2007 07:00 PM. Once DST starts Python 2.5.1 will still report that date as 01/02/2007 07:00 PM, however Windows will now report that date as 01/02/2007 at 08:00 PM. I agree and believe that Python 2.5.1 is reporting the correct textual representation of that timestamp, however, using *your* logic that a DST change *is a timezone change* that would mean that Python 2.5.1 is wrong and should be reporting the date 1 hour later just as Windows is reporting. You cannot have it both ways. If a DST change is the same as a timezone change then Python 2.5.1 should be reporting the dates that Windows reports. If a DST change is NOT the same as a timezone change then Python 2.5.1 should be reporting the dates that it currently is. From bignose+hates-spam at benfinney.id.au Wed Jun 13 05:59:31 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 13 Jun 2007 19:59:31 +1000 Subject: How to create a tuple quickly with list comprehension? References: Message-ID: <87ejkguqd8.fsf@benfinney.id.au> "fdu.xiaojf at gmail.com" writes: > I can use list comprehension to create list quickly. So I expected > that I can created tuple quickly with the same syntax. Nope. The list comprehension syntax creates lists. > But I found that the same syntax will get a generator, not a > tuple. Here is my example: > > In [147]: a = (i for i in range(10)) This contains no commas, so I don't know why you think it has anything to do with a tuple. Bear in mind that parentheses have nothing to do with the syntax for creating a tuple; the parentheses merely determine parsing order, and can enclose any expression. > Is there a way to create a tuple like (1, 2, 3, 4, 5, 6, 7, 8, 9) > quickly? tuple(range(1, 10)) -- \ "Know what I hate most? Rhetorical questions." -- Henry N. Camp | `\ | _o__) | Ben Finney From steve at REMOVE.THIS.cybersource.com.au Sun Jun 3 19:24:03 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Mon, 04 Jun 2007 09:24:03 +1000 Subject: subexpressions (OT: math) References: <4662675b$1_5@news.bluewin.ch> <1180890214.317409.85100@w5g2000hsg.googlegroups.com> <1180894045.538031.111610@g4g2000hsf.googlegroups.com> <1180895200.108582.313010@k79g2000hse.googlegroups.com> Message-ID: On Sun, 03 Jun 2007 11:26:40 -0700, Stebanoid at gmail.com wrote: > if you are discordant read more :P : > sine is a dimensionless value. > if we expand sine in taylor series sin(x) = x - (x^3)/6 + (x^5)/120 > etc. > you can see that sin can be dimensionless only if x is dimensionless > too. > > I am a professional physicist and a know about what I talk I am confused why you get different results for the square root of an angle depending on whether you use degrees or radians: sqrt(25?) = 5? = 0.087266462599716474 radians sqrt(25*pi/180) = 0.66055454960100179 radians If angles are dimensionless numbers, then: degrees_to_radians(sqrt(25?)) should equal sqrt(degrees_to_radians(25?)) but they don't. How do you interpret the square root of an angle? What does it mean? -- Steven. From benedict.verheyen at gmail.com Thu Jun 14 05:39:08 2007 From: benedict.verheyen at gmail.com (Benedict Verheyen) Date: Thu, 14 Jun 2007 11:39:08 +0200 Subject: for web application development In-Reply-To: <1181812584.392929.232670@o11g2000prd.googlegroups.com> References: <1181812584.392929.232670@o11g2000prd.googlegroups.com> Message-ID: james_027 schreef: > hi everyone, > > I am very new to python, I am almost done learning the python language > enough that I can start learning developing web app in python. I have > gone thru many research and I still say that I will want to develop > web app in python. Although some says php should be better since the > language is made for the web compare to python. In the point of view > of rails, they say that their framework is really easy and best for > web app. > > My problem is looking for a web framework for python, that could > provide a natural way of developing web app. I am avoiding to learn > template language as much as possible. > > Any advice will be greatly appreciated. > > THanks > james I use Django and it's easy to use. http://www.djangoproject.com/ Regards, Benedict From gandalf at shopzeus.com Tue Jun 26 16:37:16 2007 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Tue, 26 Jun 2007 22:37:16 +0200 Subject: Non-blocking keyboard read In-Reply-To: <1182335402.853626.72150@n60g2000hse.googlegroups.com> References: <1182335402.853626.72150@n60g2000hse.googlegroups.com> Message-ID: <468178FC.8000706@shopzeus.com> pinkfloydhomer at gmail.com wrote: > I am writing a curses application, but the getch() does not seem to > give me all I want. Of course, if I press "d", it returns an ord("d") > and so on. But I want to be able to detect whether alt, shift or ctrl > has been pressed also. Shift is normally covered by returning an > uppercase character instead and ctrl seems to return control codes (as > is normal, I guess), but alt I can't detect with getch, it seems. > > Preferably, I would like one of two things: > > 1) Having a getch() (or other function) that returns a code like now, > but with different codes depending on the status of the ctrl, alt or > shift keys, for instance by setting higher bits or something. Just as > long as I can differentiate between "d", "D", ctrl+"d", alt+"d", shift > +"d" and maybe ctrl+alt+"d" and ctrl+shift+"d" etc. > You can try to combine select.select with sys.stdin. I have never tried this, but it is my platform independent idea. > 2) Having a way to read the keyboard status at any given time, for > instance just reading a dictionary (or whatever) of bool for each key. > So that key[KEY_D] == true when d is being pressed, and key[LEFT_ALT] > == true when left alt is being pressed etc. > I'm affraid this is not possible from the base Python installation. You need to use external modules, but there are many. E.g. under windows, you can use the win32 extensions. Under X window, probably you can use a python/gnome module. I would also look at PyGame, I guess it has functions that can read the keyboard state. (Never tried...) I'm not sure about console mode programs though. > 1) can of course be created from 2) which is lower level, so I would > prefer 1) to save me some work. > > Also, are there problems with using a non-curses method of reading > keyboard input, within a curses application? > Under unix, the non-curses-method will end up in reading a file. The curses-method will do exactly the same. Problems will come out when you 1. use something at low level. For example, modifying the internal keyboard buffer... 2. try to read from different threads/processes (why would you do that?) Best, Laszlo From aleax at mac.com Tue Jun 19 10:15:32 2007 From: aleax at mac.com (Alex Martelli) Date: Tue, 19 Jun 2007 07:15:32 -0700 Subject: Does altering a private member decouple the property's value? References: <87r6o8z5m6.fsf@benfinney.id.au> Message-ID: <1hzy0u3.16xvizo1egcxk8N%aleax@mac.com> Ben Finney wrote: > "Ethan Kennerly" writes: > > > I really like properties for readonly attributes, > > Python doesn't have "readonly attributes", Many Python types do, e.g.: >>> def f(): pass ... >>> def g(): pass ... >>> f.func_name = 'zap' >>> f.func_code = g.func_code >>> f >>> f.func_code ", line 1> >>> f.func_closure = g.func_closure Traceback (most recent call last): File "", line 1, in TypeError: readonly attribute i.e., you can reassign some of f's attributes (such as its name and code) but others (such as its closure) are readonly (as the TypeError's message says) so you cannot reassign those. It makes just as much sense for user-coded types (aka classes) to have some r/w attributes and others that are readonly, as it does for builtin types -- and properties are often the simplest way to accomplish that. > and to attempt to use > properties for that purpose will only lead to confusion. I disagree -- a property is a great way to implement readonly attributes, as long as you're using a new-style class of course. class Rectangle(object): def __init__(self, w, h): self.w = w self.h = h area = property(lambda self: self.w * self.h) No confusion here -- given a Rectangle instance r, you can both read and write (reassign) r.w and r.h, but r.area is readonly (can't be set): >>> r = Rectangle(12, 34) >>> r.area 408 >>> r.h = 10 >>> r.area 120 >>> r.area = 144 Traceback (most recent call last): File "", line 1, in AttributeError: can't set attribute Alex From nogradi at gmail.com Wed Jun 13 15:32:29 2007 From: nogradi at gmail.com (Daniel Nogradi) Date: Wed, 13 Jun 2007 21:32:29 +0200 Subject: Goto In-Reply-To: <1181762459.749538.151730@z28g2000prd.googlegroups.com> References: <1181762459.749538.151730@z28g2000prd.googlegroups.com> Message-ID: <5f56302b0706131232k13b30a1bn3564cb43e096eb7@mail.gmail.com> > How does one effect a goto in python? I only want to use it for debug. > I dasn't slap an "if" clause around the portion to dummy out, the > indentation police will nab me. http://entrian.com/goto/ From vsaini at cybage.com Tue Jun 19 06:08:35 2007 From: vsaini at cybage.com (Vikas Saini) Date: Tue, 19 Jun 2007 15:38:35 +0530 Subject: Execute script on remote computer Message-ID: <0B5158DBDB894441A80F5928175235330589F243@postoffice.cybage.com> I am trying to run the agent on one machine that will execute the script of a remote machine. Could you please help me in this regards. vikas "Legal Disclaimer: This electronic message and all contents contain information from Cybage Software Private Limited which may be privileged, confidential, or otherwise protected from disclosure. The information is intended to be for the addressee(s) only. If you are not an addressee, any disclosure, copy, distribution, or use of the contents of this message is strictly prohibited. If you have received this electronic message in error please notify the sender by reply e-mail to and destroy the original message and all copies. Cybage has taken every reasonable precaution to minimize the risk of malicious content in the mail, but is not liable for any damage you may sustain as a result of any malicious content in this e-mail. You should carry out your own malicious content checks before opening the e-mail or attachment." www.cybage.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From rappavu at gmail.com Thu Jun 28 13:08:33 2007 From: rappavu at gmail.com (Rajendran Appavu) Date: Thu, 28 Jun 2007 22:38:33 +0530 Subject: Tkinter pack_forget() and destroy() In-Reply-To: References: Message-ID: <3634b0c20706281008x589f072ag7a7c0948d02a55e@mail.gmail.com> I asked just to be sure. Thank you. Rajendran. On 6/28/07, Eric Brunel wrote: > On Thu, 28 Jun 2007 07:45:08 +0200, Rajendran Appavu > wrote: > > > When I am done with a widget that is packed in a Frame, is it safe to > > call destroy() method on the widget after calling its pack_forget() or > > grid_forget() method? > > Since I do that all the time, I'd say yes... Did you have a problem? Or do > you ask just to be sure? > > HTH > -- > python -c "print ''.join([chr(154 - ord(c)) for c in > 'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])" > -- > http://mail.python.org/mailman/listinfo/python-list > -- Thanks, Rajendran. From notbob at nothome.com Tue Jun 26 10:26:25 2007 From: notbob at nothome.com (notbob) Date: Tue, 26 Jun 2007 09:26:25 -0500 Subject: The Modernization of Emacs: terminology buffer and keybinding References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182272495.990807.99110@a26g2000pre.googlegroups.com> <87tzt3ihev.fsf@kobe.laptop> <1182370216.961241.6960@n60g2000hse.googlegroups.com> <85zm2ufjpb.fsf@lola.goethe.zz> <1182372592.803332.288260@u2g2000hsc.googlegroups.com> <1182549094.366282.286740@m37g2000prh.googlegroups.com> <877iprhos9.fsf@kobe.laptop> Message-ID: On 2007-06-25, Giorgos Keramidas wrote: > X11 interface. I don't see why Notepad is special in any way here. It's not. I discovered, quite by accident, wordpad is the superior text editor in windows. It even properly formats those cryptic brag pages crackers put in cracked software. nb From gagsl-py2 at yahoo.com.ar Thu Jun 7 14:21:19 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 07 Jun 2007 15:21:19 -0300 Subject: TLSAbruptCloseError References: <000d01c7a796$23691250$6a3b36f0$@edu> Message-ID: En Tue, 05 Jun 2007 14:22:48 -0300, Todd Hopfinger escribi?: > I am using TLS Lite and J2ME SecureConnection for the purposes of > encrypting > traffic to/from a Java Midlet client and a multithreaded Python server. > However, I encounter a TLSAbruptCloseError. I have tried to determine the > cause of the exception to no avail. I understand that it has to do with > close_notify alerts. My abbreviated code follows. > > > // Server > > > def sslSockRecv(conn, num): > > data = '' > > while len(data) < num: > > data = conn.recv(num - len(data)) # > TLSAbruptCloseError thrown here > > if len(data) == 0: > > raise NotEnoughBytes > ('Too > few bytes from client. Expected ' + str(num) + '; got ' + str(len(data)), > num, len(data)) > > return data Without much analysis, shouldn't be: data += conn.recv(num - len(data)) or something like that? Else you are discarding the previously received data. -- Gabriel Genellina From mark.dufour at gmail.com Fri Jun 29 06:48:00 2007 From: mark.dufour at gmail.com (Mark Dufour) Date: Fri, 29 Jun 2007 12:48:00 +0200 Subject: Shed Skin Python-to-C++ Compiler 0.0.21, Help needed In-Reply-To: <8180ef690703310255q55572efaqc512b968504e2c1b@mail.gmail.com> References: <8180ef690703310255q55572efaqc512b968504e2c1b@mail.gmail.com> Message-ID: <8180ef690706290348m4418d226l482e9a36474b3697@mail.gmail.com> Hi all, I have just released version 0.0.22 of Shed Skin, an experimental Python-to-C++ compiler. Among other things, it has the exciting new feature of being able to generate (simple, for now) extension modules, so it's much easier to compile parts of a program and use them (by just importing them). Here's the complete changelog: -support for generating simple extension modules (linux/windows; see README) -dos text format fix (long overdue) -improved detection of dynamic types (avoid hanging on them) -improved overloading (__nonzero__, __int__, __abs__ etc.) -add str(ing).{capitalize, capwords, swapcase, center, ato*) -fix string.maketrans -several other minor bug fixes For more details about Shed Skin and a collection of 27 programs, at a total of about 7,000 lines, that it can compile (resulting in an average speedup of about 39 times over CPython and 11 times over Psyco on my computer), please visit the homepage at: http://mark.dufour.googlepages.com I could really use some help in pushing Shed Skin forward. Please try the latest release and send in bug reports, or join the project via the homepage. Thanks, Mark Dufour. On 3/31/07, Mark Dufour wrote: > Hi all, > > I have recently released version 0.0.20 and 0.0.21 of Shed Skin, an > optimizing Python-to-C++ compiler. Shed Skin allows for translation of > pure (unmodified), implicitly statically typed Python programs into > optimized C++, and hence, highly optimized machine language. Besides > many bug fixes and optimizations, these releases add the following > changes: > > -support for 'bisect', 'collections.deque' and 'string.maketrans' > -improved 'copy' support > -support for 'try, else' construction > -improved error checking for dynamic types > -printing of floats is now much closer to CPython > > For more details about Shed Skin and a collection of 27 programs, at a > total of about 7,000 lines, that it can compile (resulting in an > average speedup of about 39 times over CPython and 11 times over Psyco > on my computer), please visit the homepage at: > > http://mark.dufour.googlepages.com > > I could really use more help it pushing Shed Skin further. Simple ways > to help out, but that can save me lots of time, are to find smallish > code fragments that Shed Skin currently breaks on, and to help > improve/optimize the (C++) builtins and core libraries. I'm also > hoping someone else would like to deal with integration with CPython > (so Shed Skin can generate extension modules, and it becomes easier to > use 'arbitrary' external CPython modules such as 're' and 'pygame'.) > Finally, there may be some interesting Master's thesis subjects in > improving Shed Skin, such as transforming heap allocation into stack- > and static preallocation, where possible, to bring performance even > closer to manual C++. Please let me know if you are interested in > helping out, and/or join the Shed Skin mailing list. > > > Thanks! > Mark Dufour. > -- > "One of my most productive days was throwing away 1000 lines of code" > - Ken Thompson > Mark Dufour. -- "One of my most productive days was throwing away 1000 lines of code" - Ken Thompson From james.harris.1 at googlemail.com Sat Jun 23 16:37:14 2007 From: james.harris.1 at googlemail.com (James Harris) Date: Sat, 23 Jun 2007 13:37:14 -0700 Subject: Portable general timestamp format, not 2038-limited In-Reply-To: <1182552560.194980.297550@z28g2000prd.googlegroups.com> References: <1182544384.709759.235300@o11g2000prd.googlegroups.com> <1182552560.194980.297550@z28g2000prd.googlegroups.com> Message-ID: <1182631034.645474.14430@q75g2000hsh.googlegroups.com> On 22 Jun, 23:49, Roger Miller wrote: ... > My rule of thumb in situations like this is "When in doubt store it as > text". The one format I am pretty sure we will still be able to deal > with in 2039. Interesting. I hadn't thought about using text. It would add to the storage a bit as each record is otherwise quite short. But this sounds like a good option and may help - at least while debugging - to see the raw date and time as digits. I will consider using this, perhaps as yyyymmddhhmmssttt. From saint.infidel at gmail.com Mon Jun 11 18:51:24 2007 From: saint.infidel at gmail.com (infidel) Date: Mon, 11 Jun 2007 15:51:24 -0700 Subject: SimplePrograms challenge In-Reply-To: References: Message-ID: <1181602284.131343.145200@i38g2000prf.googlegroups.com> # reading CSV files, tuple-unpacking import csv #pacific.csv contains: #1,CA,California #2,AK,Alaska #3,OR,Oregon #4,WA,Washington #5,HI,Hawaii reader = csv.reader(open('pacific.csv')) for id, abbr, name in reader: print '%s is abbreviated: "%s"' % (name, abbr) From george.sakkis at gmail.com Mon Jun 11 09:38:08 2007 From: george.sakkis at gmail.com (George Sakkis) Date: Mon, 11 Jun 2007 13:38:08 -0000 Subject: Postpone creation of attributes until needed In-Reply-To: <1181564855.890242.116840@m36g2000hse.googlegroups.com> References: <1181553891.447344.109390@g4g2000hsf.googlegroups.com> <1181559496.911368.219210@p77g2000hsh.googlegroups.com> <1181564855.890242.116840@m36g2000hse.googlegroups.com> Message-ID: <1181569088.048872.254700@m36g2000hse.googlegroups.com> On Jun 11, 8:27 am, Frank Millman wrote: > On Jun 11, 1:56 pm, Steven D'Aprano > > wrote: > > > Unless you have thousands and thousands of instances, __slots__ is almost > > certainly not the answer. __slots__ is an optimization to minimize the > > size of each instance. The fact that it prevents the creation of new > > attributes is a side-effect. > > Understood - I am getting there slowly. > > I now have the following - > > >>> class A(object): > > ... def __init__(self,x,y): > ... self.x = x > ... self.y = y > ... def __getattr__(self,name): > ... print 'getattr',name > ... self.compute() > ... return self.__dict__[name] > ... def compute(self): # compute all missing attributes > ... self.__dict__['z'] = self.x * self.y > [there could be many of these] > > >>> a = A(3,4) > >>> a.x > 3 > >>> a.y > 4 > >>> a.z > > getattr z > 12>>> a.z > 12 > >>> a.q > > KeyError: 'q' > > The only problem with this is that it raises KeyError instead of the > expected AttributeError. > > > > > You haven't told us what the 'compute' method is. > > > Or if you have, I missed it. > > Sorry - I made it more explicit above. It is the method that sets up > all the missing attributes. No matter which attribute is referenced > first, 'compute' sets up all of them, so they are all available for > any future reference. > > To be honest, it feels neater than setting up a property for each > attribute. I don't see why this all-or-nothing approach is neater; what if you have a hundred expensive computed attributes but you just need one ? Unless you know this never happens in your specific situation because all missing attributes are tightly coupled, properties are a better way to go. The boilerplate code can be minimal too with an appropriate decorator, something like: class A(object): def __init__(self,x,y): self.x = x self.y = y @cachedproperty def z(self): return self.x * self.y where cachedproperty is def cachedproperty(func): name = '__' + func.__name__ def wrapper(self): try: return getattr(self, name) except AttributeError: # raised only the first time value = func(self) setattr(self, name, value) return value return property(wrapper) HTH, George From Squzer at gmail.com Mon Jun 18 02:15:50 2007 From: Squzer at gmail.com (Squzer Crawler) Date: Sun, 17 Jun 2007 23:15:50 -0700 Subject: Memory problem with Python In-Reply-To: <1182146807.758384.301000@j4g2000prf.googlegroups.com> References: <1182138694.632692.17590@x35g2000prf.googlegroups.com> <1182146807.758384.301000@j4g2000prf.googlegroups.com> Message-ID: <1182147350.690466.163980@d30g2000prg.googlegroups.com> On Jun 18, 11:06 am, "sor... at gmail.com" wrote: > On Jun 17, 8:51 pm, Squzer Crawler wrote: > > > i am developing distributed environment in my college using Python. I > > am using therads in client for downloading wepages. Even though i am > > reusing the thread, memory usage get increased. I don know why.? I am > > using BerkelyDB for URLQueue, BeautifulShop for Parsing the webpages. > > Isn't the increased memory resulted from storing the already > processed pages? > > Look first at all places where your code instantiates new > objects - and make sure you don't keep references to such objects that > are not needed anymore. > > Also, reusing threads has nothing to do with saving memory - but > with saving on thread creation time, if I understand your problem > description. what about the cyclic reference.. can i use GC in my program.. if so, please tell me how to implement.. i am calling the gc.collect() at the enf of the fetching.. Will it reduce my program speed. Else in which way i can call it..? please tell me........ From nszabolcs at gmail.com Thu Jun 7 14:49:54 2007 From: nszabolcs at gmail.com (Szabolcs Nagy) Date: Thu, 07 Jun 2007 11:49:54 -0700 Subject: url to image In-Reply-To: <1181226789.660163.49290@q75g2000hsh.googlegroups.com> References: <1181226789.660163.49290@q75g2000hsh.googlegroups.com> Message-ID: <1181242194.662583.196040@g4g2000hsf.googlegroups.com> sono... at gmail.com wrote: > just wondering are there any snippets out there where you can convert > a url to an image using python you mean render a webpage as an image? does not sound a simple task maybe you can use oss web rendering engines like gecco, khtml or webcore From S.Mientki-nospam at mailbox.kun.nl Sat Jun 2 04:16:17 2007 From: S.Mientki-nospam at mailbox.kun.nl (Stef Mientki) Date: Sat, 02 Jun 2007 10:16:17 +0200 Subject: subexpressions In-Reply-To: References: Message-ID: <9120$46612665$d443bb3a$31035@news.speedlinq.nl> > > > Check the two alternatives: > > def f(x): > y = x*x > return sin(y) + cos(y) > > 44 key presses, including tabs and newlines and a blank line after the > function, but excluding counting the shift key separately. > > lambda x: (lambda y: sin(y) + cos(y))(x*x) > > 42 key presses. > > Apart from the extremely minor issue of "namespace pollution", I think > that speaks for itself. and now I've only 60 lines on my screen, so what about def f(x): y = x*x; return sin(y)+cos(y); cheers, Stef Mientki From xah at xahlee.org Tue Jun 19 13:02:44 2007 From: xah at xahlee.org (Xah Lee) Date: Tue, 19 Jun 2007 10:02:44 -0700 Subject: The Modernization of Emacs: not dumb down In-Reply-To: <1182093200.598418.218620@e9g2000prf.googlegroups.com> References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> Message-ID: <1182272564.002509.186650@i13g2000prf.googlegroups.com> Here are some Frequently Asked Questions about The Modernization of Emacs. They are slightly lengthy, so i've separated each item per post. The whole article can be found at http://xahlee.org/emacs/modernization.html ------------ Q: Why should emacs want to be popular and why should emacs change to conform the majority? We don't want emacs to be popular. We want people to adopt emacs, not emacs adopting people. A: This attitude has plagued unix and computer geekers for decades. In the early 1990s (DOS and unix), tech geekers would sneer at graphical menus and mouse, with hordes of reasons how pure text interface, the command line, and or keyboard operations are sufficient and superior than graphical user interface or using a mouse. This seems ridiculous today, but such online forum messages are common. The reason for these type of attitude, is almost never a sensible alternative view about the topic in discussion, but a show of machismo and superiority complex. (perhaps more than 95% of online computing forum users are males, and majority of them are aged under 25.) The person who utters such opinion, made sure in the way he writes that he is a expert in the ?more difficult to use? method or tools and would prefer things not to be ?dumbed down?. It is silly to retort ?Why should emacs want to be popular??. It is like asking ?why do you want to live longer?? when someone is picky about healthy food, or ?why should you want to look beautiful?? when someone dresses up. We want to improve software, not taking the attitude of ?we are more complex and unique and superior and we want to keep dummies out?. In software design, occasionally we are tied down with a design decision, such that it has a popular vs elegant aspect. For example, suppose we are designing a set of keyboard shortcuts for emacs and we are faced the question of whether to keep the copy/paste/undo/open etc with the conventional C/V/Z/O etc keystrokes. Or, we can choose to sacrifice user's familiarity of conventions but obtain a keyboard shortcut set that is in some way more consistent, extensible, or otherwise technically better. If a design decision comes down to a pure popularity vs elegance and everything else equal, then the decision might be based on our philosophical dispositions or the software creator's ultimate goal. However, it is not proper to pigeon-hole design issues into popularity vs elegance. Xah xah at xahlee.org ? http://xahlee.org/ From moranar at gmail.com Tue Jun 26 02:01:30 2007 From: moranar at gmail.com (Adriano Varoli Piazza) Date: Mon, 25 Jun 2007 23:01:30 -0700 Subject: The Modernization of Emacs: terminology buffer and keybinding In-Reply-To: <1182811109.258156.306150@k79g2000hse.googlegroups.com> References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182547318.325617.16370@o11g2000prd.googlegroups.com> <1182657564.912472.55570@g4g2000hsf.googlegroups.com> <5eaptcF378d21U3@mid.individual.net> <1182811109.258156.306150@k79g2000hse.googlegroups.com> Message-ID: <1182837690.585067.165060@p77g2000hsh.googlegroups.com> Twisted wrote: > With the latest stuff like Ubuntu, you're pretty much right ... until > something goes wrong. Windows has . [...] > Linux has ... the > command line, or worse a GRUB or fsck prompt at startup. No access to > accessible, easy to browse help right when you need it most. I suppose you never used Ubuntu's disc for anything but installing or reformatting either, but that doesn't mean it's the only thing that can be done with it. You can boot with it, have a working net connection (or create it) and solve many problems in the comfort of the full GUI, and with all the help available from the web. As for the available help on Windows, I didn't know Windows Safe mode let you connect to the Intertubes, or that its help was of any help in those situations. Really, if you have no idea, it's ok to refrain from posting. -- Saludos Adriano From jim.hefferon at gmail.com Thu Jun 7 15:58:23 2007 From: jim.hefferon at gmail.com (Jim) Date: Thu, 07 Jun 2007 12:58:23 -0700 Subject: subprocess call acts differently than command line call? In-Reply-To: <87myzbobvl.fsf@merkury.smsnet.pl> References: <1181221850.923908.178800@q75g2000hsh.googlegroups.com> <87myzbobvl.fsf@merkury.smsnet.pl> Message-ID: <1181246303.692177.203710@q69g2000hsb.googlegroups.com> On Jun 7, 2:30 pm, Rob Wolfe wrote: > That's really strange. Have you got only *one* version of ``file`` > program on your machine? Thank you, Rob. I thought I had that kind of thing covered in specifying the -m but obviously there was something I wasn't getting, and you found it. Hope I can return the favor sometime, Jim From nagle at animats.com Fri Jun 8 15:33:46 2007 From: nagle at animats.com (John Nagle) Date: Fri, 08 Jun 2007 19:33:46 GMT Subject: Verify server certificate in HTTPS transaction In-Reply-To: <4667cbfd$0$29664$afc38c87@news.optusnet.com.au> References: <4667cbfd$0$29664$afc38c87@news.optusnet.com.au> Message-ID: I struggled with that months ago. The SSL library that ships with Python is primitive, but M2Crypto can do that. M2Crypto will actually verify the certificate chain. The documentation is weak, it's hard to build, and there are bugs, but it's the best Python has right now. John Nagle Hamish Moffatt wrote: > Hi, > I'm fetching some files over HTTPS from Python and I want to verify the > server certificate. (Not just the name etc provided in certificate.) > > How can I get access to this information? > > urllib2 doesn't seem to provide it. Even a raw SSL socket only appears > to provide access to the CN, OU etc in string form (not the raw > certificate). > > I tried pycurl, which allows you to setopt(pycurl.SSL_VERIFYPEER) and > VERIFYHOST, but the getinfo(pycurl.SSL_VERIFYRESULT) call always returns > 0. Perhaps it's unimplememented? > > I couldn't get the M2Crypto API documentation to generate; perhaps it > allows it. > > TLS Lite on to of M2Crypto? Something else again? > > > Thanks > Hamish From kyosohma at gmail.com Sat Jun 9 11:34:51 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Sat, 09 Jun 2007 15:34:51 -0000 Subject: Repository - file scanner In-Reply-To: <1181331239.609059.320740@g4g2000hsf.googlegroups.com> References: <1181331239.609059.320740@g4g2000hsf.googlegroups.com> Message-ID: <1181403291.227375.220560@g4g2000hsf.googlegroups.com> On Jun 8, 2:33 pm, HMS Surprise wrote: > Greetings, > > Could someone point my muddled head at a/the python repository. I know > that one exists but cannot find it again. In particular I am looking > for a standalone search tool that given a path searches files for a > text string. > > Thanks, > > jvh Search for text in a file, from O'Reilly's "Learning Python" book: http://www.oreilly.com/catalog/lpython/chapter/ch09.html Search for files given a path (or paths) and some text to search for: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52224 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/189973 http://www.python.org/search/hypermail/python-1994q2/0116.html The Python repository (I think): http://svn.python.org/ Mike From steve at holdenweb.com Sat Jun 16 21:42:11 2007 From: steve at holdenweb.com (Steve Holden) Date: Sat, 16 Jun 2007 21:42:11 -0400 Subject: Looking for a wxPython GUI builder In-Reply-To: References: Message-ID: hg wrote: > Dick Moores wrote: > >> How about SPE? >> >> Any others? >> >> And which ones do people >> actually use? Commercial or Freeware. >> >> Thanks, >> >> Dick Moores > > > I use wxDesigner: http://www.roebling.de/ > > hg > I've used both BoaConstructor and wxDesigner - this latter product I am still using happily after three years. However I would encourage people without much windowing experience to consider Dabo seriously. Its developers have gone to a lot of trouble to iron out inconsistencies and provide a rational GUI model. Reportedly many people happily use Dabo solely to build GUIs, even though it's actually a three-tier application development framework. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From hamish at cloud.net.au Thu Jun 7 05:12:29 2007 From: hamish at cloud.net.au (Hamish Moffatt) Date: Thu, 07 Jun 2007 19:12:29 +1000 Subject: Verify server certificate in HTTPS transaction Message-ID: <4667cbfd$0$29664$afc38c87@news.optusnet.com.au> Hi, I'm fetching some files over HTTPS from Python and I want to verify the server certificate. (Not just the name etc provided in certificate.) How can I get access to this information? urllib2 doesn't seem to provide it. Even a raw SSL socket only appears to provide access to the CN, OU etc in string form (not the raw certificate). I tried pycurl, which allows you to setopt(pycurl.SSL_VERIFYPEER) and VERIFYHOST, but the getinfo(pycurl.SSL_VERIFYRESULT) call always returns 0. Perhaps it's unimplememented? I couldn't get the M2Crypto API documentation to generate; perhaps it allows it. TLS Lite on to of M2Crypto? Something else again? Thanks Hamish From claird at lairds.us Wed Jun 20 09:40:21 2007 From: claird at lairds.us (Cameron Laird) Date: Wed, 20 Jun 2007 13:40:21 +0000 Subject: DFW Pythoneers Meeting THIS Saturday References: <5dsmh6F35u7ubU1@mid.uni-berlin.de> Message-ID: <5bnnk4-db4.ln1@lairds.us> In article <5dsmh6F35u7ubU1 at mid.uni-berlin.de>, Diez B. Roggisch wrote: >Joe Riopel wrote: > >>> Precisely what? You complained that the OP didn't provide the location >>> of the event, which he did. >> >> Well, where is DFW? > >Google, first hit: > >The Dallas Ft. Worth Pythoneers > >They even have their own website. So - what's the fuss about? The BayPIGgies >also announce their meetings here. I don't mind, even though Berlin is >about 10-12 hours away on a jet-plane. . . . The upset surprises me, too. I appreciate people who esteem Usenet enough to help "police" specific newsgroups, discouraging traffic in marginal content best handled elsewhere. On the other hand, comp.lang.python has a tradition of productive announcements of local events, "DFW" is both *very* meaningful to the target audience, and, as noted, 'bout as easy to decipher with the help of Google as anything can be. Beyond all that, there's particular value in announcements like this because they *are* of regional, rather than local, significance. By that I mean I know of several cases where Pythoneers from somewhere else in the US (or even, in a couple of cases, other countries) have been traveling, and found it possible to schedule a visit with a local interest group. That's neat! Dallas gets a lot of traffic because it's an airline hub, and close moreover to fellow computing-industry centers in Austin and Houston (and, to a lesser extent, San Antonio and El Paso). From software at ginstrom.com Mon Jun 4 18:52:48 2007 From: software at ginstrom.com (Ryan Ginstrom) Date: Tue, 5 Jun 2007 07:52:48 +0900 Subject: Python, Dutch, English, Chinese, Japanese, etc. In-Reply-To: <206026.47204.qm@web33513.mail.mud.yahoo.com> Message-ID: <20070604225204957.RCYM.13519.emta104.odn.ne.jp@mta104.odn.ne.jp> > On Behalf Of Steve Howell > Asia: > > Python should be *completely* internationalized for > Mandarin, Japanese, and possibly Hindi and Korean. > Not just identifiers. I'm talking the entire language, > keywords and all. I am a Japanese-to-English translator in my day job, and live in Japan. I can say with confidence that most Japanese programmers do not want localized keywords. Note that Yukihiro "Matz" Matsumoto created Ruby with English(-styled) keywords. One reason for preferring ASCII keywords and variable names is that typing Japanese requires the use of a front-end processor (FEP), which considerably slows and complicates typing output. One English-to-Japanese translator I know finds it quicker to write his Japanese translations by hand, and have his assistant type them (he types reasonably well in English). Additionally, most Japanese programmers would probably prefer their programs to be accessible outside Japan, and poorly named variables are a much lower barrier to understanding than Japanese would be. Regards, Ryan Ginstrom From kareta at web.de Mon Jun 18 08:13:16 2007 From: kareta at web.de (Juergen Kareta) Date: Mon, 18 Jun 2007 14:13:16 +0200 Subject: fetching text from the screen Message-ID: <5dnbq8F341tilU1@mid.individual.net> Hello list, I'm thinking about a python script which fetch some text from the screen independent of what application provides the text on the screen. In this regard it should be similar to the babylon software: www.babylon.com Here my thoughts: 1) getting the mouse position 2) calculate a adequate rectangle around the mouse position 3) fetch the screen content in this rectangle 4) use a OCR library to get the text out of 3) 5) do something usefull with it. Has someone experiences with this task ? Is this a good roadmap or could someone think of a better way? Which OCR library shoud I use ? Found tesseract-ocr (linux, windows) and simpleOCR (bad, only windows (activeX). Thanks in advance for your replays. J?rgen From lucaberto at libero.it Tue Jun 19 12:26:23 2007 From: lucaberto at libero.it (luca72) Date: Tue, 19 Jun 2007 09:26:23 -0700 Subject: ni pci-6010 Analog Input Multifunction DAQ Message-ID: <1182270383.373490.150520@e9g2000prf.googlegroups.com> Hello there is someone that have experience with the ni-pci-6010 Analog Input Multifunction DAQ and python? From kwutzke at web.de Thu Jun 21 07:44:39 2007 From: kwutzke at web.de (Karsten Wutzke) Date: Thu, 21 Jun 2007 04:44:39 -0700 Subject: The Modernization of Emacs In-Reply-To: <1182093200.598418.218620@e9g2000prf.googlegroups.com> References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> Message-ID: <1182426279.720855.246350@u2g2000hsc.googlegroups.com> On 17 Jun., 17:13, Xah Lee wrote: Yaawn! > Xah > x... at xahlee.org > ?http://xahlee.org/ Hmm I just had to think about the C64/Amiga etc. game "California Games"... The game displayed a comment when the player broke his neck the 13th time when BMXing: "Geek of the week!" Karsten From showell30 at yahoo.com Mon Jun 4 08:26:06 2007 From: showell30 at yahoo.com (Steve Howell) Date: Mon, 4 Jun 2007 05:26:06 -0700 (PDT) Subject: Python, Dutch, English, Chinese, Japanese, etc. In-Reply-To: <1180958764.491893.130160@h2g2000hsg.googlegroups.com> Message-ID: <518361.84370.qm@web33505.mail.mud.yahoo.com> --- montyphyton at gmail.com wrote: > > M?ta-MCI je napisao/la: > > Et le klingon ? > > > > Please, don't forget klingons > > SVP, n'oubliez pas les klingons > > > > ;o) > > je pense que le klingon utilise les mems lettres > comme l'anglais > Oui, mais en tous case, dans l'Enterprise on doit utiliser le Java, a cause du patron d'une chevelure pointu. ____________________________________________________________________________________ Park yourself in front of a world of choices in alternative vehicles. Visit the Yahoo! Auto Green Center. http://autos.yahoo.com/green_center/ From alextabone at gmail.com Mon Jun 18 05:55:15 2007 From: alextabone at gmail.com (Alchemist) Date: Mon, 18 Jun 2007 02:55:15 -0700 Subject: Using a web service [newbie] Message-ID: <1182160515.533065.203530@n60g2000hse.googlegroups.com> I am working with Python 2.5 and would like to use of a web service. What shall I install on my setup (or import in my Python script)? I read about Zolera Soap Infrastructure, which seems to be the preferred Python web service framework (http:// pywebsvcs.sourceforge.net/). However, its documentation seems quite old (c. 2001/2002) whilst the Babel Fish translation example (http:// livedocs.adobe.com/coldfusion/6.1/htmldocs/webserv3.htm) did not work for me. Are there any more recent frameworks or tools for using web services by Python scripts? Thank you. From clj2289 at garnet.acns.fsu.edu Tue Jun 19 12:00:14 2007 From: clj2289 at garnet.acns.fsu.edu (Christopher L Judd) Date: Tue, 19 Jun 2007 09:00:14 -0700 Subject: pydev help In-Reply-To: <59f9c5160706190856k5793ec2bn7d66ab518fedf1ca@mail.gmail.com> References: <59f9c5160706190856k5793ec2bn7d66ab518fedf1ca@mail.gmail.com> Message-ID: Its called mylyn now. You can get it from here: http://www.eclipse.org/mylyn/dl.php Best, Chris On 6/19/07, Danyelle Gragsone wrote: > > My first post! > > Greetings all, > > I am trying to get pydev up and running in linux. I have it up and > running in windows but for some strange reason not here. I did > install pydev a few months ago on my windows machine so that may be > the reason why.. > > I followed this guide: http://www.fabioz.com/pydev/manual_101_install.html > > When I get to about the middle of the page where it seemingly loading > everything and I get this: Pydev Mylar Integration (0.2.0) requires > plug-in "org.eclipse.mylar (2.0.0.v20070403-1300)", or later version." > > Where do I get that module from? > > Thanks, > Danyelle > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From mostselect at gmail.com Sat Jun 30 02:35:02 2007 From: mostselect at gmail.com (mostselect at gmail.com) Date: Fri, 29 Jun 2007 23:35:02 -0700 Subject: Free usefull article.Do you need contents to add to your web site? Message-ID: <1183185302.691660.229040@j4g2000prf.googlegroups.com> Free usefull article.Do you need contents to add to your web site? www.real-article.com From horpner at yahoo.com Wed Jun 6 08:18:45 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Wed, 06 Jun 2007 12:18:45 GMT Subject: *Naming Conventions* References: <1180909218.939713.112010@q69g2000hsb.googlegroups.com> <1180990280.960271.235550@h2g2000hsg.googlegroups.com> <466699e9$0$2308$426a74cc@news.free.fr> Message-ID: On 2007-06-06, Bruno Desthuilliers wrote: > Neil Cerutti a ?crit : >> On 2007-06-04, Michael Hoffman wrote: >>> Wildemar Wildenburger wrote: >>> I agree with Bruno that i and j should be used only for >>> indices, but I'm usually less terse than that. >> >> I find i and j preferable to overly generic terms like "item." > > Since 'i' and 'j' are canonically loop indices, I find it > totally confusing to use them to name the iteration variable - > which is not an index. > > At least, 'item' suggests that it's an object, and a part of > the collection - not just an index you'll have to use to > subscript the container. Also, and as far as I'm concerned, I > certainly dont find 'i' and 'j' *less* generic than 'item' !-) Thanks, I didn't say clearly what I meant. Certainly i and j are just as generic, but they have the advantage over 'item' of being more terse. I'm in the habit of letting context indicates wether i is a contained object or a subscript. The advantage of a terse, one-letter name is how it draws attention to context, rather than itself. But it's a small distinction. I wouldn't call 'item' a bad choice. -- Neil Cerutti From cousinstanley at hotmail.com Wed Jun 6 09:44:53 2007 From: cousinstanley at hotmail.com (Cousin Stanley) Date: Wed, 06 Jun 2007 08:44:53 -0500 Subject: Who uses Python? References: <1180985830.288414.208850@q69g2000hsb.googlegroups.com> Message-ID: <1181137493_16515@sp12lax.superfeed.net> > I mean other than sysadmins, programmers, and web-site developers? > .... You might try the Python Success Stories for a good source for finding a wide variety of Python users and usage .... http://pythonology.org/success -- Stanley C. Kitching Human Being Phoenix, Arizona ----== Posted via Newsfeeds.Com - Unlimited-Unrestricted-Secure Usenet News==---- http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ Newsgroups ----= East and West-Coast Server Farms - Total Privacy via Encryption =---- From jfine at pytex.org Fri Jun 22 03:08:53 2007 From: jfine at pytex.org (Jonathan Fine) Date: Fri, 22 Jun 2007 08:08:53 +0100 Subject: Packing a simple dictionary into a string - extending struct? References: Message-ID: <467B7585.5040801@pytex.org> Jonathan Fine wrote: > Thank you for this suggestion. The growing adoption of JSON in Ajax > programming is a strong argument for my using it in my application, although > I think I'd prefer something a little more binary. > > So it looks like I'll be using JSON. Well, I tried. But I came across two problems (see below). First, there's bloat. For binary byte data, one average one character becomes just over 4. Second, there's the inconvenience. I can't simple take a sequence of bytes and encode them using JSON. I have to turn them into Unicode first. And I guess there's a similar problem at the other end. So I'm going with me own solution: http://mathtran.cvs.sourceforge.net/mathtran/py/bytedict.py?revision=1.1&view=markup It seems to be related to cerializer: http://home.gna.org/oomadness/en/cerealizer/index.html It seems to me that JSON works well for Unicode text, but not with binary data. Indeed, Unicode hides the binary form of the stored data, presenting only the code points. But I don't have Unicode strings! Here's my test script, which is why I'm not using JSON: === import simplejson x = u'' for i in range(256): x += unichr(i) print len(simplejson.dumps(x)), '\n' simplejson.dumps(chr(128)) === Here's the output === 1046 # 256 bytes => 256 * 4 + 34 bytes Traceback (most recent call last): File "/usr/lib/python2.4/encodings/utf_8.py", line 16, in decode return codecs.utf_8_decode(input, errors, True) UnicodeDecodeError: 'utf8' codec can't decode byte 0x80 in position 0: unexpected code byte === -- Jonathan From john106henry at hotmail.com Fri Jun 22 15:02:49 2007 From: john106henry at hotmail.com (John Henry) Date: Fri, 22 Jun 2007 12:02:49 -0700 Subject: Adding method to a class on the fly Message-ID: <1182538969.522044.209560@q19g2000prn.googlegroups.com> Hi list, I have a need to create class methods on the fly. For example, if I do: class Dummy: def __init__(self): exec '''def method_dynamic(self):\n\treturn self.method_static("it's me")''' return def method_static(self, text): print text return I like that to be the same as: class Dummy: def __init__(self): return def method_dynamic(self): return self.method_static("it's me") def method_static(self, text): print text return so that I can do: dum=Dummy.method_dynamic() and see "it's me" printed. Can that be done? Thanks, From wildemar at freakmail.de Mon Jun 4 07:49:59 2007 From: wildemar at freakmail.de (Wildemar Wildenburger) Date: Mon, 04 Jun 2007 13:49:59 +0200 Subject: subexpressions (OT: math) In-Reply-To: References: <4662675b$1_5@news.bluewin.ch> <1180890214.317409.85100@w5g2000hsg.googlegroups.com> <1180894045.538031.111610@g4g2000hsf.googlegroups.com> <1180895200.108582.313010@k79g2000hse.googlegroups.com> Message-ID: <4663FC67.5020009@freakmail.de> Peter Otten wrote: > Stebanoid at gmail.com wrote: > > >> sine is a dimensionless value. >> if we expand sine in taylor series sin(x) = x - (x^3)/6 + (x^5)/120 >> etc. >> you can see that sin can be dimensionless only if x is dimensionless >> too. >> > > With y = x^2 = 1/3 pi^2 - 4(cos x - cos(2x)/2^2 + cos(3x)/3^2 - ...) > > area is dimensionless, too, I suppose. > No, its not dimensionless (phew, that took me a while ... got pretty anxious there for a moment): If you look at the definition of the fourier coefficients on the page you presented (http://www.exampleproblems.com/wiki/index.php/FS6), you'll see that they have the same unit as f(x) (or y(x) as in your example). Which, btw, is VERY MUCH desired because all science (and with it the universe, mind you!) would blow up if functions didn't have the same unit as any of their series expansions. After all, they are meant to *replace* the function. Man! You scared me good! :D Oh my, remember when we used to discuss murderous snakes and silly British comedians on this group? I hardly do ... /W From wildemar at freakmail.de Sun Jun 3 19:03:50 2007 From: wildemar at freakmail.de (Wildemar Wildenburger) Date: Mon, 04 Jun 2007 01:03:50 +0200 Subject: subexpressions (OT: math) In-Reply-To: <1180895200.108582.313010@k79g2000hse.googlegroups.com> References: <4662675b$1_5@news.bluewin.ch> <1180890214.317409.85100@w5g2000hsg.googlegroups.com> <1180894045.538031.111610@g4g2000hsf.googlegroups.com> <1180895200.108582.313010@k79g2000hse.googlegroups.com> Message-ID: <466348D6.9000202@freakmail.de> Stebanoid at gmail.com wrote: > if you are discordant read more :P : > sine is a dimensionless value. > if we expand sine in taylor series sin(x) = x - (x^3)/6 + (x^5)/120 > etc. > you can see that sin can be dimensionless only if x is dimensionless > too. > > I am a professional physicist and a know about what I talk > > No you don't. I'm a student of physics, and I know better: First of all, what you have presented here is called the MacLaurin series. It is however a special case of the Taylor series, so you are correct. I just thought I'd let you know. (Sorry to sound like a bitch here, i love smartassing ;)) Let me start by saying that *if* x had a dimension, none of the terms in your expansion would have the same dimension. A well well-versed physicist's head should, upon seeing such a thing, explode so as to warn the other physicists that something is terribly off there. How (ye gods!) do you add one metre to one square-metre? You don't, that's how! OK, the *actual* form of the MacLaurin series for some function f(x) is f(x) = f(0) + x/1! f'(0) + x^2/2! f''(0) + ... So in each term of the sum you have a derivative of f, which in the case of the sine function translates to sine and cosine functions at the point 0. It's not like you're rid of the function just by doing a polynomial expansion. The only way to *solve* this is to forbid x from having a dimension. At least *I* see no other way. Do you? /W (Don't take this as a personal attack, please. I'm a good guy, I just like mathematical nitpicking.) From tburdick at gmail.com Tue Jun 12 04:15:52 2007 From: tburdick at gmail.com (Thomas F. Burdick) Date: Tue, 12 Jun 2007 08:15:52 -0000 Subject: The Concepts and Confusions of Prefix, Infix, Postfix and Fully Functional Notations In-Reply-To: <1181597817.867161.10510@h2g2000hsg.googlegroups.com> References: <1179936917.652372.24780@q69g2000hsb.googlegroups.com> <1180508453.226022.44230@q19g2000prn.googlegroups.com> <1181335574.107472.229370@x35g2000prf.googlegroups.com> <1181358616.792797.97720@k79g2000hse.googlegroups.com> <1181414625.121073.203940@g4g2000hsf.googlegroups.com> <0uHai.176367$nh4.13819@newsfe20.lga> <1181448558.120521.63250@g4g2000hsf.googlegroups.com> <0G_ai.1970$xg4.809@trnddc08> <1181525392.369255.138460@h2g2000hsg.googlegroups.com> <1181545345.788665.191690@q66g2000hsg.googlegroups.com> <1181597817.867161.10510@h2g2000hsg.googlegroups.com> Message-ID: <1181636152.035125.152390@r19g2000prf.googlegroups.com> On Jun 11, 11:36 pm, Tim Bradshaw wrote: > On Jun 11, 8:02 am, Twisted wrote: > > > On Jun 11, 2:42 am, Joachim Durchholz wrote: > > > > It is possible to write maintainable Perl. > > > Interesting (spoken in the tone of someone hearing about a purported > > sighting of Bigfoot, or maybe a UFO). > > I think it's just obvious that this is the case. What would *stop* > you writing maintainable Perl? The constantly shifting target of a language. Hell, even the parser has changed over time. Fortunately this seems to have been solved by Perl 6 [*]. [*] Stopping work on Perl 5 to focus on the probably never-to-be Perl 6 brought a surprising stability to the language. From tijs_news at bluescraper.nl Fri Jun 1 05:58:37 2007 From: tijs_news at bluescraper.nl (Tijs) Date: Fri, 01 Jun 2007 11:58:37 +0200 Subject: Roundup, smtplib, TLS and MS Exchange References: Message-ID: <465fedcd$0$323$e4fe514c@news.xs4all.nl> carlistixx wrote: > [foobar at moe tracker]$ roundup-server -p 8081 > roundup=/home/foobar/roundup/tracker > Roundup server started on :8081 > send: 'STARTTLS\r\n' > reply: '503 5.5.2 Send hello first\r\n' > reply: retcode (503); Msg: 5.5.2 Send hello first I think this must be an issue with roundup, issuing commands in the wrong order. The correct order should (according to the rfc and the python docs) be: * ehlo() * starttls() * ehlo() * login() ... -- Regards, Tijs From kelvie at ieee.org Thu Jun 21 08:01:16 2007 From: kelvie at ieee.org (Kelvie Wong) Date: Thu, 21 Jun 2007 05:01:16 -0700 Subject: visual gui ides for python/jythpn In-Reply-To: <1182410303.449758.135940@u2g2000hsc.googlegroups.com> References: <1182363400.993370.109800@k79g2000hse.googlegroups.com> <1182410303.449758.135940@u2g2000hsc.googlegroups.com> Message-ID: <94ccbe710706210501h18575358nef524f2dc2576255@mail.gmail.com> If Qt/PyQt is an option, I'd recommend the Qt designer. There is the odd dual license that they have, though. On 6/21/07, kromakey wrote: > Thanks, I'll take a look at these. > Kromakey > > On 20 Jun, 22:10, "Peter Decker" wrote: > > On 6/20/07, kromakey wrote: > > > > > Hi, > > > > > Are there any free visual GUI IDE's available for python/jython, which > > > have a drag and drop form designer similar to Visual Studio or > > > Delphi ? > > > > Watch these screencasts, and then check out Dabo: > > > > http://leafe.com/screencasts/dataenvironment1.htmlhttp://leafe.com/screencasts/dataenvironment2.html > > > > Dabo's site ishttp://dabodev.com. > > > > -- > > > > # p.d. > > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Kelvie From twisted0n3 at gmail.com Sun Jun 24 15:32:21 2007 From: twisted0n3 at gmail.com (Twisted) Date: Sun, 24 Jun 2007 19:32:21 -0000 Subject: The Modernization of Emacs: terminology buffer and keybinding In-Reply-To: References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182272495.990807.99110@a26g2000pre.googlegroups.com> <87tzt3ihev.fsf@kobe.laptop> <1182370216.961241.6960@n60g2000hse.googlegroups.com> <85zm2ufjpb.fsf@lola.goethe.zz> <1182372592.803332.288260@u2g2000hsc.googlegroups.com> <1182373919.262388.100740@c77g2000hse.googlegroups.com> <85r6o6fhkb.fsf@lola.goethe.zz> <1182375045.626510.188170@m36g2000hse.googlegroups.com> <85myyufgwj.fsf@lola.goethe.zz> <1182375528.985142.293900@q69g2000hsb.googlegroups.com> <1182545268.055596.228700@i38g2000prf.googlegroups.com> <1182547318.325617.16370@o11g2000prd.googlegroups.com> <1182657564.912472.55570@g4g2000hsf.googlegroups.com> Message-ID: <1182713541.449966.195970@o61g2000hsh.googlegroups.com> On Jun 24, 8:10 am, Martin Gregorie wrote: > > Actually, what I prefer in (2D and 3D) visual design apps is the > > ability to snap to some kind of grid/existing vertices, and to zoom in > > close. Then small imprecisions in mouse movement can be rendered > > unimportant. > > That might work for visual design apps, but it doesn't for CAD, where > you may want to point to an arbitrary position with a (scaled) accuracy > of microns. I didn't mention that you should be able to zoom and make the grid fine to whatever limit is reasonable given the application? The issue being, how accurate is "accurate enough"? Pinpoint precision isn't possible, unless it's an integer or a functionally derived value like pi or some arithmetic result of that. Grids are good for getting rational numbers exactly, and nothing will hit the irrational ones exactly, save if you can enter a formula for it to use to compute the point's location to any desired precision. A mouse click (sans grid) will always introduce some error; the zoom level lets you limit the magnitude of the error. So does a grid, and to zero if the desired point is a grid vertex, and to half the grid size more generally. > The fact remains that mechanical mice do jump when you click them, > though optical mice are better in this respect. Ultimately, the button has to be non-mechanical for this sort of thing to really work. Or else not physically part of the mouse. Being able to "click" from the keyboard makes sense given such requirements. So does being able to snap to a grid. > > The problem of course being the complete exclusion of type 1 users. > > Totally untrue. I'm not talking about in general. I'm talking about the specific sorts of unixy applications that are under discussion here. Those emphatically cater solely to type-3s and type-4s, aside from newer graphical apps for KDE and Gnome, which are emerging as a third group of type-1-accessible tool alongside Mac applications and Windows applications. > Thats not true and never can be: a computer is > the most complex device the average person will own or use and is likely > to retain that title for the foreseeable future. What about the fabrication devices? Oh, but I suppose the "foreseeable future" has already ended by the time those trickle down to widespread consumer use. > I grant you that type 2 users are rare, but I think flight simulators > may fit this case when used for training. Anything you have to use to meet some important external goal, I suppose. But most usually there are options. A programmer needs a text editor but it need not be emacs. Jobs requiring the use of specific software (for training, or just on the job) maybe, of which your example is a subset. > Not really. What's needed is a single interface that can be used by > anybody from beginner to expert and that, in the case of an error, shows > precisely where it got, what caused the action to fail to complete and > that allows the user to continue from that point without having to > undo/redo the bits that were successful. Its not easy, but it can be done. Why do those who have the skills, talent, knowledge, and thus capability to do this insist on making cruft like emacs then? I've never seen a classic-unix tool that didn't barf unhelpful and uninformative error messages at the drop of a hat (just like Windows!) and present a piss-poor UI, or even no UI at all (unless "usage: blah blah blah" qualifies as a UI, to which my response is one word. "Non- interactive.") When the error messages are informative, they're still cryptic, and only someone with knowledge of the software's internals has a hope in hell of fixing the problem as a rule. Of course, the number one rule of interface design is to speak the user's language and the language of the problem domain, and remain mute (except to developers invoking debug modes) about the implementation details and the language of the solution domain. Especially given that a different version of the same software, nevermind a different app with the same usage, is probably going to use a different implementation anyway. One exception can be to expose a specific scripting language for advanced users to use to automate tasks. Emacs does this, and it's one thing I don't have a problem with. As long as knowledge of its arcana is not needed to either do straightforward stuff, or fix the errors that occur attempting to do straightforward stuff, anyway. If the beginner can safely ignore the thing's existence (e.g. the VB-based scripting language in some office and paint programs) it's fine. > > ROM BASICs and QBasic (on any really ancient microcomputer, and old > > pre-Windows PCs, respectively; the former came with printed manuals > > and you could just run prepackaged software from disks very easily; > > Hang on: you don't read manuals. You object to using tutorials and to > buying books, so its a bit precious to claim this example. The manuals came with the computers, at no additional charge. It was a different time. This isn't going to be true of any separately- purchased book or user-made printout concerning emacs. Also, the manuals provided a basic introduction for the beginning user. A traditional-unix-tool providing anything resembling that would genuinely shock me. > > * The word processor with the usual interface where I can define > > logical styles, then change them in only one place and affect every > > pre-existing occurrence retroactively. > > Thats been in Word since DOS days and is part of OpenOffice. Its called > a "style sheet". I distinctly remember Winword circa 2002 not being able to retroactively change all of a bunch of like-formatted paragraphs easily. Not without delving into VBscript or something, anyway. > You're thinking of Wordperfect and its 'Reveal Codes' function. That was > the worst idea I've ever seen in a WP, matched only by the illogically > arranged set of 12 function keys, each with 4 shifts. Why? > It didn't. 'Reveal codes' could only let you inspect the current > document. Unfortunately it was essential to use it because some input > sequences could completely mess up the formatting and the only way to > recover was via 'Reveal codes'. The effect was similar to making a data > entry clerk use a hex editor on a database to fix keyboarding errors. Oh, because the implementation (of "reveal codes" and of everything else) was awful, not because of any intrinsic flaw in the idea itself. Would you want to edit a Web page without being able to hand-hack the HTML? Use a GUI builder for Swing without being able to hand-hack the Java? Thought not. [Snip description of an advanced-for-its-time interface] What happened to the guys that did all this stuff after it became obsolete? Microsoft offer them $300 grand a year to mop floors or sit in on various board meetings without a vote or something to get them out of the way, being unable to use their talents competently and equally unable to stand having them work for a competitor, or worse, contribute to open source? Or offer a mob type $100 grand once to whack them maybe? > > The bog-standard alt, this, that sequences on Windows "come close"; > > they do make the menus display, but otherwise they do exactly what you > > want, and you can ignore the menus blinking around in your peripheral > > vision. > > No they don't: you can't easily string them together to act as a single > command and the error diagnosis and reporting is remarkably poor. Same > goes for Gnome, so I'm not particularly bashing Windows here. You can string them together manually, or use a keyboard macro recording and playback tool (they exist, though one doesn't come standard with Windows; I think maybe one does with MacOS). It would be nice if straightforward macro recording was standard in Windows though. On the other hand, I've not always been 100% sure of that sort of thing. Even seemingly straightforward search-and-replace can suffer from Sorceror's Apprentice Syndrome even at the best of times. And if the thing treats every individual replace as a separate undoable action instead of the one batch-of-replaces, and has a buffer of only 10 undos, and 13 items match, and one of them was unexpected and shouldn't have been replaced... Macro capabilities might be a dream, but macros running amok are a nightmare. Maybe a real programmability would be better. I think the scripting language capabilities in some apps provide that, with more ability to control and constrain it from going into Sorceror's Apprentice mode, but every app tends to have its own scripting language and API and no real introduction-to-scripting type stuff, leading us back to "the emacs problem" -- an arcane interface that begins and ends in midair, with nowhere for the beginning user to climb aboard, and differing from application to application so limiting the value of investing much time in any one of them versus if a single universal one were used (say Lua, or even elisp, or even *gag* VB...) From steve at REMOVE.THIS.cybersource.com.au Fri Jun 15 21:25:55 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sat, 16 Jun 2007 11:25:55 +1000 Subject: Python's "only one way to do it" philosophy isn't good? References: <1181368143.874341.273140@r19g2000prf.googlegroups.com> Message-ID: On Fri, 15 Jun 2007 17:05:27 -0400, Douglas Alan wrote: > You are ignoring the fact that Scheme has a powerful syntax extension > mechanism (i.e., hygenic macros), which means that anyone in the world > can basically extend Scheme to include practically any language > feature they might like it to have. You say that like it is a good thing. -- Steven. From a.schmolck at gmail.com Tue Jun 12 20:42:51 2007 From: a.schmolck at gmail.com (Alexander Schmolck) Date: Wed, 13 Jun 2007 01:42:51 +0100 Subject: Python's "only one way to do it" philosophy isn't good? References: <1181368143.874341.273140@r19g2000prf.googlegroups.com> Message-ID: Steven D'Aprano writes: > On Mon, 11 Jun 2007 01:28:09 +0100, Alexander Schmolck wrote: > >> Steven D'Aprano writes: >> >>> On Sat, 09 Jun 2007 22:42:17 +0100, Alexander Schmolck wrote: >>> >>>>> As for why tail calls are not optimized out, it was decided that being able >>>>> to have the stack traces (with variable information, etc.) was more useful >>>>> than offering tail call optimization >>>> >>>> I don't buy this. >>> >>> Do you mean you don't believe the decision was made, or you don't agree >>> with the decision? >> >> Neither. I don't believe the rationale stated in this thread to be the true >> reason. > > > Don't keep us in suspense. What do you believe is the true reason? It's easier to spot that some rationalization is bogus than to unconver the true underlying causes; I'm pretty sure it's more a Gestalt thing than a compelling technical reason (I guess Guido's distaste for scheme also plays a role). Not that I discount that out of hand -- maybe all that's great about python is due to Guido being exceptionally good at making such judgements. >>> Are you volunteering? If you are, I'm sure your suggestion will be welcomed >>> gratefully. >> >> I rather doubt it. Guido has stated quite clearly that his not >> interested in incorporating this feature. > > He's not the only one who gets to make these decisions. This is news to me. Who else does? > But even if he uses his veto to prevent tail-recursion optimization from > being put into the main branch, there are other options. That don't involve abducting his kids? >>>>> (do what I say). >>>> >>>> Where did you say run out of memory and fail? More importantly how do >>>> you say "don't run out of memory and fail"? >>> >>> If we can live with a certain amount of "arbitrary failures" in simple >>> arithmetic, >> >> I prefer not too, and thus when possible avoid to use languages where >> ``a + b`` is liable to fail arbitrarily (such as C, where the behavior >> will often be undefined). > > That's not the sort of arbitrary failure I was discussing, but for that > matter Python is one of those languages. Apart from floating point arithmetic, simple arithmetic doesn't tend to fail arbitrarily in python, as far as I'm aware. You can of course create your very own classes specifically to get broken arithmetic but that doesn't strike me as "simple" arithmetic anymore. > Perhaps Python is not the language for you? Do you also happen to know what would be? > Correct me if I'm wrong, but surely it is C++ that can have arbitrary > behaviour for "a + b", not C? ``INT_MAX + 1`` can do precisely anything in C. >>> You can always hand-optimize it yourself. >> >> Not tail calls, in general, no. > > Sorry, how does that work? You're suggesting that there is an algorithm > which the compiler could follow to optimize away tail-recursion, but human > beings can't follow the same algorithm? Now I'm confused. Does it also confuse you that if I give you a 500x500 matrix A you won't be able to figure out a single element in A^-1 by doing mental arithmetic (or using pen and paper), although my computer manages just fine and I'm happy to give you the algorithm it uses? 'as From tereglow at yahoo.com Tue Jun 12 11:14:53 2007 From: tereglow at yahoo.com (tereglow) Date: Tue, 12 Jun 2007 08:14:53 -0700 Subject: Convert String to Int and Arithmetic In-Reply-To: <1181659583.424110.194340@r19g2000prf.googlegroups.com> References: <1181658761.300066.118210@a26g2000pre.googlegroups.com> <1181659583.424110.194340@r19g2000prf.googlegroups.com> Message-ID: <1181661293.426877.237680@a26g2000pre.googlegroups.com> On Jun 12, 10:46 am, Kay Schluehr wrote: > On 12 Jun., 16:32, tereglow wrote: > > > Hello, > > > I am a complete newbie to Python and am accustomed to coding in PHP/ > > Perl/Shell. I am trying to do the following: > > > I have a string: > > > cpuSpeed = 'Speed: 1000000000' > > > What I would like to do is extract the '1000000000' from the string, > > and divide that by 1000 twice to get the speed of a processor in MHz. > > > My understanding is that I need to 'import re' and then use re.split > > to get the first part done. > > It shall suffice to use string methods in this case: > > >>> int(cpuSpeed.split(":")[1].strip()) > > 1000000000 > > Finally you might trim the numerical value by division just as you > wish. Thanks guys. The biggest problem I'm having with Python is that it makes things too easy to do! From bugmagnet at gmail.com Mon Jun 25 08:56:50 2007 From: bugmagnet at gmail.com (bugmagnet at gmail.com) Date: Mon, 25 Jun 2007 05:56:50 -0700 Subject: Internationalised email subjects In-Reply-To: References: <1182337500.638044.63470@e9g2000prf.googlegroups.com> <46791592$0$5719$edfadb0f@dread14.news.tele.dk> <1182346499.123234.279880@e9g2000prf.googlegroups.com> <1182417604.446766.47660@e9g2000prf.googlegroups.com> <1182417823.793678.323530@a26g2000pre.googlegroups.com> <467B5D56.7060208@v.loewis.de> <1182496538.387301.122670@i38g2000prf.googlegroups.com> <1182505762.845544.314940@e9g2000prf.googlegroups.com> Message-ID: <1182776210.444247.205100@a26g2000pre.googlegroups.com> I'm an idiot! Gabriel, you're right! Turns out the ISP was running Python 2.3, which has known issues with the GB2312 codec. They've upgraded to 2.4 and now everything runs smoothly! From http Tue Jun 26 13:10:42 2007 From: http (Paul Rubin) Date: 26 Jun 2007 10:10:42 -0700 Subject: Python's "only one way to do it" philosophy isn't good? References: <7x3b0nmkk6.fsf@ruckus.brouhaha.com> <1182750077.570603.160240@q69g2000hsb.googlegroups.com> <7xir9cbm0g.fsf@ruckus.brouhaha.com> <7xejjzmk7u.fsf@ruckus.brouhaha.com> <7xy7i7xjl5.fsf@ruckus.brouhaha.com> <1182872972.417776.78650@o11g2000prd.googlegroups.com> <1182873568.454491.302860@e9g2000prf.googlegroups.com> Message-ID: <7xps3iy73h.fsf@ruckus.brouhaha.com> Andy Freeman writes: > Compare that with what a programmer using Python 2.4 has to do if > she'd like the functionality provided by 2.5's with statement. Yes, > with is "just syntax", but it's extremely useful syntax, syntax that > can be easily implemented with lisp-style macros. Not really. The with statement's binding targets all have to support the protocol, which means a lot of different libraries need redesign. You can't do that with macros. Macros can handle some narrow special cases such as file-like objects, handled in Python with contextlib.closing. That said, the with statement was missing from Python for much too long, since users were happy to rely on reference counting. From Screamingfirst at gmail.com Fri Jun 1 14:12:13 2007 From: Screamingfirst at gmail.com (Screamingfirst at gmail.com) Date: Fri, 01 Jun 2007 18:12:13 -0000 Subject: __getslice__ depreciation In-Reply-To: <1180720203.950209.260610@w5g2000hsg.googlegroups.com> References: <1180720203.950209.260610@w5g2000hsg.googlegroups.com> Message-ID: <1180721533.851070.309770@w5g2000hsg.googlegroups.com> On Jun 1, 7:50 pm, Screamingfi... at gmail.com wrote: > If __getslice__ is depreciated (since version 2.0) why are neither > __setslice__ or __delslice__ depreciated?http://docs.python.org/ref/sequence-methods.html Sorry disregard that, I should have RTFA From zowers at gmail.com Sat Jun 9 10:28:17 2007 From: zowers at gmail.com (Alexander Petrov) Date: Sat, 9 Jun 2007 18:28:17 +0400 Subject: Tackling setup.py - A bug?? Message-ID: <967fb7350706090728m38376b94j457e23db3ffef70f@mail.gmail.com> Hi, I've successfully compiled p4python with modified setup.py the key to success was to split extra_compile_args's argument '-arch' into 2 args. below is fixed part: [code] ext_modules=[Extension("P4Client", [ "P4Clientmodule.cc" ], include_dirs=[ os.path.join( p4_api_dir, "include", "p4" ) ], library_dirs=[ os.path.join( p4_api_dir, "lib" ) ], libraries=["client", "rpc", "supp"], # P4API libs extra_compile_args=["-DCASE_INSENSITIVE", "-fpascal-strings", "-isysroot", "/Developer/SDKs/MacOSX10.4u.sdk", "-DOS_MACOSX", "-DOS_MACOSX104" , "-arch", "ppc" ,"-D%s" % p4_api_ver], extra_link_args=[ "-Wl,-syslibroot,/Developer/SDKs/MacOSX10.4u.sdk" , "-arch", "ppc" , "-framework", "System" , "-framework", "CoreFoundation" , "-framework", "Carbon" ], )] [/code] hope it will help --- Original Message: --- And this followed by an setup.py install seemed to work just fine. Ok so now I need to backport these options into setup.py. Here is what I came up with.. elif os.name == "posix": setup(name=NAME, version=VERSION, description=DESCRIPTION, author=AUTHOR, author_email=AUTHOR_EMAIL, maintainer=MAINTAINER, maintainer_email=MAINTAINER_EMAIL, license=LICENSE, url=URL, keywords=KEYWORDS, classifiers = filter(None, classifiers.split("\n")), long_description = "\n".join(doclines[2:]), py_modules=PY_MODULES, ext_modules=[Extension("P4Client", ["P4Clientmodule.cc"], include_dirs=[p4_api_dir], library_dirs=[p4_api_dir], libraries=["client", "rpc", "supp"], # P4API libs extra_compile_args=["-DCASE_INSENSITIVE", "-fpascal-strings", "-isysroot/Developer/ SDKs/MacOSX10.4u.sdk", "-DOS_MACOSX", "- DOS_MACOSX104", "-DOS_MACOSXPPC", "- DOS_MACOSX104PPC" ,"-D%s" % p4_api_ver], extra_link_args=[ "-Wl,-syslibroot,/ Developer/SDKs/MacOSX10.4u.sdk", "-arch ppc", "-framework Carbon" ], )]) But low and behold it didn't work... In the course of debugging I found that the compile works. The linking appears to be a problem. In the link stage I see the command which is being run looks very similar to my command g++ -bundle -undefined dynamic_lookup build/temp.macosx-10.3-ppc-2.5/ P4Clientmodule.o \ -Lp4api6.1 -lclient -lrpc -lsupp -o build/lib.macosx-10.3-ppc-2.5/ P4Client.so \ -Wl,-syslibroot,/Developer/SDKs/MacOSX10.4u.sdk -arch ppc -framework Carbon Not quite the same but close enough. HERE is where the bug shows up........ If I rerun this same EXACT command at the command line - followed by a setup.py install it works. Can someone with a larger python brain than mine please help me figure this out? It's bugging the crap out fo me... -- BR. Alexander 'zowers' Petrov. jabber:zowers at jabber.ru icq:69694782 http://zowers.googlepages.com/ mailto:zowers at gmail.com From cam.ac.uk at mh391.invalid Mon Jun 4 17:25:50 2007 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Mon, 04 Jun 2007 22:25:50 +0100 Subject: *Naming Conventions* In-Reply-To: References: <1180909218.939713.112010@q69g2000hsb.googlegroups.com> <1180990280.960271.235550@h2g2000hsg.googlegroups.com> Message-ID: Wildemar Wildenburger wrote: > bruno.desthuilliers at gmail.com wrote: >> On Jun 4, 12:20 am, Ninereeds wrote: >> >>> First, for small loops with loop variables whose meaning is obvious >>> from context, the most readable name is usually something like 'i' or >>> 'j'. >>> >> >> 'i' and 'j' are the canonical names for for loops indices in languages >> that don't support proper iteration over a sequence. Using them for >> the iteration variable of a Python for loop (which is really a >> 'foreach' loop) would be at best confusing. >> >> > > While that is true, I guess it is commonplace to use i, j, k and n > (maybe others) in constructs like > > for i in range(len(data)): > do_stuff(data[i]) > > Or should the good python hacker do that differently? Hope not ;). Well, yes, I would do: for item in data: do_stuff(item) or, if using enumerate: for item_index, item in enumerate(data): do_stuff(item_index, item) I agree with Bruno that i and j should be used only for indices, but I'm usually less terse than that. -- Michael Hoffman From donn at u.washington.edu Wed Jun 27 19:34:21 2007 From: donn at u.washington.edu (Donn Cave) Date: Wed, 27 Jun 2007 16:34:21 -0700 Subject: PEP 3107 and stronger typing (note: probably a newbie question) References: <1182369568.941307.316260@p77g2000hsh.googlegroups.com> <5dveb4F360un0U1@mid.individual.net> <467a9209$0$22165$426a74cc@news.free.fr> <1182858785.886469.93060@n60g2000hse.googlegroups.com> <46824d8d$0$2324$426a74cc@news.free.fr> <4682eddc$0$23164$426a74cc@news.free.fr> Message-ID: In article <4682eddc$0$23164$426a74cc at news.free.fr>, Bruno Desthuilliers wrote: > John Nagle a ?crit : > > Bruno Desthuilliers wrote: > > > >> Indeed - static typing is for compilers, not for programmers. > > > > > > Actually, static typing is for detecting errors before the > > program is run. > > bruno at bibi ~ $ cat toto.c > #include > int main(void) > { > char *toto = (char *)42; > printf("%s", toto); > return 0; > } > bruno at bibi ~ $ gcc -ototo toto.c > bruno at bibi ~ $ ./toto > Erreur de segmentation > bruno at bibi ~ $ > > You said ? A discussion about static typing on comp.lang.python is liable to be a little tiresome even when it isn't conducted on such a silly level. The GvR ideas I've seen on V3 typing show some acquaintance with type inference etc. as used in modern functional languages. While C++ or Java may represent static typing to Python users, I don't think there's much risk that they will have anything to do with static typing in V3, if it's supported in some way. Secondly, one can reasonably argue that steel toed boots prevent injuries to the toe, without having to prove that they withstand a welding torch, a nuclear blast, etc. Donn Cave, donn at u.washington.edu From horpner at yahoo.com Thu Jun 21 09:53:04 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Thu, 21 Jun 2007 13:53:04 GMT Subject: strip() 2.4.4 References: <1182432181.050589.5800@n2g2000hse.googlegroups.com> Message-ID: On 2007-06-21, Nick wrote: > strip() isn't working as i expect, am i doing something wrong - > > Sample data in file in.txt: > > 'AF':'AFG':'004':'AFGHANISTAN':'Afghanistan' > 'AL':'ALB':'008':'ALBANIA':'Albania' > 'DZ':'DZA':'012':'ALGERIA':'Algeria' > 'AS':'ASM':'016':'AMERICAN SAMOA':'American Samoa' > > > Code: > > f1 = open('in.txt', 'r') > > for line in f1: > print line.rsplit(':')[4].strip("'"), > > Output: > > Afghanistan' > Albania' > Algeria' > American Samoa' > > Why is there a apostrophe still at the end? Most likely it's the newline at the end of each record that's getting in your way. You can double-strip it. for line in f1: print line.strip().rsplit(':')[4].strip("'") -- Neil Cerutti The world is more like it is now than it ever has been before. --Dwight Eisenhower From conor.robinson at gmail.com Fri Jun 1 17:14:52 2007 From: conor.robinson at gmail.com (py_genetic) Date: Fri, 01 Jun 2007 21:14:52 -0000 Subject: Create a new class on the fly In-Reply-To: <1hyy30j.f4k5tc17kc7ohN%aleax@mac.com> References: <1180568447.449581.250500@g37g2000prf.googlegroups.com> <1hyy30j.f4k5tc17kc7ohN%aleax@mac.com> Message-ID: <1180732492.717760.288190@n15g2000prd.googlegroups.com> Alex, thanks for the advise: > > class PosRecords(tables.IsDescription): > > > class A(object): > > self.__init__(self, args): > > This makes 0 sense; maybe you should learn elementary Python syntax well > _before_ trying advanced stuff, no? I accidently left that erroneous snippet in, however if your offering a class in smart ass let me know where to sign up. From peter.mosley at talk21.com Thu Jun 21 03:49:40 2007 From: peter.mosley at talk21.com (peter) Date: Thu, 21 Jun 2007 00:49:40 -0700 Subject: DFW Pythoneers Meeting THIS Saturday In-Reply-To: References: <1182325553.232470.205970@q75g2000hsh.googlegroups.com> <1182337167.504241.131530@m36g2000hse.googlegroups.com> <6a2ccd190706200535m2aff7a50r411bbf3cbeaaae25@mail.gmail.com> Message-ID: <1182412180.513164.326110@k79g2000hse.googlegroups.com> OK. Not my intention to start a flame war, but as DFW did not mean a thing to me (other than being my late father in law's initials) I was a bit peeved about the assumption that everybody would understand it. I think posts which are essentially local should make this clear to all in the title. I hope the meeting goes well. From gagsl-py2 at yahoo.com.ar Mon Jun 25 21:26:47 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 25 Jun 2007 22:26:47 -0300 Subject: New Thread- Supporting Multiline values in ConfigParser References: <1182780364.650693.10430@w5g2000hsg.googlegroups.com> Message-ID: En Mon, 25 Jun 2007 11:06:04 -0300, Phoe6 escribi?: > I took the approach of Subclassing ConfigParser to support multiline > values without leading white-spaces, but am struct at which position > in _read I should modify to accomodate the non-leading whitespace > based multiline values. And how would you detect a multiline value? Because it is not a section nor looks like a new option? > I can guess, this portion in the _read function will require change, > any change to this affects the whole of parsing. :-( Can someone who > has done this before or understands ConfigParser better help me? > > # Section I am talking about > if line[0].isspace() and cursect is not None > and optname: > > value = line.strip() > if value: > cursect[optname] = "%s\n%s" % > (cursect[optname], value) Yes, I guess so. I'd try using this: if not self.SECTCRE.match(line) and not self.OPTCRE.match(line) and cursect is not None and optname: (that is, if the line is not a section header and it's not a new option and there is a current section and option; those two last conditions same as the previous version). But you'll have to experiment - I've not tested it. -- Gabriel Genellina From jimbomaan at gmail.com Thu Jun 14 00:56:13 2007 From: jimbomaan at gmail.com (why?) Date: Wed, 13 Jun 2007 21:56:13 -0700 Subject: How to save python codes in files? In-Reply-To: <1181722913.777141.279570@n15g2000prd.googlegroups.com> References: <1181711063.512249.289520@x35g2000prf.googlegroups.com> <1181721972.486523.37680@g37g2000prf.googlegroups.com> <1181722913.777141.279570@n15g2000prd.googlegroups.com> Message-ID: <1181796973.366518.245050@x35g2000prf.googlegroups.com> I tried but its not working. Here's a code for sum of two numbers. Now how do i save it? >>> #! /usr/bin/env python ... >>> def sum(x,y): ... return x+y ... >>> x=int(raw_input('Enter a number: ')) Enter a number: 35 >>> y=int(raw_input('Enter a number: ')) Enter a number: 7 >>> print 'sum is', sum(x,y) sum is 42 From ratchetgrid at googlemail.com Sun Jun 24 13:55:28 2007 From: ratchetgrid at googlemail.com (Nathan Harmston) Date: Sun, 24 Jun 2007 18:55:28 +0100 Subject: Accessing variable from a function within a function Message-ID: <676224240706241055p94d333ep2abc9e92c6167143@mail.gmail.com> Hi, I m playing around with extended euclids algorithm from Knuth. I m trying to build a function with a function inside it. def exteuclid(m,n): a,a1,b,b1,c,d = 0,1,1,0,m,n def euclid(c,d): q = c /d r = c % d if r == 0: print a,b return d else: print a1,a,b1,b,c,d,q,r t = b1 b = t - q * b a = t - q * a c,d,a1,b1 = d,r,a,b return euclid(c,d) return euclid(c,d) Unfortunately this doesnt work since a,a1,b,b1 arent declared in the function. Is there a way to make these variables accessible to the euclid function. Or is there a better way to design this function? Many Thanks in advance, Nathan From tommy.nordgren at comhem.se Wed Jun 6 07:47:36 2007 From: tommy.nordgren at comhem.se (Tommy Nordgren) Date: Wed, 6 Jun 2007 13:47:36 +0200 Subject: Determinant of Large Matrix In-Reply-To: References: Message-ID: <08ADAC5D-9E24-41A6-AA8C-B4C245B27916@comhem.se> On 6 jun 2007, at 13.10, James Stroud wrote: > Hello All, > > I'm using numpy to calculate determinants of matrices that look like > this (13x13): > > [[ 0. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1.] > [ 1. 0. 1. 4. 1. 9. 4. 4. 1. 1. 4. 9. 4. 9.] > [ 1. 1. 0. 1. 4. 4. 9. 9. 4. 4. 1. 4. 1. 4.] > [ 1. 4. 1. 0. 9. 1. 4. 4. 9. 1. 4. 1. 4. 1.] > [ 1. 1. 4. 9. 0. 4. 4. 4. 1. 4. 1. 9. 4. 9.] > [ 1. 9. 4. 1. 4. 0. 4. 4. 9. 4. 1. 1. 4. 1.] > [ 1. 4. 9. 4. 4. 4. 0. 1. 1. 1. 9. 1. 9. 4.] > [ 1. 4. 9. 4. 4. 4. 1. 0. 4. 1. 9. 4. 4. 1.] > [ 1. 1. 4. 9. 1. 9. 1. 4. 0. 4. 4. 4. 4. 9.] > [ 1. 1. 4. 1. 4. 4. 1. 1. 4. 0. 9. 4. 9. 4.] > [ 1. 4. 1. 4. 1. 1. 9. 9. 4. 9. 0. 4. 1. 4.] > [ 1. 9. 4. 1. 9. 1. 1. 4. 4. 4. 4. 0. 4. 1.] > [ 1. 4. 1. 4. 4. 4. 9. 4. 4. 9. 1. 4. 0. 1.] > [ 1. 9. 4. 1. 9. 1. 4. 1. 9. 4. 4. 1. 1. 0.]] > > For this matrix, I'm getting this with numpy: > > 2774532095.9999971 > > But I have a feeling I'm exceeding the capacity of floats here. Does > anyone have an idea for how to treat this? Is it absurd to think I > could > get a determinant of this matrix? Is there a python package that could > help me? > > Many thanks for any answers. > > James > -- > http://mail.python.org/mailman/listinfo/python-list Are you sure NumPy return float results. As far as I know, it returns doubles (about 16 digits) ------------------------------------------------------ "Home is not where you are born, but where your heart finds peace" - Tommy Nordgren, "The dying old crone" tommy.nordgren at comhem.se From showell30 at yahoo.com Fri Jun 15 07:44:30 2007 From: showell30 at yahoo.com (Steve Howell) Date: Fri, 15 Jun 2007 04:44:30 -0700 (PDT) Subject: Serialization across languages? In-Reply-To: <46727407$0$20038$426a74cc@news.free.fr> Message-ID: <964568.38854.qm@web33510.mail.mud.yahoo.com> --- Bruno Desthuilliers wrote: > Tobiah a ?crit : > > I want to do SOAP like calls from a device who's > libraries > > don't include SOAP. I'm thinking of using simple > HTTP posts, > > but I'm going to want to send arrays and hashes. > > Then I'd second Simon's suggestion to use JSON. > I'll third it. Another thing to look at may be YAML: http://www.yaml.org/start.html http://www.yaml.org/ http://www.yaml.org/discuss.html There are implementations in Python, Ruby, Perl, Java, Javascript, etc.: http://www.yaml.org/download.html One thing that YAML has strived for, and largely got for free through fortunate coincidence, was compatibility with JSON. ____________________________________________________________________________________Ready for the edge of your seat? Check out tonight's top picks on Yahoo! TV. http://tv.yahoo.com/ From __peter__ at web.de Fri Jun 1 04:09:50 2007 From: __peter__ at web.de (Peter Otten) Date: Fri, 01 Jun 2007 10:09:50 +0200 Subject: subexpressions References: Message-ID: Sergey Dorofeev wrote: > Please help, is there way to use sub-expressions in lambda? > For example, if I want to calculate sin(x^2)+cos(x^2) I must code: > lambda x: sin(x*x)+cos(x*x) > How to make x*x to be evaluated once? >>> (lambda x: [sin(x2) + cos(x2) for x2 in [x*x]][0])(.5) == sin(.5*.5) + cos(.5*.5) True The real answer is of course: Use a function. Peter From showell30 at yahoo.com Sat Jun 2 12:31:07 2007 From: showell30 at yahoo.com (Steve Howell) Date: Sat, 2 Jun 2007 09:31:07 -0700 (PDT) Subject: Python rocks In-Reply-To: <4661700a$0$19261$da0feed9@news.zen.co.uk> Message-ID: <115495.45605.qm@web33504.mail.mud.yahoo.com> --- Mark Carter wrote: > Well, I know I'm preaching to the converted - but > Python rocks. > [...] A few questions from the choir: As a recent newcomer to the language, did you encounter any traps or pitfalls while you were learning? Also, could you single out anything in particular about Python that started making you more productive, or was it just the overall design? ____________________________________________________________________________________ Boardwalk for $500? In 2007? Ha! Play Monopoly Here and Now (it's updated for today's economy) at Yahoo! Games. http://get.games.yahoo.com/proddesc?gamekey=monopolyherenow From evan at yelp.com Sat Jun 30 23:57:33 2007 From: evan at yelp.com (Evan Klitzke) Date: Sat, 30 Jun 2007 20:57:33 -0700 Subject: object references/memory access In-Reply-To: <1183247524.662884.153830@n60g2000hse.googlegroups.com> References: <1183247524.662884.153830@n60g2000hse.googlegroups.com> Message-ID: On 6/30/07, dlomsak wrote: > If there is not a good Pythonic way to do the above, I am open to > mixing in some C to do the job if that is what it takes. I apologize > if this topic has been brought up many times before but hopefully I > have stated my intentions clearly enough for those with a higher > knowledge of the topic to help. If the above are not possible but you > have a really good idea for zipping large amounts of data from one > program to another, I'd like to hear it. You can do things like this in C with shared memory segments. I'm not familiar enough with the Python C API to tell you how easy this would be, but that might be a good place to start your investigations. -- Evan Klitzke From robin at reportlab.com Thu Jun 28 08:13:33 2007 From: robin at reportlab.com (Robin Becker) Date: Thu, 28 Jun 2007 13:13:33 +0100 Subject: 16bit hash In-Reply-To: <46833DC0.3050503@v.loewis.de> References: <46833DC0.3050503@v.loewis.de> Message-ID: <4683A5ED.1090603@chamonix.reportlab.co.uk> Martin v. L?wis wrote: 0 the ideal hash :) can't be argued with >....... > So: what are your input data, and what is the > distribution among them? > > Regards, > Martin > I'm trying to create UniqueID's for dynamic postscript fonts. According to my resources we don't actually need to use these, but if they are required by a particular postscript program (perhaps to make a print run efficient) then the private range of these ID's is 4000000<=UID<=4999999 ie a range of one million. So I probably really need an 18 bit hash The data going into the font consists of fontBBox '[-415 -431 2014 2033]' charmaps ['dup (\000) 0 get /C0 put',......] metrics ['/C0 1251 def',.....] bboxes ['/C29 [0 0 512 0] def',.......] chardefs ['/C0 {newpath 224 418 m 234 336 ......def}',......] ie a bunch of lists of strings which are eventually joined together and written out with a template to make the postscript definition. The UniqueID is used by PS interpreters to avoid recreating particular glyphs so ideally I would number these fonts sequentially using a global count, but in practice several processes separated by application and time can produce postscript which eventually gets merged back together. If the UID's clash then the printer produces very strange output. I'm fairly sure there's no obvious python way to ensure the separated processes can communicate except via the printer. So either I use a python based scheme which reduces the risk of clashes ie random or some data based hash scheme or I attempt to produce a postscript solution like looking for a private global sequence number. I'm not sure my postscript is really good enough to do the latter so I hoped to pursue a python based approach which has a low probability of busting. Originally I thought the range was a 16bit number which is why I started with 16bit hashes. -- Robin Becker From apatheticagnostic at gmail.com Thu Jun 21 17:39:16 2007 From: apatheticagnostic at gmail.com (kaens) Date: Thu, 21 Jun 2007 17:39:16 -0400 Subject: PEP 3107 and stronger typing (note: probably a newbie question) In-Reply-To: <20070621143048.GH6145@slaniel-laptop.itasoftware.com> References: <1182369568.941307.316260@p77g2000hsh.googlegroups.com> <5dveb4F360un0U1@mid.individual.net> <20070621141156.GG6145@slaniel-laptop.itasoftware.com> <20070621143048.GH6145@slaniel-laptop.itasoftware.com> Message-ID: <163f0ce20706211439r47dc7a88h25bbee91db408ff2@mail.gmail.com> On 6/21/07, Stephen R Laniel wrote: > On Thu, Jun 21, 2007 at 10:11:57AM -0400, Stephen R Laniel wrote: > > "Use another language" is not a technical answer. "Python > > could not adopt static typing without substantially changing > > the language and destroying what everyone loves about it, > > and here are examples of where the problem shows up" is. > > The best dynamic-versus-static-typing discussion I've ever > seen, by the way, was Mark-Jason Dominus's (he of > "Higher-Order Perl"): > http://perl.plover.com/yak/typing/notes.html > > -- > Stephen R. Laniel > steve at laniels.org > Cell: +(617) 308-5571 > http://laniels.org/ > PGP key: http://laniels.org/slaniel.key > -- > http://mail.python.org/mailman/listinfo/python-list > This really cleared some stuff up for me, thanks. From carsten at uniqsys.com Fri Jun 1 08:39:17 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Fri, 01 Jun 2007 08:39:17 -0400 Subject: c[:]() In-Reply-To: <002f01c7a42d$f94f5d00$240110ac@Muse> References: <1180504190.055427.173610@h2g2000hsg.googlegroups.com> <1180554872.3356.30.camel@dot.uniqsys.com> <465DF3DE.40404@cc.umanitoba.ca> <1180566831.239580.199300@m36g2000hse.googlegroups.com> <005401c7a31a$136f7fe0$240110ac@Muse> <135tobve86qj808@corp.supernews.com> <135tru124pie2b3@corp.supernews.com> <135tv1bjqgbmsc9@corp.supernews.com> <9qudnbFRU9QHJsLbnZ2dnUVZ_rKvnZ2d@speakeasy.net> <002f01c7a42d$f94f5d00$240110ac@Muse> Message-ID: <1180701557.3376.2.camel@dot.uniqsys.com> On Fri, 2007-06-01 at 02:19 -0700, Warren Stringer wrote: > There is code that you type which persists and code that you type from a > command line. Two completely different idioms. A credo inside the cell phone > game industry is that you lose half your audience with each menu keystroke. > That's how precious keystrokes are. Then why do have your users typing code into a cell phone? -- Carsten Haese http://informixdb.sourceforge.net From showell30 at yahoo.com Sun Jun 10 20:52:10 2007 From: showell30 at yahoo.com (Steve Howell) Date: Sun, 10 Jun 2007 17:52:10 -0700 (PDT) Subject: Python in the Mozilla world In-Reply-To: <466C966A.5000900@harvee.org> Message-ID: <466059.8047.qm@web33502.mail.mud.yahoo.com> --- "Eric S. Johansson" wrote: > > this is good to know except I am somewhat cautious > about the end result given > that it's from Microsoft (explained below) > Believe me, I agree! I work mostly in the Unix world now, but I've done enough serious development in the Windows world to be fearful of what MS can do to any simple idea. > Simple idea, complex partial > solution, simpler solution. only experience will > tell you when you have gotten > the most simplicity out of the solution possible. Agreed, this is a very common phenomenon in engineering, science, etc. > [...] > This is yet another good reason why folks should > really push for a simple > browser environment to replace JavaScript. I really > don't think it's horribly > hard but on the other hand, I don't understand the > full environment (starting > with a simple idea... :-) Ajax and Javascript are far from perfect, but I do think they carry some baggage from things that are really are outside of the scope of their basically well-founded purposes. For example, even if you replaced Javascript with Python, you wouldn't necessarily solve these problems: 1) Browser environments, like all GUI environments, are inherently difficult environments for things like debugging, unit testing, etc. (From what I understand, there are some half decent debuggers for Javascript, but they are not batteries included with all browsers.) 2) Browsers will always differ on subtle, but important, details of how they render things, how they expose a DOM, etc. In some cases this will be due to benevolent factors (one browser goes to a simpler model, but you still have to support the old models), and in other cases there will be the Microsoft conspiracy to make everything more difficult. ;) 3) There will always be web designers who are focused on flaming logos, skinnability, etc., vs. actual usability. Also, remember that Ajax and Javascript are still young technologies. > Thanks for the post. It's triggered some nice ideas > in my head. > You're welcome, and likewise! ____________________________________________________________________________________ Choose the right car based on your needs. Check out Yahoo! Autos new Car Finder tool. http://autos.yahoo.com/carfinder/ From gagsl-py2 at yahoo.com.ar Mon Jun 4 18:51:22 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 04 Jun 2007 19:51:22 -0300 Subject: get_traceback References: <1180977780.997361.133320@g37g2000prf.googlegroups.com> Message-ID: En Mon, 04 Jun 2007 14:23:00 -0300, escribi?: > Is there a function or idoim for returning an exception/traceback > rather than just printing it to stdout? I'm running a deamon where > stdout is going to /dev/null, and I'm not even watching it..until > now. All the functions I found in traceback and sys seemed only to > print the error rather than just returning it, so I resorted to this: Read again the docs for the traceback module. Maybe you are looking for traceback.format_exception(*sys.exc_info()) or traceback.format_exc() > f = tempfile.TemporaryFile(mode='w+') > sys.stdout = f > traceback.print_tb(sys.exc_info()[2]) In this case you can use StringIO instead of a temporary file, and the file argument to print_tb instead of swapping sys.stdout -- Gabriel Genellina From sjmachin at lexicon.net Mon Jun 18 16:11:50 2007 From: sjmachin at lexicon.net (John Machin) Date: Mon, 18 Jun 2007 13:11:50 -0700 Subject: csv search and print In-Reply-To: References: Message-ID: <1182197510.875585.89160@i13g2000prf.googlegroups.com> On Jun 19, 4:12 am, axja... at comcast.net wrote: > I have a csv file containing lot of rows & columns. I wanted to search thru the > heading for each column for a string and then print all the headings and the > corresponding rows if a match is found. > > Any advise? 1. Clarify your requirements: "corresponding rows" ... corresponding to what? How many rows/columns is a "lot"? "I have a csv file" ... only one? "search thru the heading for each column for a string" is open to misinterpretation of various kinds :-) 2. Write your script. 3. Ask a specific question if you have a problem. From byte8bits at gmail.com Wed Jun 6 11:52:36 2007 From: byte8bits at gmail.com (brad) Date: Wed, 06 Jun 2007 11:52:36 -0400 Subject: Who uses Python? In-Reply-To: <1180985830.288414.208850@q69g2000hsb.googlegroups.com> References: <1180985830.288414.208850@q69g2000hsb.googlegroups.com> Message-ID: walterbyrd wrote: > I mean other than sysadmins, programmers, and web-site developers? > Anything else? Finance? Web-analytics? SEO? Digital art? IT Security Analysts use it... see code and screenshots... these are not professional programmers: http://filebox.vt.edu/users/rtilley/public/find_ssns/mac/index.html From winter at biotec.tu-dresden.de Wed Jun 13 14:09:55 2007 From: winter at biotec.tu-dresden.de (Christof Winter) Date: Wed, 13 Jun 2007 20:09:55 +0200 Subject: Python Help!!! In-Reply-To: References: Message-ID: <467032F3.2030703@biotec.tu-dresden.de> Elfine Peterson Tjio wrote: > I'm trying to make a program that reads Fasta file and print it out. I used > the SeqIO module and the results is: > > 'ATGGTCAT....SingleAlphabet()' > > For this purpose, should I use SeqIO or Fasta? > > for example: > > from Bio import SeqIO > > or > > from Bio import Fasta > > I want it to print every letter. Can anyone point me to the right direction. > The newest biopython tutorial or book recommendation will be appreciated, > too. Dear Elfine: The correct place for such a question is the BioPython discussion list at biopython at lists.open-bio.org You can subscribe to it here: http://lists.open-bio.org/mailman/listinfo/biopython/ The newest BioPython tutorial (last updated 16 March 2007) can be found at http://biopython.org/DIST/docs/tutorial/Tutorial.pdf SeqIO and Fasta should both work fine. You could also try >>> help(SeqIO) >>> help(Fasta) after your import for some further information. Cheers, Christof From half.italian at gmail.com Wed Jun 27 11:54:35 2007 From: half.italian at gmail.com (half.italian at gmail.com) Date: Wed, 27 Jun 2007 15:54:35 -0000 Subject: Getting importError: No module named _md5 In-Reply-To: <1182953092.454946.321760@k29g2000hsd.googlegroups.com> References: <1182953092.454946.321760@k29g2000hsd.googlegroups.com> Message-ID: <1182959675.705826.137670@o11g2000prd.googlegroups.com> On Jun 27, 7:04 am, jeffself wrote: > I'm running Python 2.5.1 which I'm getting from the MacPort package > system. I just installed Django and tried to start up the Django > server and I got the following error: > > ImportError: No module named _md5 > > I'm pretty sure this is a python problem, not Django problem. I'm > looking in the python2.5 directory and I see md5.py, md5.pyc and > md5.pyo files. > > Any suggestions? Try to load the md5 module from the interactive prompt. Are you using the python version you expect? Try starting up your previous version of python and see if you get the same error. Delete the MacPort install and install from source. My 2 cents. ~Sean From hamish at cloud.net.au Thu Jun 7 05:15:41 2007 From: hamish at cloud.net.au (Hamish Moffatt) Date: Thu, 07 Jun 2007 19:15:41 +1000 Subject: Integer division In-Reply-To: <1181207216.890336.99990@r19g2000prf.googlegroups.com> References: <1181207216.890336.99990@r19g2000prf.googlegroups.com> Message-ID: <4667CCBD.2040709@cloud.net.au> jm.suresh at no.spam.gmail.com wrote: > Hello all, > I have two integers and I want to divide one by another, and want to > get an integer result which is the higher side whenever the result is > a fraction. > 3/2 => 1 # Usual behavior > some_func(3, 2) => 2 # Wanted > > Any easier solution other than int(math.ceil(float(3)/2)) The normal solution is to add (divisor-1) to the dividend before division. Ie ceil(3/2) = floor((3+(2-1))/2) = 2. Correct. But ceil(4/2) = floor((4+(2-1))/2) = 2 also. Correct. Hamish From tim at preservedwords.com Tue Jun 26 21:16:56 2007 From: tim at preservedwords.com (tim at preservedwords.com) Date: Tue, 26 Jun 2007 21:16:56 -0400 Subject: Can Readlines() go to next line after a Tab Message-ID: <16914272.243781182907016292.JavaMail.servlet@perfora> I have a module based app that can load many modules at startup. The modules are text based with a '\t' separating the keyword from the definition. The app reads each module to extract the keywords, but because readlines() must read to the end of the current line to get to the next, the module loading is slow. Is there a way to have readlines() go to the next line when it finds a tab '\t' instead of a newline '\n'? Is there a better way to do this? I know a second file could be made of the keywords only, but I would like to have only one file. Thanks, Tim From dave at boost-consulting.com Thu Jun 21 16:03:42 2007 From: dave at boost-consulting.com (David Abrahams) Date: Thu, 21 Jun 2007 16:03:42 -0400 Subject: import mysteries Message-ID: <87sl8laxcx.fsf@grogan.peloton> I'm pretty comfortable with Python, but recently I'm constantly finding mysterious issues with import. For example, looking at http://genshi.edgewall.org/browser/trunk/genshi/filters/transform.py the examples use the symbol 'HTML' but it's not defined locally, it's not explicitly imported, and there's no import *. Yet doctest will test this module and it passes with flying colors. It turns out HTML is defined in genshi.input. How do I know that? I grepped for it. How does it become available to this module? Another example: I was recently working on some code that did an import from inside a class method. That import was failing. I moved the import to the top of the file (at module scope) and it succeeded. I'm fairly sure that nobody was monkeying around with sys.path in that case. Can anyone think of a likely explanation? TIA, -- Dave Abrahams Boost Consulting http://www.boost-consulting.com The Astoria Seminar ==> http://www.astoriaseminar.com From dwahler at gmail.com Wed Jun 20 12:02:35 2007 From: dwahler at gmail.com (David Wahler) Date: Wed, 20 Jun 2007 17:02:35 +0100 Subject: How to hide a program? In-Reply-To: <1182352921.305431.72290@k79g2000hse.googlegroups.com> References: <1182347596.414718.117190@w5g2000hsg.googlegroups.com> <1182352921.305431.72290@k79g2000hse.googlegroups.com> Message-ID: On 6/20/07, jvdb wrote: > The thing is, i don't want to see anything of my program, just the > launched program. > I already have the program working. But when i create an executable of > it with py2exe and start it, i don't want to see that it is running, > perhaps just in the systemtray. That is my problem. Try renaming your main script to have a .pyw extension as Diez said, or use the --windows option when running py2exe. http://mail.python.org/pipermail/python-list/2003-December/241319.html -- David From xahlee at gmail.com Fri Jun 8 16:46:14 2007 From: xahlee at gmail.com (xahlee at gmail.com) Date: Fri, 08 Jun 2007 13:46:14 -0700 Subject: The Concepts and Confusions of Prefix, Infix, Postfix and Fully Functional Notations In-Reply-To: <1180508453.226022.44230@q19g2000prn.googlegroups.com> References: <1179936917.652372.24780@q69g2000hsb.googlegroups.com> <1180508453.226022.44230@q19g2000prn.googlegroups.com> Message-ID: <1181335574.107472.229370@x35g2000prf.googlegroups.com> How Purely Nested Notation Limits The Language's Utility [The full HTML formatted article is available at: http://xahlee.org/UnixResource_dir/writ/notations.html ] 2007-05-03 There is a common complain by programers about lisp's notation, of nested parenthesis, being unnatural or difficult to read. Long time lisp programers, often counter, that it is a matter of conditioning, and or blaming the use of ?inferior? text editors that are not designed to display nested notations. In the following, i describe how lisp notation is actually a problem, in several levels. (1) Some 99% of programers are not used to the nested parenthesis syntax. This is a practical problem. On this aspect along, lisp's syntax can be considered a problem. (2) Arguably, the pure nested syntax is not natural for human to read. Long time lispers may disagree on this point. (3) Most importantly, a pure nested syntax discourages frequent or advanced use of function sequencing or compositions. This aspect is the most devastating. The first issue, that most programers are not comfortable with nested notation, is well known. It is not a technical issue. Whether it is considered a problem of the lisp language is a matter of philosophical disposition. The second issue, about nested parenthesis not being natural for human to read, may be debatable. I do think, that deep nesting is a problem to the programer. Here's a example of 2 blocks of code that are syntactically equivalent in the Mathematica language: vectorAngle[{a1_, a2_}] := Module[{x, y}, {x, y} = {a1, a2}/Sqrt[a1^2 + a2^2] // N; If[x == 0, If[Sign at y === 1, ?/2, -?/2], If[y == 0, If[Sign at x === 1, 0, ?], If[Sign at y === 1, ArcCos at x, 2 ? - ArcCos at x] ] ] ] SetDelayed[vectorAngle[List[Pattern[a1,Blank[]],Pattern[a2,Blank[]]]], Module[List[x,y], CompoundExpression[ Set[List[x,y], N[Times[List[a1,a2], Power[Sqrt[Plus[Power[a1,2],Power[a2,2]]],-1]]]], If[Equal[x,0], If[SameQ[Sign[y],1],Times[?,Power[2,-1]], Times[Times[-1,?],Power[2,-1]]], If[Equal[y,0],If[SameQ[Sign[x],1],0,?], If[SameQ[Sign[y],1],ArcCos[x], Plus[Times[2,?],Times[-1,ArcCos[x]]]]]]]]] In the latter, it uses a full nested form (called FullForm in Mathematica). This form is isomorphic to lisp's nested parenthesis syntax, token for token (i.e. lisp's ?(f a b)? is Mathematica's ?f[a,b]?). As you can see, this form, by the sheer number of nested brackets, is in practice problematic to read and type. In Mathematica, nobody really program using this syntax. (The FullForm syntax is there, for the same reason of language design principle shared with lisp of ?consistency and simplicity?, or the commonly touted lisp advantage of ?data is program; program is data?.) The third issue, about how nested syntax seriously discourages frequent or advanced use of inline function sequencing on the fly, is the most important and I'll give further explanation below. One practical way to see how this is so, is by considering unix's shell syntax. You all know, how convenient and powerful is the unix's pipes. Here are some practical example: ?ls -al | grep xyz?, or ?cat a b c | grep xyz | sort | uniq?. Now suppose, we get rid of the unix's pipe notation, instead, replace it with a pure functional notation: e.g. (uniq (sort (grep xyz (cat a b c)))), or enrich it with a composition function and a pure function construct (?), so this example can be written as: ((composition uniq sort (lambda (x) (grep xyz x))) (cat a b c)). You see, how this change, although syntactically equivalent to the pipe ?|? (or semantically equivalent in the example using function compositions), but due to the cumbersome nested syntax, will force a change in the nature of the language by the code programer produces. Namely, the frequency of inline sequencing of functions on the fly will probably be reduced, instead, there will be more code that define functions with temp variables and apply it just once as with traditional languages. A language's syntax or notation system, has major impact on what kind of code or style or thinking pattern on the language's users. This is a well-known fact for those acquainted with the history of math notations. The sequential notation ?f at g@h at x?, or ?x//h//g//f?, or unixy ?x|h|g| f?, are far more convenient and easier to decipher, than ?(f (g (h x)))? or ?((composition f g h) x)?. In actual code, any of the f, g, h might be a complex pure function (aka lambda constructs, full of parenthesis themselves). Lisp, by sticking with a almost uniform nested parenthesis notation, it immediately reduces the pattern of sequencing functions, simply because the syntax does not readily lend the programer to it as in the unix's ?x|h|g|f?. For programers who are aware of the coding pattern of sequencing functions, now either need to think in terms of a separate ?composition? construct, and or subject to the much problematic typing and deciphering of nested parenthesis. (Note: Lisp's sexp is actually not that pure. It has ad hoc syntax equivalents such as the ?quote? construct ? '(a b c) ?, and also ?`?, ?#?, ?,@? constructs, precisely for the purpose of reducing parenthesis and increasing readability. Scheme's coming standard the R6RS ?, even proposes the introduction of [] and {} and few other syntax sugars to break the uniformity of nested parenthesis for legibility. Mathematica's FullForm, is actually a version of unadulterated nested notation as can be.) Xah xah at xahlee.org ? http://xahlee.org/ From deets at nospam.web.de Fri Jun 15 06:19:37 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 15 Jun 2007 12:19:37 +0200 Subject: save class In-Reply-To: <1181847914.603957.174200@n15g2000prd.googlegroups.com> References: <1181784016.454693.42340@o11g2000prd.googlegroups.com> <1181787082.712869.72770@z28g2000prd.googlegroups.com> <1181847914.603957.174200@n15g2000prd.googlegroups.com> Message-ID: <5df7drF34ivvjU1@mid.uni-berlin.de> > of having to keep track of a separate dictionary file. I am new to > this, but I thought that this would be a regular thing to do in > python, because people must make classes in the interactive console > and then export them somehow for later use. No. That's not how things work. One does dabble with the interpreter a bit, sometimes even creating a tiny class. But except from the occasional expression tested in the interpreter, it's not common to use that code and save it. Write python-files from the start. Then either execute them python myfile.py or if you insist, do python >>> import myfile >>> myfile.some_function() Diez From twisted0n3 at gmail.com Wed Jun 20 16:04:30 2007 From: twisted0n3 at gmail.com (Twisted) Date: Wed, 20 Jun 2007 20:04:30 -0000 Subject: The Modernization of Emacs In-Reply-To: <1182319163.532211.174470@u2g2000hsc.googlegroups.com> References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <873b0p9vpm.fsf@W0053328.mgh.harvard.edu> <1182280875.861486.324370@w5g2000hsg.googlegroups.com> <1182319163.532211.174470@u2g2000hsc.googlegroups.com> Message-ID: <1182369870.641156.4040@p77g2000hsh.googlegroups.com> On Jun 20, 1:59 am, "spamfilteracco... at gmail.com" wrote: > On Jun 19, 9:21 pm, Ed wrote: > > > Have you ever seen an, "Extractmethod," function for emacs? Whereby > > you highlight some lines of code, press a key, and the code is whisked > > into its ownmethod, with the appropriatemethodinvocation left in > > its place. If you could post a link, that'd be just champion. > > xrefactory does this. I tried it once. It's a bit pricey , though. Someone is charging money for an emacs addon? Are they nuts? A lot of people won't touch emacs with a ten foot pole, and emacs is free. How many would actually pay for something that's useless without emacs? Especially given the near-certainty that the price is almost pure profit margin... From ai.nature at gmail.com Tue Jun 5 05:21:45 2007 From: ai.nature at gmail.com (ai) Date: Tue, 05 Jun 2007 02:21:45 -0700 Subject: Python, Dutch, English, Chinese, Japanese, etc. In-Reply-To: References: Message-ID: <1181035305.734962.173490@j4g2000prf.googlegroups.com> I am not a native English speaker. But I totally do not support PEP 3131. If a program is written in English and commented by other language, I am read it. But if a program is written in other language, it will be full unreadable by me even it is commented by English. I think language is just a tool used for intercommunion. The best situation is all people use only one language. From tjreedy at udel.edu Fri Jun 8 01:10:06 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 8 Jun 2007 01:10:06 -0400 Subject: Integer division References: <1181207216.890336.99990@r19g2000prf.googlegroups.com> Message-ID: "Some Other Guy" wrote in message news:bb9ae$4668b133$cef88832$11811 at TEKSAVVY.COM... | jm.suresh at no.spam.gmail.com wrote: | | > Hello all, | > I have two integers and I want to divide one by another, and want to | > get an integer result which is the higher side whenever the result is | > a fraction. | > 3/2 => 1 # Usual behavior | > some_func(3, 2) => 2 # Wanted | | Are you trying to accomplish int((a/b) + 0.5), but cheaply? No, the OP wanted 'ceiling' division rather than 'floor' division. In other words, always round up instead of down. | If so, consider that that is the same as (a/b) + (b/2b), | which is (2a/2b) + (b/2b), which is (2a+b)/2b. This is nice for rounded division. tjr From alban.lefebvre at gmail.com Sun Jun 17 05:49:13 2007 From: alban.lefebvre at gmail.com (Baltimore) Date: Sun, 17 Jun 2007 09:49:13 -0000 Subject: Function that returns a tuple In-Reply-To: <1182071765.760451.298490@u2g2000hsc.googlegroups.com> References: <1182043826.790070.4420@u2g2000hsc.googlegroups.com> <1182071765.760451.298490@u2g2000hsc.googlegroups.com> Message-ID: <1182073753.544045.256670@g4g2000hsf.googlegroups.com> On 17 juin, 11:16, Marcpp wrote: > On 17 jun, 03:53, Dan Hipschman wrote:> On Sat, Jun 16, 2007 at 06:30:26PM -0700, Marcpp wrote: > > > Hi, I need to returns a tuple from a function (reads a database) > > > Any idea?. > > > Like this? > > > def foo(): > > return 1, 2, 3, 4 > > Hi, I need to return a tupla like this function: > > def BDllids(a): > a = () > conn = sqlite.connect('tasques.db') > cursor = conn.cursor() > cursor.execute('SELECT * FROM tasques') > for row in cursor: > a.append (row[0]) > return a() > > I'm doing the correct, method? Why is 'a' used as argument of the function ? You don't need to put it in argument. def BDllids(): a = () conn = sqlite.connect('tasques.db') cursor = conn.cursor() cursor.execute('SELECT * FROM tasques') for row in cursor: a.append (row[0]) return a But that's the correct method ! From deets at nospam.web.de Thu Jun 28 18:22:38 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 29 Jun 2007 00:22:38 +0200 Subject: exception from a thread In-Reply-To: <1183064774.900116.198270@k79g2000hse.googlegroups.com> References: <1183064774.900116.198270@k79g2000hse.googlegroups.com> Message-ID: <5eiqljF36jh57U1@mid.uni-berlin.de> _spitFIRE schrieb: > assume a scenario, where there is a class that for doing some work, > spawns lot of threads. > > class X: > def __init__(self): > # Spawns some threads to > # do some work > > now, assuming that at least one of the threads encounters a problem > while doing work and throws an exception. Would I be able to handle > that error in the caller class? When I try to do this, I see that the > errors thrown by the threads never cascade to this caller :( Exactly. Because they are different threads - the very essence of them is each of them having their own stacks. Depending on what you do in the main-thread, you can do something like this: class Worker(Thread): def __init__(self): ... self.running = False ... self.start() def run(self): self.running = True try: ... # work finally: self.running = False In the main-thread, you test for each thread if it's still running. while True: time.sleep(.1) for t in threads: if not t.running: print "Not running anymor: %r" % t Diez From twisted0n3 at gmail.com Sun Jun 24 02:33:42 2007 From: twisted0n3 at gmail.com (Twisted) Date: Sun, 24 Jun 2007 06:33:42 -0000 Subject: The Modernization of Emacs: terminology buffer and keybinding In-Reply-To: References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182272495.990807.99110@a26g2000pre.googlegroups.com> <87tzt3ihev.fsf@kobe.laptop> <1182370216.961241.6960@n60g2000hse.googlegroups.com> <1182549831.068658.123870@i13g2000prf.googlegroups.com> Message-ID: <1182666822.651882.7200@k79g2000hse.googlegroups.com> On Jun 23, 11:56 am, Bjorn Borud wrote: > [Twisted ] > | > | That sort of negative-sum thinking is alien to me. Software being easy > | for beginners to get started using does not in and of itself detract > | from its value to expert users. > > the fact that you imply that this is my argument tells me that either > you have not paid attention, or you have a raging inferiority complex. > given the sum of your postings so far I'd say that you neither are, > nor consider yourself, a cerebral sort of person, so this narrows it > down somewhat (although not to the exclusion of you not having paid > attention). That ... makes no sense. Sorry. Previously, I said: > Being beginner-friendly doesn't have to be at the expense of power or > expert-user usability and you said that depended on the definition of "expert". Apparently you believe there is a type of "expert" for whom beginner-friendly software is intrinsically less usable than beginner-hostile software. Given that beginner-friendliness does not preclude any kind of expert level functionality being available (consider something configurable enough that an advanced user can start it up and open an advanced-uses window and immediately do advanced stuff, and a real expert can make it start up with that window already open and focused by default), it follows that these experts' perceptions of decreased usability are a psychological result of simply knowing beginners can easily become proficient in using basic functions of the software in question, rather than a material result of some compromise necessarily made in the software's design, as there is no such compromise that can't in practise be avoided. An expert who feels software is less suitable for his use *purely* because the unwashed masses can actually use it to accomplish something is quite obviously some type of elitist jerk. I rest my case. From benedict.verheyen at gmail.com Mon Jun 11 05:23:59 2007 From: benedict.verheyen at gmail.com (Benedict Verheyen) Date: Mon, 11 Jun 2007 11:23:59 +0200 Subject: python-ldap for Python 2.5 on Windows? In-Reply-To: <1181323389.805143.236480@i38g2000prf.googlegroups.com> References: <1181323389.805143.236480@i38g2000prf.googlegroups.com> Message-ID: Waldemar Osuch schreef: > > I have managed to build it for myself using MinGW: > http://www.osuch.org-a.googlepages.com/python-ldap-2.3.win32-py2.5.exe > > See if it will work for you > > Waldemar Hi Waldemar, thanks for the installation file. When i installed it, i got an error stating "The setup files are corrupt". Anyway, i would be interested in knowing how to build the setup. The only experience i have so far with building stuff via MinGW was with a Qemu build. Regards, Benedict From wim.vogelaaratmc2worlddotorg Thu Jun 14 08:31:08 2007 From: wim.vogelaaratmc2worlddotorg (Wim Vogelaar) Date: Thu, 14 Jun 2007 14:31:08 +0200 Subject: IndentationError: unexpected indent References: Message-ID: <467134fe$0$66966$dbd49001@news.wanadoo.nl> You have possibly unvisible tab characters in your file. Just copy your lines to the simple MS notepad and try again. Wim Vogelaar, http://home.wanadoo.nl/w.h.vogelaar/ From dak at gnu.org Sat Jun 23 03:26:29 2007 From: dak at gnu.org (David Kastrup) Date: Sat, 23 Jun 2007 09:26:29 +0200 Subject: The Modernization of Emacs: terminology buffer and keybinding References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182272495.990807.99110@a26g2000pre.googlegroups.com> <87tzt3ihev.fsf@kobe.laptop> <1182370216.961241.6960@n60g2000hse.googlegroups.com> <85zm2ufjpb.fsf@lola.goethe.zz> <1182372592.803332.288260@u2g2000hsc.googlegroups.com> <1182549094.366282.286740@m37g2000prh.googlegroups.com> Message-ID: <85odj7b07u.fsf@lola.goethe.zz> Twisted writes: > HOW IN THE BLOODY HELL IS IT SUPPOSED TO OCCUR TO SOMEONE TO ENTER > THEM, GIVEN THAT THEY HAVE TO DO SO TO REACH THE HELP THAT WOULD > TELL THEM THOSE ARE THE KEYS TO REACH THE HELP?! Because there is a menu called "HELP" and because the "standard" keybinding for help, f1, brings up help? Not to mention that there is an initial splash screen pointing this out? -- David Kastrup, Kriemhildstr. 15, 44793 Bochum From cowie.rob at gmail.com Tue Jun 19 19:20:19 2007 From: cowie.rob at gmail.com (Rob Cowie) Date: Tue, 19 Jun 2007 16:20:19 -0700 Subject: easy_install from svn In-Reply-To: <46782AC9.6040501@web.de> References: <1182269819.795671.43860@k79g2000hse.googlegroups.com> <46782AC9.6040501@web.de> Message-ID: <1182295219.373283.289010@k79g2000hse.googlegroups.com> On Jun 19, 8:13 pm, Stefan Behnel wrote: > Rob Cowie wrote: > > I currently use easy_install to install packages from a custom, > > locally hosted package_index. The index consists of a single html doc > > with a list of package names and urls. All works well. > > > I would like to get a little more sophisticated and install a package > > from subversion. > > > My package is structured as described in the setuptools docs. > > > Simply pointing the url in my package index to svn://my/repo/package/trunk > > works, but I would like - and I get the impression it is possible - to > > be able to specify a revision number, or a tag and have that version > > installed. > > > Is it simply a case of appending a fragment to the url? > > Would anyone be so kind as to provide a working example? > > This is how we do it for lxml: > > http://cheeseshop.python.org/pypi/lxml/1.2.1 > > Stefan Thanks. I guess I was wrong in thinking that one could add a revision number to the url fragment and have easy_install get that revision. Instead, I should explicitly specify the urls in the package index (and/or setup.py) and identify them with the fragment. So, to make a head version and a tag available, the following urls must be in the package index: svn://svn/my/repo/package/trunk#egg=package-dev svn://svn/my/repo/package/tags/r1.0#egg=package-1.0 and install them thus... easy_install -i http://may/index package==dev | package==1.0 cheers, Rob Cowie From conor.robinson at gmail.com Thu Jun 14 17:39:40 2007 From: conor.robinson at gmail.com (py_genetic) Date: Thu, 14 Jun 2007 21:39:40 -0000 Subject: Efficient way of generating original alphabetic strings like unix file "split" In-Reply-To: <87d4zyqoy5.fsf@merkury.smsnet.pl> References: <1181846461.238047.84140@j4g2000prf.googlegroups.com> <87d4zyqoy5.fsf@merkury.smsnet.pl> Message-ID: <1181857180.456039.252940@q19g2000prn.googlegroups.com> > > You didn't try hard enough. :) > > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/190465 > > -- > HTH, > Rob Thanks Rob, "permutation" was the keyword I shcould have used! From lee at bustech.com Wed Jun 20 17:52:39 2007 From: lee at bustech.com (Lee Merrill) Date: Wed, 20 Jun 2007 17:52:39 -0400 Subject: Looking for a wxPython GUI builder In-Reply-To: <8726.51200411401$1181956756@news.gmane.org> References: <8726.51200411401$1181956756@news.gmane.org> Message-ID: Dick Moores wrote: > And which ones do people > actually use? Commercial or Freeware. I have tried SPE/wxGlade/pycard and a few others and still use xrced, it does basically what I need, it does the grunt work of fitting together the windows and sizers so I don't put a sizer where there should be a window etc. So I find xrced quite satisfactory, it seems sometimes being unambitious is the best ambition... Lee From mensanator at aol.com Thu Jun 14 17:54:01 2007 From: mensanator at aol.com (mensanator at aol.com) Date: Thu, 14 Jun 2007 14:54:01 -0700 Subject: Efficient way of generating original alphabetic strings like unix file "split" In-Reply-To: <87d4zyqoy5.fsf@merkury.smsnet.pl> References: <1181846461.238047.84140@j4g2000prf.googlegroups.com> <87d4zyqoy5.fsf@merkury.smsnet.pl> Message-ID: <1181858041.964498.38910@e9g2000prf.googlegroups.com> On Jun 14, 3:08 pm, Rob Wolfe wrote: > py_genetic writes: > > Hi, > > > I'm looking to generate x alphabetic strings in a list size x. This > > is exactly the same output that the unix command "split" generates as > > default file name output when splitting large files. > > > Example: > > > produce x original, but not random strings from english alphabet, all > > lowercase. The length of each string and possible combinations is > > dependent on x. You don't want any repeats. > > > [aaa, aab, aac, aad, .... aax, ...... bbc, bbd, .... bcd] > > > I'm assumming there is a slick, pythonic way of doing this, besides > > writing out a beast of a looping function. I've looked around on > > activestate cookbook, but have come up empty handed. Any suggestions? > > You didn't try hard enough. :) > > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/190465 Unfortunately, that's a very poor example. The terminaology is all wrong. "xpermutations takes all elements from the sequence, order matters." This ought to be the Cartesian Product, but it's not (no replacement). "xcombinations takes n distinct elements from the sequence, order matters." If order matters, it's a PERMUTATION, period. "xuniqueCombinations takes n distinct elements from the sequence, order is irrelevant." No such thing, a Combination is unique by definition. "xselections takes n elements (not necessarily distinct) from the sequence, order matters." Ah, this allows a size operator, so if size = length, we get full Cartesian Product. The proper terminology for the Cartesian Product and its subsets is: Permutations with replacement Combinations with replacement Permutations without replacement Combinations without replacement And if the functions were properly labeled, you would get: permutation without replacement - size 4 Permutations of 'love' love loev lvoe lveo leov levo olve olev ovle ovel oelv oevl vloe vleo vole voel velo veol elov elvo eolv eovl evlo evol permutation without replacement - size 2 Combinations of 2 letters from 'love' lo lv le ol ov oe vl vo ve el eo ev combination without replacement - size 2 Unique Combinations of 2 letters from 'love' lo lv le ov oe ve permutation with replacement - size 2 Selections of 2 letters from 'love' ll lo lv le ol oo ov oe vl vo vv ve el eo ev ee full Cartesian Product, permutations with replacement - size 4 Selections of 4 letters from 'love' llll lllo lllv llle llol lloo llov lloe llvl llvo llvv llve llel lleo llev llee loll lolo lolv lole lool looo loov looe lovl lovo lovv love loel loeo loev loee lvll lvlo lvlv lvle lvol lvoo lvov lvoe lvvl lvvo lvvv lvve lvel lveo lvev lvee lell lelo lelv lele leol leoo leov leoe levl levo levv leve leel leeo leev leee olll ollo ollv olle olol oloo olov oloe olvl olvo olvv olve olel oleo olev olee ooll oolo oolv oole oool oooo ooov oooe oovl oovo oovv oove ooel ooeo ooev ooee ovll ovlo ovlv ovle ovol ovoo ovov ovoe ovvl ovvo ovvv ovve ovel oveo ovev ovee oell oelo oelv oele oeol oeoo oeov oeoe oevl oevo oevv oeve oeel oeeo oeev oeee vlll vllo vllv vlle vlol vloo vlov vloe vlvl vlvo vlvv vlve vlel vleo vlev vlee voll volo volv vole vool vooo voov vooe vovl vovo vovv vove voel voeo voev voee vvll vvlo vvlv vvle vvol vvoo vvov vvoe vvvl vvvo vvvv vvve vvel vveo vvev vvee vell velo velv vele veol veoo veov veoe vevl vevo vevv veve veel veeo veev veee elll ello ellv elle elol eloo elov eloe elvl elvo elvv elve elel eleo elev elee eoll eolo eolv eole eool eooo eoov eooe eovl eovo eovv eove eoel eoeo eoev eoee evll evlo evlv evle evol evoo evov evoe evvl evvo evvv evve evel eveo evev evee eell eelo eelv eele eeol eeoo eeov eeoe eevl eevo eevv eeve eeel eeeo eeev eeee And Combinations with replacement seems to be missing. > > -- > HTH, > Rob- Hide quoted text - > > - Show quoted text - From martin at v.loewis.de Mon Jun 25 01:26:33 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Mon, 25 Jun 2007 07:26:33 +0200 Subject: socket on cygwin python In-Reply-To: <1182748882.617588.190230@c77g2000hse.googlegroups.com> References: <1182748882.617588.190230@c77g2000hse.googlegroups.com> Message-ID: <467f5209$0$26251$9b622d9e@news.freenet.de> bacon.chao at gmail.com schrieb: > I've installed cygwin with latest python 2.5.1, but it seems that the > socket lib file do NOT support IPv6(cygwin\lib\python2.5\lib-dynload > \_socket.dll), what can I do if I want to use IPv6? Use the Python binaries from python.org. If that is not acceptable, recompile Python for Cygwin to use WinSock2. Regards, Martin From showell30 at yahoo.com Fri Jun 1 06:23:20 2007 From: showell30 at yahoo.com (Steve Howell) Date: Fri, 1 Jun 2007 03:23:20 -0700 (PDT) Subject: file reading by record separator (not line by line) In-Reply-To: <465ff00c$0$323$e4fe514c@news.xs4all.nl> Message-ID: <206029.26955.qm@web33501.mail.mud.yahoo.com> --- Tijs wrote: > Steve Howell wrote: > > [...] but I wonder if the Python community > > couldn't help a lot of newbies (or insufficiently > > caffeinated non-newbies) by any of the following: > > > Well, I'm not a newbie, and I always make sure to be > thoroughly caffeinated > before sitting down for coding. :) > But I think the > itertools example in the > parent post shows a problem with that package: > unless you have intimate > knowledge of the package, it is not clear what the > code does when reading > it. In other words, it is not intuitive. > Agreed. > Perhaps a dedicated "block-read" module that wraps > any read()-able object > would be better. At least it would immediately be > clear what the code > means. > > from blockread import BlockReader > > b = BlockReader(f, boundary='>') > for block in b: > # whatever > Yep, I like this idea. You might have a few variations: def simple_block_reader(f, start_char='>'): # returns list or iterator where each item # is a list of lines all belonging to the same # block def regex_block_reader(f, start_regex, end_regex=None): # start_regex is regular expression to match on # if end_regex is none, then end of block is # signified by start of next block or end of file def block_reader3(f, start_method, end_method=None): # start_method, end_method should be functions # that evaluate line, return True/False # # if end_method is None, then end of block is # signified by start of next block or end of # input stream ____________________________________________________________________________________ Sick sense of humor? Visit Yahoo! TV's Comedy with an Edge to see what's on, when. http://tv.yahoo.com/collections/222 From bbxx789_05ss at yahoo.com Tue Jun 26 05:49:12 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: Tue, 26 Jun 2007 02:49:12 -0700 Subject: can't start Apache on Mac OS X--no listening sockets available? In-Reply-To: <1182844415.398825.306380@o11g2000prd.googlegroups.com> References: <1182824632.015853.317970@g4g2000hsf.googlegroups.com> <1182826067.067254.247940@j4g2000prf.googlegroups.com> <1182838193.195172.206160@u2g2000hsc.googlegroups.com> <1182844415.398825.306380@o11g2000prd.googlegroups.com> Message-ID: <1182851352.173384.45770@k79g2000hse.googlegroups.com> > Console and the system logs are an invaluable debugging tool on Macs. > Bet you have some errors there saying why apache couldnt stop/start. > What/where is Console and how do I look at the system logs? From jackt123 at gmail.com Sun Jun 24 21:03:06 2007 From: jackt123 at gmail.com (JackT) Date: Mon, 25 Jun 2007 01:03:06 -0000 Subject: The Modernization of Emacs: terminology buffer and keybinding In-Reply-To: <87wsxsam2w.fsf@telesippa.clsnet.nl> References: <87tzt3ihev.fsf@kobe.laptop> <1182370216.961241.6960@n60g2000hse.googlegroups.com> <85zm2ufjpb.fsf@lola.goethe.zz> <1182372592.803332.288260@u2g2000hsc.googlegroups.com> <1182373919.262388.100740@c77g2000hse.googlegroups.com> <85r6o6fhkb.fsf@lola.goethe.zz> <1182375045.626510.188170@m36g2000hse.googlegroups.com> <85myyufgwj.fsf@lola.goethe.zz> <1182375528.985142.293900@q69g2000hsb.googlegroups.com> <1182545268.055596.228700@i38g2000prf.googlegroups.com> <1182661040.286559.150880@q75g2000hsh.googlegroups.com> <1182731526.329068.101540@c77g2000hse.googlegroups.com> <1182732527.577903.63600@q75g2000hsh.googlegroups.com> <87wsxsam2w.fsf@telesippa.clsnet.nl> Message-ID: <1182733386.404922.24200@w5g2000hsg.googlegroups.com> On Jun 25, 12:56 am, Cor Gest wrote: > Some entity, AKA JackT wrote this mindboggling stuff: > (selectively-snipped-or-not-p) No need to be insulting. > > > We don't care about the 1970 version ofEmacs, > > because of course back then there WAS NO GUI. > > But if you are blind as bat, any 2007's GUI is useless. > You may have missed part of the discussion. Today's GNU emacs will still run with most of its features (even keyboard-driven text-drawn menu) when you run it on a GUI-less environment. At the same time, today's GNU emacs, when run on a GUI, will be able to pop up file-selection menus, display colors, etc. etc. - JackT From robin at reportlab.com Mon Jun 18 13:19:18 2007 From: robin at reportlab.com (Robin Becker) Date: Mon, 18 Jun 2007 18:19:18 +0100 Subject: avoid script running twice In-Reply-To: References: <4676AB35.7060500@chamonix.reportlab.co.uk> Message-ID: <4676BE96.5030404@chamonix.reportlab.co.uk> Evan Klitzke wrote: ........ > > Another method that you can use is to open up a socket on some > predetermined port (presumably above 1024), and then have your program > try to connect to that port and "talk" to the other program to > determine whether or not to run (or whether to do some of the > remaining work, etc.). > that might work, but this runs on someone's java solaris box with possible many connections going on. I doubt I'd be able to guarantee a particular port. -- Robin Becker From sjmachin at lexicon.net Mon Jun 18 19:12:50 2007 From: sjmachin at lexicon.net (John Machin) Date: Mon, 18 Jun 2007 16:12:50 -0700 Subject: cStringIO unicode weirdness In-Reply-To: <7x7iq0j2ik.fsf@ruckus.brouhaha.com> References: <7x7iq0j2ik.fsf@ruckus.brouhaha.com> Message-ID: <1182208370.045447.217020@n15g2000prd.googlegroups.com> On Jun 19, 8:56 am, Paul Rubin wrote: > Python 2.5 (r25:51908, Oct 6 2006, 15:24:43) > [GCC 4.1.2 20060928 (prerelease) (Ubuntu 4.1.1-13ubuntu4)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> import StringIO, cStringIO > >>> StringIO.StringIO('a').getvalue() > 'a' > >>> cStringIO.StringIO('a').getvalue() > 'a' > >>> StringIO.StringIO(u'a').getvalue() > u'a' > >>> cStringIO.StringIO(u'a').getvalue() > 'a\x00\x00\x00' > >>> > > I would have thought StringIO and cStringIO would return the > same result for this ascii-encodeable string. Looks like a bug to me. > Worse: > > >>> StringIO.StringIO(u'a').getvalue().encode('utf-8').decode('utf-8') > u'a' > > does the right thing, but > > >>> cStringIO.StringIO(u'a').getvalue().encode('utf-8').decode('utf-8') > u'a\x00\x00\x00' > > looks bogus. Am I misunderstanding something? Not worse, no more bogus than before. Note that an explicit design feature of utf8 is that ASCII characters (ord(c) < 128) are unchanged by the transformation. >>> 'a\x00\x00\x00'.encode('utf-8') # IMPLICIT conversion to unicode (effectively .decode('ascii')), then encoding as utf8 'a\x00\x00\x00' # no change to original buggy result >>> >>> 'a\x00\x00\x00'.decode('utf-8') u'a\x00\x00\x00' # as expected >>> From oscartheduck at gmail.com Fri Jun 22 18:07:26 2007 From: oscartheduck at gmail.com (oscartheduck) Date: Fri, 22 Jun 2007 22:07:26 -0000 Subject: regular expression concatenation with strings In-Reply-To: <1182546637.032673.106920@a26g2000pre.googlegroups.com> References: <1182543519.337279.25800@z28g2000prd.googlegroups.com> <1182546637.032673.106920@a26g2000pre.googlegroups.com> Message-ID: <1182550046.089794.153040@x35g2000prf.googlegroups.com> Got it: #!/usr/bin/env python from PIL import Image import glob, os, re size = 128, 128 def thumbnailer(dir, filenameRx): for picture in [ p for p in os.listdir(dir) if os.path.isfile(os.path.join( dir,p)) and filenameRx.match(p) ]: file, ext = os.path.splitext(picture) im = Image.open (picture) im.thumbnail(size, Image.ANTIALIAS) im.save(file + ".thumbnail" + ext) jpg = re.compile(".*\.(jpg|jpeg)", re.IGNORECASE) thumbnailer(".", jpg) The answer was sitting in front of my eyes. What is your code doing? It looks like: for $foo in [current working directory] if $foo is a file and foo's name matches the regex From josiah.carlson at sbcglobal.net Wed Jun 6 12:35:06 2007 From: josiah.carlson at sbcglobal.net (Josiah Carlson) Date: Wed, 06 Jun 2007 09:35:06 -0700 Subject: lists - append - unique and sorted In-Reply-To: References: <1181143597.563633.241640@o5g2000hsb.googlegroups.com> Message-ID: Neil Cerutti wrote: > On 2007-06-06, rhXX wrote: >> and/or >> >> - SORTED - INSERT in the correct place using some criteria? > > Consult the Python Docs about the heapq module. Heaps (as produced by heapq) are not sorted. This will not produce correct results unless one then pops everything and de-dupes the output. As Diez has already said, 'use the bisect module' . - Josiah From bohnenkamp at mevisbreastcare.de Thu Jun 21 03:56:19 2007 From: bohnenkamp at mevisbreastcare.de (Sascha Bohnenkamp) Date: Thu, 21 Jun 2007 09:56:19 +0200 Subject: The Modernization of Emacs In-Reply-To: <1182378809.880265.314150@o61g2000hsh.googlegroups.com> References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182344981.372713.298580@w5g2000hsg.googlegroups.com> <86y7ieoiv7.fsf@lola.quinscape.zz> <1182378809.880265.314150@o61g2000hsh.googlegroups.com> Message-ID: <5dup93F35nekiU1@mid.individual.net> E M A C S i e n o w g g d n a h a t p t b i p y n i t o n e u g s s l o y f m e m o r y From JohnRoth1 at jhrothjr.com Mon Jun 25 23:50:11 2007 From: JohnRoth1 at jhrothjr.com (John Roth) Date: Tue, 26 Jun 2007 03:50:11 -0000 Subject: Looking for an interpreter that does not request internet access In-Reply-To: References: Message-ID: <1182829811.698212.62490@u2g2000hsc.googlegroups.com> On Jun 25, 7:07 pm, James Alan Farrell wrote: > Hello, > I recently installed new anti-virus software and was surprised the > next time I brought up IDLE, that it was accessing the internet. > > I dislike software accessing the internet without telling me about it, > especially because of my slow dial up connection (there is no option > where I live), but also because I feel it unsafe. > > Can anyone recommend an interpreter that does not access the internet > when it starts (or when it is running, unless I specifically write a > program that causes it to do so, so as a browser)? > > James Alan Farrell One of two things is going on. Either the anti-virus program you installed is so clueless that it doesn't understand "localhost" or the IP address equivalent, or IDLE (or it's subprocess) is opening the socket in promiscuous mode. Either one will give you that symptom. There are definitely anti-virus products that are that clueless. Scream at the vendor. I doubt if it's Idle, but I'm not in the mood to check the code to see if it's doing it right. John Roth From zapman449 at gmail.com Mon Jun 25 11:02:26 2007 From: zapman449 at gmail.com (Jason Zapman II) Date: Mon, 25 Jun 2007 08:02:26 -0700 Subject: How to save initial configuration? (program installation) Message-ID: <1182783746.718276.209460@w5g2000hsg.googlegroups.com> I've written a program. To install this program, I'm going to need to initialize some stuff for the users environment, specifically the name/ location of an internal state file. Currently, I'm hard coding the location of this file, but that's in- elegant. What I'd like to do is just ask the user, with a suggested default. My question is how do I save this answer? It's kind of a chicken-and- egg problem. The only solution I've thought of is to write something that's self modifying, but that's ugly (go in, grep for this variable initialization, re-write that line with the new value, quit). Is there a better way to do this? There almost has to be... If not, are there some 'best practices' on how to do the self- modification? Thanks for any help; Jason From luismgz at gmail.com Sat Jun 30 04:27:12 2007 From: luismgz at gmail.com (=?iso-8859-1?q?Luis_M=2E_Gonz=E1lez?=) Date: Sat, 30 Jun 2007 08:27:12 -0000 Subject: Shed Skin Python-to-C++ Compiler 0.0.21, Help needed In-Reply-To: References: <8180ef690703310255q55572efaqc512b968504e2c1b@mail.gmail.com> Message-ID: <1183192032.484293.175200@o61g2000hsh.googlegroups.com> On Jun 29, 7:48 am, "Mark Dufour" wrote: > Hi all, > > I have just released version 0.0.22 of Shed Skin, an experimental > Python-to-C++ compiler. Among other things, it has the exciting new > feature of being able to generate (simple, for now) extension modules, > so it's much easier to compile parts of a program and use them (by > just importing them). Here's the complete changelog: > > -support for generating simple extension modules (linux/windows; see README) > -dos text format fix (long overdue) > -improved detection of dynamic types (avoid hanging on them) > -improved overloading (__nonzero__, __int__, __abs__ etc.) > -add str(ing).{capitalize, capwords, swapcase, center, ato*) > -fix string.maketrans > -several other minor bug fixes > > For more details about Shed Skin and a collection of 27 programs, at a > total of about 7,000 lines, that it can compile (resulting in an > average speedup of about 39 times over CPython and 11 times over Psyco > on my computer), please visit the homepage at: > > http://mark.dufour.googlepages.com > > I could really use some help in pushing Shed Skin forward. Please try > the latest release and send in bug reports, or join the project via > the homepage. > > Thanks, > Mark Dufour. > > On 3/31/07, Mark Dufour wrote: > > > > > Hi all, > > > I have recently released version 0.0.20 and 0.0.21 of Shed Skin, an > > optimizing Python-to-C++ compiler. Shed Skin allows for translation of > > pure (unmodified), implicitly statically typed Python programs into > > optimized C++, and hence, highly optimized machine language. Besides > > many bug fixes and optimizations, these releases add the following > > changes: > > > -support for 'bisect', 'collections.deque' and 'string.maketrans' > > -improved 'copy' support > > -support for 'try, else' construction > > -improved error checking for dynamic types > > -printing of floats is now much closer to CPython > > > For more details about Shed Skin and a collection of 27 programs, at a > > total of about 7,000 lines, that it can compile (resulting in an > > average speedup of about 39 times over CPython and 11 times over Psyco > > on my computer), please visit the homepage at: > > >http://mark.dufour.googlepages.com > > > I could really use more help it pushing Shed Skin further. Simple ways > > to help out, but that can save me lots of time, are to find smallish > > code fragments that Shed Skin currently breaks on, and to help > > improve/optimize the (C++) builtins and core libraries. I'm also > > hoping someone else would like to deal with integration with CPython > > (so Shed Skin can generate extension modules, and it becomes easier to > > use 'arbitrary' external CPython modules such as 're' and 'pygame'.) > > Finally, there may be some interesting Master's thesis subjects in > > improving Shed Skin, such as transforming heap allocation into stack- > > and static preallocation, where possible, to bring performance even > > closer to manual C++. Please let me know if you are interested in > > helping out, and/or join the Shed Skin mailing list. > > > Thanks! > > Mark Dufour. > > -- > > "One of my most productive days was throwing away 1000 lines of code" > > - Ken Thompson > > Mark Dufour. > -- > "One of my most productive days was throwing away 1000 lines of code" > - Ken Thompson I love it! This is absolutely fantastic!!! I can't belive I can write extension modules that easily... Keep up the good work and thank you!!! Luis From python-url at phaseit.net Mon Jun 4 13:05:38 2007 From: python-url at phaseit.net (Gabriel Genellina) Date: Mon, 4 Jun 2007 17:05:38 +0000 (UTC) Subject: Python-URL! - weekly Python news and links (Jun 4) Message-ID: QOTW: "Stop thinking of three lines as 'extensive coding' and your problem disappears immediately." - Steve Holden "Hey, did you hear about the object-oriented version of COBOL? They call it 'ADD ONE TO COBOL'." - Tim Roberts EuroPython: Registration is open! http://www.europython.org/sections/registration_issues/registration-open EuroPython in the Python411 Podcast Series http://www.europython.org/sections/tracks_and_talks/announcements/europython-in-python411 Python 2.5 appears to give wrong results on Windows for file creation/modification/last access time - but no, it's right, although the differences are a bit hard to explain: http://groups.google.com/group/comp.lang.python/browse_thread/thread/890eef2197c6f045 http://groups.google.com/group/comp.lang.python/browse_thread/thread/2a73854b3f835d78 The right way to handle Unicode filenames, including Zip archives: http://groups.google.com/group/comp.lang.python/browse_thread/thread/4d39da08fdddc48b/ The concept of "active exception" may be a bit obscure - see a great clarification by Duncan Booth in this thread: http://groups.google.com/group/comp.lang.python/browse_thread/thread/74dc5145c2bb558b However widely it's believed that items in a Tkinter listbox can't be differentially colored, rfg007 knows better: http://groups.google.com/group/comp.lang.python/browse_thread/thread/a7276ce6910019e5/ itertools.groupby is a great tool. Trying to improve the documentation, contributors arrive at pleasing examples: http://groups.google.com/group/comp.lang.python/browse_thread/thread/7ef930186a8e5e4c/ What people like about Python, pitfalls, desired features, misfeatures, all in a rather serious and objective thread called -of course- "Python rocks!" :) http://groups.google.com/group/comp.lang.python/browse_thread/thread/2a771ba3d329d57 Python and memory handling: why you don't notice the freed memory, why one should not care, and details on the "small-object allocator" http://groups.google.com/group/comp.lang.python/browse_thread/thread/5d3a5a37048e707e/ If you are concerned on how __special__ methods map onto the internal type structures, or just curious about that, these comments may be useful: http://groups.google.com/group/comp.lang.python/browse_thread/thread/e86275f51899b0a5/ ======================================================================== 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. The Python Papers aims to publish "the efforts of Python enthusiats". http://pythonpapers.org/ 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 Steve Bethard continues the marvelous tradition early borne by Andrew Kuchling, Michael Hudson, Brett Cannon, Tony Meyer, and Tim Lesher of intelligently summarizing action on the python-dev mailing list once every other week. http://www.python.org/dev/summary/ The Python Package Index catalogues packages. http://www.python.org/pypi/ The somewhat older Vaults of Parnassus ambitiously collects references to all sorts of Python resources. http://www.vex.net/~x/parnassus/ Much of Python's real work takes place on Special-Interest Group mailing lists http://www.python.org/sigs/ 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 erikwickstrom at gmail.com Sun Jun 3 14:52:07 2007 From: erikwickstrom at gmail.com (erikcw) Date: Sun, 03 Jun 2007 18:52:07 -0000 Subject: Is 1 large Regex faster than 3 smaller ones? Message-ID: <1180896727.419817.303960@p47g2000hsd.googlegroups.com> Hi, I need to match 3 small strings in a small text file (about 200 words of text). Would it be faster to write 1 compiled regex that matches all 3 substrings in one go, or to use 3 separate regular expressions to do the same job? Thanks! Erik From horpner at yahoo.com Thu Jun 28 08:23:35 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Thu, 28 Jun 2007 12:23:35 GMT Subject: listing the type of an object References: <71af3$4682d18c$d443bb3a$9028@news.speedlinq.nl> <46836088$0$29024$426a74cc@news.free.fr> Message-ID: On 2007-06-28, Bruno Desthuilliers wrote: > Stef Mientki a ?crit : >> How can I list a type of an object instance ? >> >> I tried: >> >> class tLED (tDevice): > > > Do yourself (and the world) a favour and give up hungarian notation... > This should be: > > class Led(Device): > #... Using a naming convention for class objects, e.g., camel-case, is a practice very similar to hungarian notation. I would've said something like: start learning the Python community's naming conventions, and use those instead of inventing your own. -- Neil Cerutti It will work out, somehow. That's a hell of a duo right there, Marbury, Crawford and Houston. --Carmelo Anthony From steveg at moregruel.net Thu Jun 21 17:05:01 2007 From: steveg at moregruel.net (Steve Greenland) Date: 21 Jun 2007 21:05:01 GMT Subject: Logger vs. Handler log levels Message-ID: <467ae7fc$0$63185$a726171b@news.hal-pc.org> Apparently I don't understand logging levels. The code: import logging, logging.handlers logging.basicConfig(level=logging.WARNING) newlog = logging.handlers.TimedRotatingFileHandler( filename='/home/steveg/logtest.log', when="midnight") newlog.setLevel(logging.INFO) logging.getLogger().addHandler(newlog) logging.info("Message from logtest") logging.debug("Debug message from logtest") doesn't print on the console (as expected), but also doesn't add the first message to the file. Changing the basicConfig() call to set the level to 'level.DEBUG' shows both messages on the console, and only the first in the file, which is what I did expect. I suspect my confusion is the distinction between "handler" and "logger". It appears that the logger won't pass any messages lower than its level to any of its handlers. If I read the docs, what I need is to do is have the root logger left at NOTSET, but then there doesn't seem to be any way to set the level on the default stream handler. Have I diagnosed the problem correctly? Is the only (or at least, correct) solution to ignore the default handler and create my own console and file handlers, setting levels as desired? Thanks, Steve -- Steve Greenland The irony is that Bill Gates claims to be making a stable operating system and Linus Torvalds claims to be trying to take over the world. -- seen on the net From walterbyrd at iname.com Mon Jun 25 10:14:23 2007 From: walterbyrd at iname.com (walterbyrd) Date: Mon, 25 Jun 2007 07:14:23 -0700 Subject: Collections of non-arbitrary objects ? In-Reply-To: <467ed491$0$27132$426a34cc@news.free.fr> References: <1182449993.223262.229500@z28g2000prd.googlegroups.com> <87k5twx4hf.fsf@benfinney.id.au> <1182559502.069773.321620@i38g2000prf.googlegroups.com> <87wsxvrzsj.fsf@benfinney.id.au> <1182620734.940718.196520@e16g2000pri.googlegroups.com> <467ed491$0$27132$426a34cc@news.free.fr> Message-ID: <1182780863.067601.89320@d30g2000prg.googlegroups.com> On Jun 24, 10:31 pm, Bruno Desthuilliers wrote: > > Especially since variables in python do not have to be explicitly > > assigned > > ??? I have probably expressed this incorrectly. What I meant was: >>> a = [1,2,3] >>> b = a >>> a[1] = 'spam' Here, I have changed b, without an explicit assignment. After I assigned a to b, I never did another "b =" yet b changed anyway because I changed a. I am not saying there is anything wrong with this, I'm just explaining what I meant. So let's say I have list L, and I have a routine that expects every item in L to be a dictionary like: {'name':'joe', 'job':'dev', 'pay': min_wage}. Not only could the app crash if an incorrect item where inserted into L. But the app could crash if an incorrect item were inserted in lists X,Y, or Z. Of course, you can always work around this by just programming very carefully, and doing a lot of error checking. That is always true in any language. But, I think sometimes it's helpful to use a structure that is little more restrictive, to sort of enforce a degree of integrity. An example I have already given: why use tuples instead of a list? Tuples are actually a bit more restrictive. I don't think there is anything wrong with the data structures that exist in python. I was just wondering if there was a structure that would restrict a collection to only allow certain types. The "restrictedlist" class discussed in another thread may be the sort of thing I was looking for. BTW: I think polymorphism is great and all. But it does have (and IMO should have) it's limitations. For example, I don't think you can divide a string by another string. From half.italian at gmail.com Tue Jun 26 04:36:13 2007 From: half.italian at gmail.com (half.italian at gmail.com) Date: Tue, 26 Jun 2007 08:36:13 -0000 Subject: Tkinter: different results from the same tcl script In-Reply-To: References: Message-ID: <1182846973.665883.324830@e9g2000prf.googlegroups.com> On Jun 26, 1:06 am, Fabrizio Pollastri wrote: > Hello, > in mixed python-tcl programming I found the following different > behaviours of the same tcl script. > > If I type manually in the python interpreter the following lines > > >>> from Tkinter import * > >>> w = Tk() > >>> w.tk.evalfile('my_tcl_script.tcl') > > where my_tcl_script.tcl is > > #!/bin/sh > package require Tk > wm withdraw . > toplevel .root > wm title .root "My title" > > I obtain one toplevel window with title "My title", as expected. > > The same result is obtained with the tcl shell command > > % wish my_tcl_script.tcl > > Now, I wish to run the same instructions from a python script. So, I > written the following script > > from time import * > from Tkinter import * > w = Tk() > w.tk.evalfile('my_tcl_script.tcl') > sleep(3) > > I expected to see the same toplevel window for 3 seconds, but the result > of this python script is nothing, no window appears. > > If anybody can explain the different behaviour and how to normalize it > with the correct one, I will be very glad. Thank you in advance. > > F. Pollastri You need a call to `w.mainloop()` w=Tk() w.after(3000, lambda: w.quit()) w.mainloop() ~Sean From ErendisAldarion at gmail.com Sun Jun 24 20:58:25 2007 From: ErendisAldarion at gmail.com (Aldarion) Date: Sun, 24 Jun 2007 17:58:25 -0700 Subject: how to sorted by summed itemgetter(x) Message-ID: <1182733105.118722.86390@e16g2000pri.googlegroups.com> for example, let from operator import itemgetter items = [('a', [5, 2]), ('c', [1]), ('b', [6]), ('d', [7])] sorted(items, key = itemgetter(1)) get this back: [('c', [1]), ('a', [5, 2]), ('b', [6]), ('d', [7])] but sorted(items, key = sum(itemgetter(1))) raise a errer: 'operator.itemgetter' object is not iterable how to sorted by summed itemgetter(1)? maybe sorted(items,key = lambda x:sum(x[1])) can't itemgetter be used here? From claird at lairds.us Tue Jun 5 17:25:20 2007 From: claird at lairds.us (Cameron Laird) Date: Tue, 5 Jun 2007 21:25:20 +0000 Subject: Tkinter - resize tkMessageBox References: <1180988981.634298.38830@o11g2000prd.googlegroups.com> <1181026856.261957.207570@q75g2000hsh.googlegroups.com> Message-ID: <0v0hj4-pip.ln1@lairds.us> In article <1181026856.261957.207570 at q75g2000hsh.googlegroups.com>, Glenn Hutchings wrote: >On 4 Jun, 21:29, rahulna... at yahoo.com wrote: >> Is there a way to resize the width of the "tkMessageBox.askyesno" >> dialog box, so that the text does not wrap to the next line. > >You can use the Tk option database, either explicitly or from a file. >For example, to set the wrap length of all dialogs to 10 inches, try >this: > > root = Tk() > root.option_add("*Dialog.msg.wrapLength", "10i") . . . But that does *not* affect the MessageBoxes under MacOS and Windows, right? From mccredie at gmail.com Tue Jun 26 14:49:59 2007 From: mccredie at gmail.com (Matimus) Date: Tue, 26 Jun 2007 18:49:59 -0000 Subject: problem mixing gettext and properties In-Reply-To: <1182880358.100599.139120@j4g2000prf.googlegroups.com> References: <1182880358.100599.139120@j4g2000prf.googlegroups.com> Message-ID: <1182883799.883429.13880@g37g2000prf.googlegroups.com> On Jun 26, 10:52 am, Andr? wrote: > I've encountered a problem using gettext with properties while using a > Python interpreter. > > Here's a simple program that illustrate the problem. > ============== > # i18n_test.py: test of gettext & properties > > import gettext > > fr = gettext.translation('i18n_test', './translations', > languages=['fr']) > fr.install() > > help = _("Help me!") > > class Test_i18n(object): > def get(self): > __help = _("HELP!") > return __help > help_prop = property(get, None, None, 'help') > > test = Test_i18n() > > print help > print test.help_prop > #### end of file > > To run the above program, you need to have the strings translated and > the proper ".po" and ".mo" files created. (for those interested, I > can send the whole lot in a zip file) > > If I run the program as is, the output is: > Aidez-moi! > AIDE!!! > > Ok, let's try with the Python interpreter: > > ActivePython 2.4.2 Build 248 (ActiveState Corp.) based on > Python 2.4.2 (#67, Oct 30 2005, 16:11:18) [MSC v.1310 32 bit (Intel)] > on win32 > Type "help", "copyright", "credits" or "license" for more information.>>> import i18n_test > > Aidez-moi! > AIDE!!! > > # No surprise there so far. > > >>> print i18n_test.help > Aidez-moi! > >>> print i18n_test.test.help_prop > AIDE!!! > >>> i18n_test.help > > 'Aidez-moi!' > > # all of the above are as expected; now for the first surprise > > >>> i18n_test.test.help_prop > > Traceback (most recent call last): > File "", line 1, in ? > File "i18n_test.py", line 12, in get > __help = _("HELP!") > TypeError: 'str' object is not callable > > # and a second surprise where we try to repeat something that used to > work > > >>> print i18n_test.test.help_prop > > Traceback (most recent call last): > File "", line 1, in ? > File "i18n_test.py", line 12, in get > __help = _("HELP!") > TypeError: 'str' object is not callable > > #============= > > Dare I say: "Help!" I really need to use the above at the > interpreter prompt. > > Andr? In the interpreter "_" is used to store the return value of the last statement executed. So when this line is run: >>> i18n_test.help "_" is set to 'Aidez-moi!'. A possible fix, which I have not tested in your context, would be to explicitly set _ to _ after your module is loaded. So, try this: >>> import i18n_test >>> _ = i18n_test._ ... The rest of your code here I don't know for sure that this will work. From what I have tried though, assigning to _ seems to disable that feature of the interpreter. Matt From malaclypse2 at gmail.com Fri Jun 8 15:51:49 2007 From: malaclypse2 at gmail.com (Jerry Hill) Date: Fri, 8 Jun 2007 15:51:49 -0400 Subject: Binary In-Reply-To: <101441.49837.qm@web27905.mail.ukl.yahoo.com> References: <101441.49837.qm@web27905.mail.ukl.yahoo.com> Message-ID: <16651e80706081251h7ab0b9b3td816ef0424e3a841@mail.gmail.com> Brian, I'm including the list back in on this reply, so that more than just me can see your message and potentially help out. On 6/8/07, Brain Murphy wrote: > > this is what i have so far. > x= 100 > b=2 > while x > 0: > print x > x=divmod(x,b) > > the problem is that since it is a tuple I can not use that last part, x = > divmod(x,b) > how can I put this in a loop? > were it goes through the whole number, as in 100/2=50 50/2 25 ect. > but also keeping the remiander? Since divmod() returns a tuple, you need to unpack it. For example: >>> q, r = divmod(10, 3) >>> print q 3 >>> print r 1 If you want to store all the remainders as you go, maybe you could build up a list of remainders by starting with an empty list and append() the values to the list as you go through the loop. -- Jerry From benedict.verheyen at gmail.com Mon Jun 11 05:32:26 2007 From: benedict.verheyen at gmail.com (Benedict Verheyen) Date: Mon, 11 Jun 2007 11:32:26 +0200 Subject: python-ldap for Python 2.5 on Windows? In-Reply-To: References: <1181323389.805143.236480@i38g2000prf.googlegroups.com> Message-ID: Thorsten Kampe schreef: > * Benedict Verheyen (Mon, 11 Jun 2007 11:23:59 +0200) >> Waldemar Osuch schreef: >>> I have managed to build it for myself using MinGW: >>> http://www.osuch.org-a.googlepages.com/python-ldap-2.3.win32-py2.5.exe >>> >>> See if it will work for you >>> >> thanks for the installation file. >> When i installed it, i got an error stating "The setup files are corrupt". > > I downloaded and installed them. They work fine... I'm on Vista (boohoo :(), what's your platform? From dborne at gmail.com Sat Jun 16 21:31:06 2007 From: dborne at gmail.com (Dave Borne) Date: Sat, 16 Jun 2007 20:31:06 -0500 Subject: IndentationError: unexpected indent In-Reply-To: <46738a0e$0$95697$dbd4b001@news.wanadoo.nl> References: <46738a0e$0$95697$dbd4b001@news.wanadoo.nl> Message-ID: <6e42ec490706161831j64b990e8wa7d9ff70a5dd063b@mail.gmail.com> > It would be very helpful when Python would warn you when there are tabs in > your source. invoke python with the -t option for warnings about tabs or -tt for errors. -Dave From kyosohma at gmail.com Wed Jun 20 14:42:50 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Wed, 20 Jun 2007 11:42:50 -0700 Subject: Controlling Firefox with Python In-Reply-To: <1182348300.106377.111100@u2g2000hsc.googlegroups.com> References: <1182286371.974090.80760@q75g2000hsh.googlegroups.com> <46784c34$0$5104$ba4acef3@news.orange.fr> <1182348300.106377.111100@u2g2000hsc.googlegroups.com> Message-ID: <1182364970.854846.158650@k79g2000hse.googlegroups.com> On Jun 20, 9:05 am, kyoso... at gmail.com wrote: > On Jun 19, 4:35 pm, "M?ta-MCI" > wrote: > > > Hi! > > > See Mozlab: http://dev.hyperstruct.net/mozlab > > > and give a report, please. > > Thank you in advance. > > > Michel Claveau > > There seems to be some kind of weird bug with the current version of > MozLab. When I use telnet on my Windows XP box, it tries to evaluate > every character I type, which only results in lots of syntax errors. I > tried Putty in raw mode, and it works, but not well. Each line doesn't > get output to the far left. Instead, each line is dropped down one > line and tabbed over so it's one character ahead of the previous line. > > I assume you think I can use Python to telnet to a running MozLab to > execute my commands? I will need to be able to do this to all the > users on a network and installing extensions on everyone's PC will be > somewhat difficult. > > Mike UPDATE: I can do tab traversal in Firefox using the sendkeys method. I just need a way to read the label on the current tab or the title of the Firefox window. Any ideas? Mike From chris at shenton.org Tue Jun 5 15:38:31 2007 From: chris at shenton.org (Chris Shenton) Date: Tue, 05 Jun 2007 15:38:31 -0400 Subject: Logging: how to suppress default output when adding handlers? In-Reply-To: <1181054185.267953.181050@p47g2000hsd.googlegroups.com> (Vinay Sajip's message of "Tue\, 05 Jun 2007 07\:36\:25 -0700") References: <1181054185.267953.181050@p47g2000hsd.googlegroups.com> Message-ID: <86lkey6vk8.fsf@PECTOPAH.shenton.org> Vinay Sajip writes: > The default handler is created because you are calling the convenience > functions of the logging package: logging.error, etc. If you don't > want the default handler to be created, either > > (a) Configure the logging system yourself before any logging call is > made (I'm not sure why you're not doing this - it could be done in > your main script before anything else happens) - or Yeah, I think this is the cause. Unfortunately I'm using a couple dozen files and a bunch more libraries and if they're doing a logging.debug() or whatnot they're creating this. Do you have any ideas how I can trace where the first call is made? This seems a newbie question but if I have a bunch of other files which do stuff like "from sqlalchemy import *" they might be invoking a logging call so I'm not sure how to chase these down. > (b) Make calls on a specific named logger, e.g. > logging.getLogger("logtest2").error("foo"), rather than > logging.error("foo") which is for casual/unsophisticated use only. I'm dreading having to be so verbose with my (copious) loggers, which is why I was curious if there was a way to nuke any auto-created ones. I thought calling logging.shutdown() before configuring my loggers might do this but it didn't. Thanks. From vishnu at montalvosystems.com Wed Jun 20 01:27:17 2007 From: vishnu at montalvosystems.com (VishnuMohan) Date: Tue, 19 Jun 2007 22:27:17 -0700 Subject: measuring regression pass rate Message-ID: <1182317237.455867.83910@o11g2000prd.googlegroups.com> Hi, Is there a script available online something similar that can connect to the database, get the regression database results and display a graph of pass rate onto the web page. Thanks in advance, Regards, VishnuMohan From __peter__ at web.de Thu Jun 28 09:37:16 2007 From: __peter__ at web.de (Peter Otten) Date: Thu, 28 Jun 2007 15:37:16 +0200 Subject: problem with hack using multiple inheritance for plugins References: <1183026288.857294.91620@q69g2000hsb.googlegroups.com> <1183028051.940679.145680@q69g2000hsb.googlegroups.com> <46839f4c$0$22380$426a74cc@news.free.fr> <1183034478.587345.214570@w5g2000hsg.googlegroups.com> <1183036068.348031.240690@n60g2000hse.googlegroups.com> Message-ID: massimo s. wrote: > Again: using a new-style plugin class for multiple inheritance does > not work. This statement is certainly too broad. [earlier] > TypeError: unbound method _plug_init() must be called with > dummyguiplugGui instance as first argument (got MainWindowPlugged > instance instead) So it looks like you failed to make dummyguiplugGui a base class of MainWindowPlugged. > What can I do now? Post a self-contained example. Peter From gagsl-py2 at yahoo.com.ar Mon Jun 11 15:48:39 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 11 Jun 2007 16:48:39 -0300 Subject: Repository - file scanner References: <1181331239.609059.320740@g4g2000hsf.googlegroups.com> <1181515276.379978.136400@z28g2000prd.googlegroups.com> <1181581520.733087.253380@q66g2000hsg.googlegroups.com> <87zm36uy5g.fsf@rudin.co.uk> Message-ID: En Mon, 11 Jun 2007 15:46:51 -0300, Paul Rudin escribi?: > HMS Surprise writes: >>> >>> Why not use grep? >> >> With Windows XP? > > www.cygwin.com Why? Try findstr /? at the command prompt. -- Gabriel Genellina From david at boddie.org.uk Sun Jun 24 09:52:46 2007 From: david at boddie.org.uk (David Boddie) Date: Sun, 24 Jun 2007 15:52:46 +0200 Subject: how to query/test the state of a qt widget? Message-ID: <200706241552.46861.david@boddie.org.uk> On Sun Jun 24 02:20:55 CEST 2007, raacampbell wrote: > I'm writing a simple Python/Qt3 application and I am trying to write > some code in which the user presses a button and the program performs > action A or B depending upon the state of a pair of radio buttons. You would typically connect the button's clicked() signal to a function or method and perform the actions there. Since I don't know exactly what you are doing, I can't give you an exact answer, but you probably want to write something like this: self.connect(self.pushButton, SIGNAL("clicked()"), self.perform_action) This assumes that you're calling connect() from a QObject subclass. If not, you could call connect() on the button itself. > I would therefore like Python to read the state of the buttons. I was > expecting this to be straightforward but I've not been able to work > out how to do it and searching on Google hasn't helped. Surely there's > a one-liner that will do what I want? It seems like an every-day sort > of problem. I'm after something like: > > if self.polPlotRadioButton.enabled==1: print "BLAH" This is more or less what you would write in the method that gets invoked when the clicked() signal is emitted, though you would need to call enabled() since it's a method and not an attribute. > I've found squish from www.froglogic.com but that seems over the top. > Possibly pythonqt.sourceforge.net has something that will solve my > problem but that wants Qt4 and at the moment I'm making heavy use of > matplotlib widgets and I've not worked out how to get them to > incorporate into a Qt4 app so I'm stuck with Qt3. It's been a while since I've looked at using matplotlib with PyQt. Looking at the 0.90.1 release, it seems that there is support for PyQt4, so maybe you'll get what you need if you upgrade to that. I don't think you need Squish for this - it's a tool for automated user interface testing, and you're not doing that as far as I can tell. David From http Thu Jun 28 01:18:43 2007 From: http (Paul Rubin) Date: 27 Jun 2007 22:18:43 -0700 Subject: nested list comprehension and if clauses References: <1183007216.684569.222450@k79g2000hse.googlegroups.com> Message-ID: <7xbqf0y7v0.fsf@ruckus.brouhaha.com> Jyotirmoy Bhattacharya writes: > print [(m,n) for m in range(5) for n in multab(m) if m>2] > I was wondering if there is some way to write the if-clause so that it > is 'hoisted' out of the inner loop and the multab function is not > called at all for m=0,1,2. That would seem to be important if multab > were an expensive function. Maybe you mean print [(m,n) for m in [a for a in range(5) if a > 2] for n in multab(m)] You'd probably really write print [[(m,n) for m in range(3,5)] for n in multab(m)] You should also use xrange instead of range, if the range might be large. And you could use a generator expression instead of a listcomp for the inner list. From martin at v.loewis.de Sat Jun 2 06:04:22 2007 From: martin at v.loewis.de (=?ISO-8859-15?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sat, 02 Jun 2007 12:04:22 +0200 Subject: Python 2.5.1 broken os.stat module In-Reply-To: References: Message-ID: <466140A6.1090100@v.loewis.de> > Reviewing my code it seems that it should still work with the 2.5.1 os.stat > changes however that does not appear to be the case. > > Timestamps reported by os.stat() are no longer correct and the results are > not even consistent. I don't think this is the case. The results Python reports are correct and consistent. > In my first test case ALL 3 timestamps reported by Python are 1 hour less > than the actual timestamp on the file. No. Instead, your *rendering* of the time-stamp is 1 hour less than what you expect to see. This is because you render the time stamp according to the current time zone (which is daylight-saving), not according to the time-zone that was in effect when the file was created (which was regular time). > Assuming there is no error in the following code that prints out the > timestamps using the new return value from os.stat() then it would appear > that the 2.5.1 os.stat changes have a bug. > > print 'Creation Time: %s' % time.strftime('%m/%d/%Y %H:%M:%S', > time.localtime(file_stats[stat.ST_CTIME])) > print 'Last Access Time: %s' % time.strftime('%m/%d/%Y %H:%M:%S', > time.localtime(file_stats[stat.ST_ATIME])) > print 'Last Write Time: %s' % time.strftime('%m/%d/%Y %H:%M:%S', > time.localtime(file_stats[stat.ST_MTIME])) It's not clear whether it's an error, however, localtime() does something different from what dir does. Regards, Martin From blmblm at myrealbox.com Wed Jun 27 14:41:36 2007 From: blmblm at myrealbox.com (blmblm at myrealbox.com) Date: 27 Jun 2007 18:41:36 GMT Subject: The Modernization of Emacs: terminology buffer and keybinding References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182661040.286559.150880@q75g2000hsh.googlegroups.com> <5eaqjmF36ga72U1@mid.individual.net> <1182811569.871702.207010@n2g2000hse.googlegroups.com> Message-ID: <5efpavF392efmU1@mid.individual.net> In article <1182811569.871702.207010 at n2g2000hse.googlegroups.com>, Twisted wrote: > On Jun 25, 5:32 pm, blm... at myrealbox.com wrote: > > To me it's similar to "memorizing" a phone number by dialing > > it enough times that it makes its way into memory without > > conscious effort. I suspect that not everyone's brain works > > this way, and some people have to look it up every time. > > For those people, I can understand why something without a > > GUI could be a painful experience. "YMMV", maybe. > > You'll be happy to know then that my opinion is that the phone system > is archaic too. Happy? Not especially. Amused? Yes. One more, um, "eccentric"? opinion, from someone with many of them. [ snip ] -- B. L. Massingill ObDisclaimer: I don't speak for my employers; they return the favor. From twisted0n3 at gmail.com Wed Jun 20 17:38:48 2007 From: twisted0n3 at gmail.com (Twisted) Date: Wed, 20 Jun 2007 21:38:48 -0000 Subject: The Modernization of Emacs: terminology buffer and keybinding In-Reply-To: <85myyufgwj.fsf@lola.goethe.zz> References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182272495.990807.99110@a26g2000pre.googlegroups.com> <87tzt3ihev.fsf@kobe.laptop> <1182370216.961241.6960@n60g2000hse.googlegroups.com> <85zm2ufjpb.fsf@lola.goethe.zz> <1182372592.803332.288260@u2g2000hsc.googlegroups.com> <1182373919.262388.100740@c77g2000hse.googlegroups.com> <85r6o6fhkb.fsf@lola.goethe.zz> <1182375045.626510.188170@m36g2000hse.googlegroups.com> <85myyufgwj.fsf@lola.goethe.zz> Message-ID: <1182375528.985142.293900@q69g2000hsb.googlegroups.com> On Jun 20, 5:35 pm, David Kastrup wrote: > But Emacs does not have a "clunky" interface. That's for the everyday novice-to-intermediate user to decide. Your gnu.org email address (and attitude) clearly marks you as not a normal user, and so your opinion doesn't count. From gnewsg at gmail.com Thu Jun 14 16:26:52 2007 From: gnewsg at gmail.com (billiejoex) Date: Thu, 14 Jun 2007 13:26:52 -0700 Subject: os.path.normpath bug? Message-ID: <1181852812.831695.183610@i13g2000prf.googlegroups.com> Hi there, I've noticed that os.path.normpath does not collapse redundant separators if they're located at the beginning of the string: >>> print os.path.normpath('/a//b//c') \a\b\c >>> print os.path.normpath('//a//b//c') \\a\b\c Is it intentional or is it a bug? From grante at visi.com Fri Jun 1 10:33:58 2007 From: grante at visi.com (Grant Edwards) Date: Fri, 01 Jun 2007 14:33:58 -0000 Subject: c[:]() References: <1180504190.055427.173610@h2g2000hsg.googlegroups.com> <1180554872.3356.30.camel@dot.uniqsys.com> <465DF3DE.40404@cc.umanitoba.ca> <1180566831.239580.199300@m36g2000hse.googlegroups.com> <005401c7a31a$136f7fe0$240110ac@Muse> <135tobve86qj808@corp.supernews.com> <135tru124pie2b3@corp.supernews.com> <135tv1bjqgbmsc9@corp.supernews.com> <002801c7a3fb$56cc8030$240110ac@Muse> <9qudnbBRU9SHIcLbnZ2dnUVZ_rLinZ2d@speakeasy.net> Message-ID: <1360bimi84t7919@corp.supernews.com> On 2007-06-01, Warren Stringer wrote: > I like your use case. Am I correct in assuming that `y = x[:]; > y()` is NOT to be found in working code? No, you may not assume that. > If that is the case, then nothing gets broken. It would be > instructive to have a use case where enabling c[:]() would > break existing code. I've already explained such a use case. You still seem to be operating under the delusion that c[:] is somehow different than c. -- Grant Edwards grante Yow! I'm imagining a surfer at van filled with soy sauce! visi.com From apardon at forel.vub.ac.be Mon Jun 11 06:34:58 2007 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 11 Jun 2007 10:34:58 GMT Subject: Python's "only one way to do it" philosophy isn't good? References: <1181368143.874341.273140@r19g2000prf.googlegroups.com> Message-ID: On 2007-06-09, Terry Reedy wrote: > > "WaterWalk" wrote in message > news:1181368143.874341.273140 at r19g2000prf.googlegroups.com... >| I've just read an article "Building Robust System" by Gerald Jay >| Sussman. The article is here: >| > http://swiss.csail.mit.edu/classes/symbolic/spring07/readings/robust-systems.pdf >| >| In it there is a footprint which says: >| "Indeed, one often hears arguments against building exibility into an >| engineered sys- >| tem. For example, in the philosophy of the computer language Python it >| is claimed: > > For him to imply that Python is anti-flexibility is wrong. Very wrong.. > He should look in a mirror. See below. My impression is that python supporters often enough show some anti-flexibility attitude. >| \There should be one|and preferably only one|obvious way to do >| it."[25] Science does >| not usually proceed this way: In classical mechanics, for example, one >| can construct equa- >| tions of motion using Newtonian vectoral mechanics, or using a >| Lagrangian or Hamiltonian >| variational formulation.[30] In the cases where all three approaches >| are applicable they are >| equivalent, but each has its advantages in particular contexts." > > And in those contexts, one would hope that the method with advantages is > somehow the obvious way to do it. Otherwise beginners might become like > Buriden's ass. > > So I dispute that science is as different as he claims. And I do not see > any real value in the statement in that I do not see it saying anything > useful to the reader, at least not in this snippet. Yes science is different. The difference is the following. Should science only know the Newtonian vectoral mechanics and someone would come up with the Lagrangian approach, nobody would protest against this new approach by remarking that there should only be one obvious approach, implying that by introducing the second approach you give the people a choice, which they will have to think about so their decision what to use is no longer obvious, which it is if there is only one option. Yet these kind of remarks are made often enough when someone suggest a change to python. -- Antoon Pardon From larry.bates at websafe.com Thu Jun 21 11:36:16 2007 From: larry.bates at websafe.com (Larry Bates) Date: Thu, 21 Jun 2007 10:36:16 -0500 Subject: Reading multiline values using ConfigParser In-Reply-To: <1182394281.778904.315430@z28g2000prd.googlegroups.com> References: <1182358231.269388.250510@m36g2000hse.googlegroups.com> <1182394281.778904.315430@z28g2000prd.googlegroups.com> Message-ID: <467A9AF0.30507@websafe.com> Phoe6 wrote: > On Jun 20, 10:35 pm, "John Krukoff" wrote: > >>> Is there anyway, I can include multi-line value in the configfile? I > >> Following the link to RFC 822 (http://www.faqs.org/rfcs/rfc822.html) >> indicates that you can spread values out over multiple lines as long as >> there is a space or tab character imeediately after the CRLF. > > Thanks for the response. It did work! > >>>> config = ConfigParser() >>>> config.read("Testcases.txt") > ['Testcases.txt'] >>>> output = config.get("Information", "Testcases") >>>> print output > > tct123 > tct124 > tct125 >>>> output > '\ntct123\ntct124\ntct125' > > However, as I am going to provide Testcases.txt to be "user editable", > I cannot assume or "ask users" to provide value testcases surronded by > spaces. I got to figure out a workaround here. > > Thanks, > Senthil > I do this a lot and implement it as: [Testcases] case_001=tct123 case_002=tct124 case_003=tct101 Then it is pretty easy to do something in my code like: section='Testcases' cases=[x for x in INI.options(section) if x.startswith('case_')] for case in cases: casefile=INI.get(section, case) # # Process each casefile here # -Larry From steve at REMOVE.THIS.cybersource.com.au Sat Jun 16 21:04:55 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sun, 17 Jun 2007 11:04:55 +1000 Subject: a_list.count(a_callable) ? References: <1181850818.567840.251090@x35g2000prf.googlegroups.com> <1181853479.914070.217270@i13g2000prf.googlegroups.com> <1181855184.511137.100870@z28g2000prd.googlegroups.com> <1181916937.648267.163070@z28g2000prd.googlegroups.com> <1181981527.960296.135820@i13g2000prf.googlegroups.com> <1182026221.039617.56320@n2g2000hse.googlegroups.com> Message-ID: On Sat, 16 Jun 2007 20:37:01 +0000, Dustan wrote: > On Jun 16, 12:04 pm, Wildemar Wildenburger > wrote: >> class SmartCountingList(list): >> def count(self, item, func=lambda x: x): >> return len([item for item in self if func(item) is True]) > > A less bug-prone and (I would think) speedier example, although still > untested: > > class SmartCountingList(list): > def count(self, item, func=lambda x: x): > return sum(1 for i in self if func(item)==item) > > Then, you would call it as follows: > a_list.count(True, a_function) Did you intend for the method to count the number of items where func(item) is item instead of true? Personally, I don't see any advantage to making this a subclass. I think a bare function would be far, far more sensible, since you could then apply it to any sequence or iterable. Here's a version that should work with any iterable. If the iterable is a short enough sequence, it will use filter to build an intermediate list. If it is too long, or if it can't predict how long the intermediate list will be, it falls back to code that doesn't build an intermediate list. (The cut-off length I have used is a wild guess. Somebody who cares more than me can time the various strategies tactics and work out the "best" length to switch from one strategy to another. Don't forget to try it in different versions of Python.) def count_items(iterable, func=None, _cutoff=100003): """Count the number of items of iterable where func(item) is a true value. Equivalent to len(filter(func, seq)). If func is None or not given, counts the number of true items. Will not work for iterators that do not terminate. """ try: # Counting items in pure Python code is only # worthwhile if building a temporary list using # filter would take a long time. use_filter = len(iterable) < _cutoff except TypeError: # iterable has no len(), so play it safe and # avoid calling filter. use_filter = False if use_filter: # Take advantage of the fast filter built-in. return len(filter(func, iterable)) else: n = 0 if func is None: for item in iterable: if item: n += 1 else: for item in iterable: if func(item): n += 1 return n -- Steven. From warren at muse.com Fri Jun 1 13:22:29 2007 From: warren at muse.com (Warren Stringer) Date: Fri, 1 Jun 2007 10:22:29 -0700 Subject: c[:]() In-Reply-To: References: <1180504190.055427.173610@h2g2000hsg.googlegroups.com><1180554872.3356.30.camel@dot.uniqsys.com><465DF3DE.40404@cc.umanitoba.ca><1180566831.239580.199300@m36g2000hse.googlegroups.com><005401c7a31a$136f7fe0$240110ac@Muse><135tobve86qj808@corp.supernews.com><135tru124pie2b3@corp.supernews.com><135tv1bjqgbmsc9@corp.supernews.com> <9qudnbFRU9QHJsLbnZ2dnUVZ_rKvnZ2d@speakeasy.net> Message-ID: <005f01c7a471$6f4b8b30$240110ac@Muse> > And that your > insisting on ``c[:]()`` instead of just ``c()`` seems to indicate you want > a change that is quite surprising. It would mean that a slice of a list > returns an other type with the __call__ method implemented. I am not insisting on anything. I use ``c[:]()`` as shorthand way of saying "c() for c in d where d is a container" Having c() support containers seems obvious to me. It jibes with duck typing. Perhaps the title of this thread should have been: "Why don't containers quack?" A change is surprising only if it breaks something. I still haven't seen any code that breaks by making such a change. Seeing such code would teach a great deal. > Grok The Zen of Python (``import this`` at the interpreter prompt)? I think this is incredibly cool. > Write "pythonic" code? Probably not yet; I'm still learning - I have yet to perfect my silly walk. http://grampyshouse.net/cliches/images/sillywalk.jpg From thomas at jollans.com Sat Jun 16 07:17:52 2007 From: thomas at jollans.com (Thomas Jollans) Date: Sat, 16 Jun 2007 13:17:52 +0200 Subject: Installing manpage in setup.py In-Reply-To: References: Message-ID: Papalagi Pakeha wrote: > Hi all, > > how can I tell setup() in distutils' setup.py to install manual pages > of my program? I.e. prgclient.1 to /.../man/man1 and prgdaemon.8 to > /.../man/man8? The problem is that those /.../ directories may be > different on every system, for instance /usr/share/man on OpenSUSE and > /usr/man on Solaris. Is there a way to automatically put the manpages > to their proper directories? Looking at http://docs.python.org/dist/dist.html , it seams highly unlikely that such a syntax exists IMHO. I myself would just install it to share/man/man? since that is the path specified in the FHS [1]. setup.py being a python program, you could just as well check for the existence or /use/share/man and /usr/man. Thomas Jollans -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 260 bytes Desc: OpenPGP digital signature URL: From enleverlesX.XmcX at XmclaveauX.com Thu Jun 21 03:34:04 2007 From: enleverlesX.XmcX at XmclaveauX.com (Méta-MCI) Date: Thu, 21 Jun 2007 09:34:04 +0200 Subject: PEP 3107 and stronger typing (note: probably a newbie question) References: <1182369568.941307.316260@p77g2000hsh.googlegroups.com> Message-ID: <467a29f6$0$25930$ba4acef3@news.orange.fr> Hi! >Given that one can add/replace/remove methods and attributes >dynamically either on a per-class or per-instance basis, and even >dynamically change the class of an object, I fail to see how static >typechecking could be meaningfull. Et toc ! From showell30 at yahoo.com Sat Jun 2 12:00:18 2007 From: showell30 at yahoo.com (Steve Howell) Date: Sat, 2 Jun 2007 09:00:18 -0700 (PDT) Subject: file reading by record separator (not line by line) In-Reply-To: <1180790653.751231.223250@p47g2000hsd.googlegroups.com> Message-ID: <235736.19304.qm@web33501.mail.mud.yahoo.com> --- George Sakkis wrote: > > It seems > > like it would be fairly straightforward to do a > quick > > prototype implementation of this. I'm off to work > > soon, so I can't do it today, but maybe Sunday. > > I'm afraid I beat you to it :) > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/521877 Well done. Can I suggest a minor optimization? Instead of this... def get_predicate(arg): return arg if callable(arg) else ( arg.__eq__ if hasattr(arg,'__eq__') else lambda item: item == arg) ...would this be faster?: if not callable(start): start = lambda arg: (arg.__eq__ if hasattr(... # then start iterating Also, you haven't completely ruined my Sunday plans, because I think I could enhance the cookbook example by providing an alternative implementation that works on finite lists, to show the less sophisticated (but also less functional) approach to this problem. But maybe somebody will beat me to that as well... ____________________________________________________________________________________ We won't tell. Get more on shows you hate to love (and love to hate): Yahoo! TV's Guilty Pleasures list. http://tv.yahoo.com/collections/265 From wildemar at freakmail.de Mon Jun 4 05:15:26 2007 From: wildemar at freakmail.de (Wildemar Wildenburger) Date: Mon, 04 Jun 2007 11:15:26 +0200 Subject: subexpressions (OT: math) In-Reply-To: References: <4662675b$1_5@news.bluewin.ch> <1180890214.317409.85100@w5g2000hsg.googlegroups.com> <1180894045.538031.111610@g4g2000hsf.googlegroups.com> <1180895200.108582.313010@k79g2000hse.googlegroups.com> Message-ID: <4663D82E.8090006@freakmail.de> Erik Max Francis wrote: > Wildemar Wildenburger wrote: > > >> So in each term of the sum you have a derivative of f, which in the >> case of the sine function translates to sine and cosine functions at the >> point 0. It's not like you're rid of the function just by doing a >> polynomial expansion. The only way to *solve* this is to forbid x from >> having a dimension. At least *I* see no other way. Do you? >> > > That was precisely his point. The Maclaurin series (not MacLaurin) only > makes any sense if the independent variable is dimensionless. And thus, > by implication, so it is also the case for the original function. > > No that was not his point. Maybe he meant it, but he said something profoundly different. To quote: Stebanoid at gmail.com wrote: > if we expand sine in taylor series sin(x) = x - (x3)/6 + (x5)/120 etc. > you can see that sin can be dimensionless only if x is dimensionless too. This argumentation gives x (and sin(x)) the option of carrying a unit. That however is *not* the case. This option does not exist. Until someone proves the opposite, of course. Geez, I love stuff like that. Way better than doing actual work. :D /W (PS: THX for the MacLaurin<>Maclaurin note. I can't help that appearantly; I also write 'LaGrange' all the time.) From Squzer at gmail.com Tue Jun 26 02:08:59 2007 From: Squzer at gmail.com (Squzer) Date: Tue, 26 Jun 2007 06:08:59 -0000 Subject: Mirror Urls Message-ID: <1182838139.724898.120610@j4g2000prf.googlegroups.com> I am involving in the development of a crawler. i need my script to detect the mirror urls of the page. so that i can ignor the urls. Please tell me any idea to detect...... From mauriceling at acm.org Tue Jun 26 20:21:23 2007 From: mauriceling at acm.org (Maurice LING) Date: Wed, 27 Jun 2007 00:21:23 GMT Subject: ANN: YahooQuote 0.1.0 In-Reply-To: <467f9e21$1@news.orcon.net.nz> References: <467f9e21$1@news.orcon.net.nz> Message-ID: <4681ad7f$1@news.unimelb.edu.au> Hi David, I can't download from your link http://www.freenet.org.nz/python/yahooquote/YahooQuote-0.1.tar.gz Cheers maurice DavidM wrote: > Hi, > > After a 3-year break from working with it, I've just released version 0.1.0 > (the first formally packaged release) of YahooQuote. As the name implies, > it's a stockmarket prices fetcher. > > Features: > - easily fetch stock price quotes and histories > - fetch bulk histories across one or more of the major stockmarket > indexes > - fast efficient automatic caching via a MetaKit database > - pleasant object-oriented interface > - thorough epydoc-generated API doco > - simple examples > > This supersedes the unpackaged YahooQuote module of 2004, and brings > YahooQuote up to date with the present Yahoo Finance web interface. > > http://www.freenet.org.nz/python/yahooquote > > License: LGPL > > Enjoy > > Cheers > David From arorap at gmail.com Tue Jun 12 17:03:38 2007 From: arorap at gmail.com (arorap) Date: Tue, 12 Jun 2007 14:03:38 -0700 Subject: How does mod_python know where's Python installed ? Message-ID: <1181682218.110112.251420@i13g2000prf.googlegroups.com> Hi, I recently setup mod_python successfully and things work smooth. However, I do not remember telling mod_python where to find Python installation. There's not environment variable which gives that information. As such how does mod_python know where to find Python ? When I print sys.path in my scripts it contains my python installation folder. I'm wondering how does Apache/mod_python get this information ? I'm running Apache 2.2 on windows. -Puneet. From NikitaTheSpider at gmail.com Thu Jun 7 11:02:53 2007 From: NikitaTheSpider at gmail.com (Nikita the Spider) Date: Thu, 07 Jun 2007 11:02:53 -0400 Subject: open function fail after running a day References: <1181226795.455934.177550@n15g2000prd.googlegroups.com> Message-ID: In article <1181226795.455934.177550 at n15g2000prd.googlegroups.com>, alexteo21 wrote: > The script is working fine on the day of execution. > It is able to process the data files very hour. However, the > processing fail one day later i.e. the date increment by 1. > > Traceback (most recent call last): > File "./alexCopy.py", line 459, in processRequestModule > sanityTestSteps(reqId,model) > File "./alexCopy.py", line 699, in sanityTestSteps > t = open(filename, 'rb') > IOError: [Errno 24] Too many open files: > > I have explicitly closed the file. Is there something else I need to > do? Sounds like the .close() isn't getting executed as you think. Try using the logging module to log a line immediately before each open and close so that you can ensure you're really closing all the files. Alternatively, some other bit of code my be the guilty party. A utility like fstat can show you who has files open. Good luck -- Philip http://NikitaTheSpider.com/ Whole-site HTML validation, link checking and more From jadestar at idiom.com Tue Jun 19 20:18:41 2007 From: jadestar at idiom.com (James T. Dennis) Date: Wed, 20 Jun 2007 00:18:41 -0000 Subject: Re printing on same line. References: <1181920861.071568.4860@w5g2000hsg.googlegroups.com> Message-ID: <1182298720.972552@smirk> Robert Bauck Hamar wrote: > Jerry Hill wrote: >> On 6/15/07, HMS Surprise wrote: >>> I want to print a count down timer on the same line. I tried >>> print '\r', timeLeft, >>> which just appends to the same line. >> Sounds to me like whatever you're printing to doesn't do what you >> expect when it encounters a carriage return (\r). Is your program >> running in a terminal? Both the windows cmd.exe shell and bash under >> linux seem to do the right thing when encountering a '\r'. > Actually, bash has nothing to do with how the terminal handles \r. The job > of the shell (bash, ksh, csh, sh ...) is to execute your script when you > type its name. > Outputting a \r might or might not move the cursor to the beginning of the > line. It's completely system specific, and even on the same OS, it depends > on the capabilities of the actual terminal the programs run on, and on some > terminal emulators it might depend on configuration settings. > If you need to explore the capabilities of the terminal, curses will be a > good place to start. > -- > rbh Sometimes you don't want to full curses mode switch and other baggage. You can use the 'tput' utility to get the terminal escape sequences for various cursor movements for your terminal. Read the tput man page for some information, and the terminfo(5) man page for more. In particular you can do things like (from a shell prompt): tput sc; tput cup 0 30;echo Front and Center; tput rc ... which saves the current cursor location (sc), executes a cursor position to the first line, 30th column (cup 0 30), writes some text there, and then restores the cursor location (rc). The trick, in Python, is that you can read these sequences into your program via popen() calls and then print them wherever you want to use them. You can even set colors (foreground and background), and text attributes (dim, bright, blinking, underline) and perform various other curses like applications without actually doing the curses mode changes if you're really a bit masochistic. However, for the original poster's purposes the easiest option would probably be to print something like: print chr(0x08) * 80, "new line stuff" + " " * 66 (Print lots of backspaces followed by whatever information you wanted to over-write the line with and padding with enough spaces to clear any other stuff you wanted to over-write). Yes, this is sloppy. Yes, it might not work on some terminals or under some terminal settings. However, it should work under most circumstances on most terminals --- including some which wouldn't support the curses module. You can improve it somewhat by keeping track of how many characters you've printed to the current (last) line and dynamically printing the precise number of backspaces and padding spaces that are needed. -- Jim Dennis, Starshine: Signed, Sealed, Delivered From moegoldberg at gmail.com Thu Jun 21 15:18:24 2007 From: moegoldberg at gmail.com (moegoldberg at gmail.com) Date: Thu, 21 Jun 2007 19:18:24 -0000 Subject: Changing the names of python keywords and functions In-Reply-To: <1182452862.872909.206780@u2g2000hsc.googlegroups.com> References: <1182452862.872909.206780@u2g2000hsc.googlegroups.com> Message-ID: <1182453504.084126.211450@q69g2000hsb.googlegroups.com> I'm not quite clear on what you are asking, but you can use the __import__() function to import modules by name. On Jun 21, 3:07 pm, vedrandeko... at v-programs.com wrote: > Hello, > > I am trying to make a program for 3D modelling with "programming".And > I want make my own program commands, > > for example when user type code in my program: > > "<> OS"- (THIS IS MY IMAGINARY EXAMPLE OF KEYWORD), > > my program must write this code in some user file, but my > > program must read this command like: "import os".How > > can I do something like that?? > > Please, HELP ME somebody!!! From jorgen.maillist at gmail.com Wed Jun 6 07:40:36 2007 From: jorgen.maillist at gmail.com (Jorgen Bodde) Date: Wed, 6 Jun 2007 13:40:36 +0200 Subject: function in a function accessing vars In-Reply-To: <5cnepqF2ud2rmU1@mid.uni-berlin.de> References: <5cnepqF2ud2rmU1@mid.uni-berlin.de> Message-ID: <11e49df10706060440o1ba30b77l93e2d3c9e3c393b9@mail.gmail.com> Hi Diez, Thanks, I thought it worked similar to C++ where a higher compound could access a lower section. But as it is not straight forward, I think it is better to embed the functionality inside a class, and make it a member variable .. now why didn't I think of that ;-) Thanks, - Jorgen On 6/6/07, Diez B. Roggisch wrote: > Jorgen Bodde wrote: > > > Hi all, > > > > I wanted to solve a small problem, and I have a function that is > > typically meant only as a function belonging inside another function. > >>From the inner function I want to access a variable from the outer > > function like; > > > > def A(): > > some_var = 1 > > def B(): > > some_var += 1 > > > > B() > > > > > > But this does not work, the function B does not recognize the > > some_var. In my mind I thought the scope would propagate to the new > > function and the vars would still be accessible. > > > > How can I go about this? > > The problem here is the way python determines which variables are local to a > function - by inspecting left sides. > > I'm not sure if there are any fancy inspection/stackframe/cells-hacks to > accomplish what you want. But the easiest solution seems to be a > (admittedly not too beautiful) > > def A(): > some_var = [1] > def B(v): > v[0] += 1 > > B(some_var) > > > Or you should consider making A a callable class and thus an instance, and > some_var an instance variable. Always remember: "a closure is a poor > persons object, and an object is a poor mans closure" > > Diez > -- > http://mail.python.org/mailman/listinfo/python-list > From evan at yelp.com Tue Jun 19 17:56:59 2007 From: evan at yelp.com (Evan Klitzke) Date: Tue, 19 Jun 2007 14:56:59 -0700 Subject: stftime %z time conversion character Message-ID: Although it is not present in ANSI C, the GNU version of stftime supports the conversion character %z, which is a time offset from GMT. The four digit time offset is required in RFC 2822 dates/times, and is used by a number of other programs as well. I need to convert times that use this convention to python time representations, and because Python does not support the %z time conversion character I cannot simply use the time.strptime function. What solutions have people used for this? I'm currently thinking of creating a dict that maps four digit time offsets to the time zone name and then use the %Z token on that. Is there another (or better) way? -- Evan Klitzke From ivanlocke at mail.com Fri Jun 1 19:15:34 2007 From: ivanlocke at mail.com (ilocke) Date: Fri, 01 Jun 2007 16:15:34 -0700 Subject: Get ClassID of different versions of program with same ProgID In-Reply-To: <1180739455.034381.166190@i13g2000prf.googlegroups.com> References: <1180735905.211414.62360@k79g2000hse.googlegroups.com> <1180739455.034381.166190@i13g2000prf.googlegroups.com> Message-ID: <1180739734.111071.188270@q75g2000hsh.googlegroups.com> AutoCAD.Application.16 opens 2004, but I tried numbers before and after and nothing opend up 14. I figured out a way to find it though. I was using pythoncom.GetClassFile on the AutoCAD executable instead of a drawing file. I used it with .dwg twice while associated to each of the versions, and it gave me the ClassID of the associated version. Now just to get down to the real work and make it do something useful. Ivan From miki.tebeka at gmail.com Tue Jun 12 13:30:13 2007 From: miki.tebeka at gmail.com (Miki) Date: Tue, 12 Jun 2007 17:30:13 -0000 Subject: Forgetting an import In-Reply-To: <1181666164.640868.225130@i38g2000prf.googlegroups.com> References: <1181666164.640868.225130@i38g2000prf.googlegroups.com> Message-ID: <1181669413.643796.304850@x35g2000prf.googlegroups.com> Hello, > I imported a set of functions from a file I wrote to interpreter > shell: > > from myFile import * > > Now if I change functions in this file how can I make python forget it > so I can force a fresh import? "import *" is evil for many reasons, this is one of them :) >>> import my_module >>> my_module.add(1, 1) 4 [Hack] >>> reload(my_module) >>> my_module.add(1, 1) 2 HTH, -- Miki http://pythonwise.blogspot.com From tjreedy at udel.edu Tue Jun 12 03:53:01 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 12 Jun 2007 03:53:01 -0400 Subject: A gotcha: Python pain point? References: <1181604836.292323.154510@z28g2000prd.googlegroups.com> Message-ID: "Beorn" wrote in message news:1181604836.292323.154510 at z28g2000prd.googlegroups.com... | Consider this example: | | >>> def funcs(x): | ... for i in range(5): | ... def g(): return x + i | ... yield g | | I would expect the value of x used in g to be that at the function | declaration time, as if you've pass g a (x=x) argument, Since x is constant during the funcs call, does not matter. Perhaps you meant i, which does vary? If so, put i=i in the header -- or perhaps ii=i to give two different names to two things which are made to have the same value. In any case, the simple rule is that default argument expressions in the *header* are evaluated at definition time while the *body* (past the doc string, if any) is executed after a call. Some people expect defaults to be executed every call; others expect part of the body to be executed once. Both get in trouble. For nested functions, outer call time is inner definition time and this can confuses. Defining (but delaying the call of) multiple identical inner functions, as you do in the first example below, also confuses. | especially | after reading this post: http://lua-users.org/wiki/LuaScopingDiscussion Lua is not Python. | But: | | >>> [ fun() for fun in list(funcs(1)) ] | [5, 5, 5, 5, 5] | | Whereas: | | >>> [ fun() for fun in funcs(1) ] | [1, 2, 3, 4, 5] As Calderone explained, the simple rule works as long as one keeps track of what is called when. Terry Jan Reedy From sjmachin at lexicon.net Sat Jun 9 21:33:40 2007 From: sjmachin at lexicon.net (John Machin) Date: Sat, 09 Jun 2007 18:33:40 -0700 Subject: pyexe "format" In-Reply-To: <1181438724.935702.151780@z28g2000prd.googlegroups.com> References: <1181438724.935702.151780@z28g2000prd.googlegroups.com> Message-ID: <1181439220.678204.160520@z28g2000prd.googlegroups.com> On Jun 10, 11:25 am, John Machin wrote: > On Jun 10, 10:38 am, hg wrote: > > > hg wrote: > > > Hi, > > > > Is there a clean way to figure out that a .exe was actually generated by > > > pyexe ? > > > > hg > > > I should gave writtent "definite" instead of "clean" > > > hg > > Reminds me of the story about a teacher trying to correct a student > who was using rather dialectal English: > You have went and putten "putten" when you should of putten "put"! > :-) > > You should of looken at this: > > http://www.py2exe.org/index.cgi/WhereAmI > > HTH, > John I presumed that you were really asking: "How can Python code tell whether it is being run in a py2exe-generated exe, or by the Python interpreter?". Alternatively, "How can a human inspect an exe and determine whether it was generated by py2exe?": (1) I don't know (2) Why do you care? Cheers, John From blmblm at myrealbox.com Mon Jun 25 17:20:44 2007 From: blmblm at myrealbox.com (blmblm at myrealbox.com) Date: 25 Jun 2007 21:20:44 GMT Subject: The Modernization of Emacs: terminology buffer and keybinding References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182547318.325617.16370@o11g2000prd.googlegroups.com> <1182657564.912472.55570@g4g2000hsf.googlegroups.com> Message-ID: <5eaptcF378d21U3@mid.individual.net> In article <1182657564.912472.55570 at g4g2000hsf.googlegroups.com>, Twisted wrote: > On Jun 23, 10:36 am, Martin Gregorie > wrote: [ snip ] > * The operating system where you can do powerful stuff with a command > line and a script or two, but can also get by without either. (Windows > fails the former. Linux fails the latter.) About the latter -- it's hard for me to be sure, since for many things something with a GUI is not my first choice of tool, but my impression is that on "user-friendly" Linux distributions, pretty much everything, including sysadmin stuff, can be done by pointing and clicking, starting with the menus displayed on the default desktop. Perhaps someone with more/different experience can comment on how many things still require scripting or a command line. [ snip ] -- B. L. Massingill ObDisclaimer: I don't speak for my employers; they return the favor. From bignose+hates-spam at benfinney.id.au Thu Jun 21 20:59:56 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 22 Jun 2007 10:59:56 +1000 Subject: Setuptools, build and install dependencies (was: eggs considered harmful) References: Message-ID: <87645gx0qb.fsf@benfinney.id.au> Harry George writes: > Historically, python packages played well in this context. Install > was a simple download, untar, setup.py build/install. > > Eggs and with other setuptools-inspired install processes break this > paradigm. The tarballs are incomplete in the first place. The builds > sometimes wander off to the internet looking for more downloads. The > installs sometimes wander off to the internet looking for > compatibility conditions. (Or rather they try to do so and fail > because I don't let themn through the firewall.) If you provide the build and install script with all the dependencies already present (in the current directory), my experience is that setuptools does not do any network actions. -- \ "Self-respect: The secure feeling that no one, as yet, is | `\ suspicious." -- Henry L. Mencken | _o__) | Ben Finney From oscartheduck at gmail.com Fri Jun 22 16:18:39 2007 From: oscartheduck at gmail.com (oscartheduck) Date: Fri, 22 Jun 2007 20:18:39 -0000 Subject: regular expression concatenation with strings Message-ID: <1182543519.337279.25800@z28g2000prd.googlegroups.com> Hi folks, I have a little script that sits in a directory of images and, when ran, creates thumbnails of the images. It works fine if I call the function inside the program with something like "thumbnailer("jpg), but I want to use a regular expression instead of a plain string so that I can match jpeg, jpg, JPEG etc. Here's the script: --- #!/usr/bin/env python from PIL import Image import glob, os, re size = 128, 128 # takes an extension (e.g. jpg, png, gif, tiff) as argument def thumbnailer(extension): #glob the directory the script is in for files of the type foo.extension for picture in glob.glob("*." + extension): file, ext = os.path.splitext(picture) im = Image.open (picture) im.thumbnail(size, Image.ANTIALIAS) im.save(file + ".thumbnail." + extension) jpg = re.compile("jpg|jpeg", re.IGNORECASE) thumbnailer(jpg) --- And here's the error: --- Traceback (most recent call last): File "./thumbnail.py", line 19, in ? thumbnailer(jpg) File "./thumbnail.py", line 11, in thumbnailer for picture in glob.glob("*." + extension): TypeError: cannot concatenate 'str' and '_sre.SRE_Pattern' objects --- It looks to me like the conversion to a regex object instead of a plain string is screwing up the file glob + extension concatenation. Is there a simple way to accomplish what I'm trying to do here and get rid of that error? Thanks! From elfine at gwu.edu Mon Jun 11 04:39:50 2007 From: elfine at gwu.edu (Elfine Peterson Tjio) Date: Mon, 11 Jun 2007 04:39:50 -0400 Subject: Python Help!!! Message-ID: I'm trying to make a program that reads Fasta file and print it out. I used the SeqIO module and the results is: 'ATGGTCAT....SingleAlphabet()' For this purpose, should I use SeqIO or Fasta? for example: from Bio import SeqIO or from Bio import Fasta I want it to print every letter. Can anyone point me to the right direction. The newest biopython tutorial or book recommendation will be appreciated, too. From bignose+hates-spam at benfinney.id.au Wed Jun 13 19:28:36 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 14 Jun 2007 09:28:36 +1000 Subject: Bytes/File Size Format Function References: <1181706472.008233.80050@a26g2000pre.googlegroups.com> <87r6oguru2.fsf@benfinney.id.au> Message-ID: <877iq7v3h7.fsf@benfinney.id.au> Avell Diroll writes: > I have to disagree: 'mb' should stand for "milli-bit" :) Yes, you're right. My "metre-bit" was wrong. -- \ "Whenever you read a good book, it's like the author is right | `\ there, in the room talking to you, which is why I don't like to | _o__) read good books." -- Jack Handey | Ben Finney From james.p.turk at gmail.com Wed Jun 13 21:43:04 2007 From: james.p.turk at gmail.com (James Turk) Date: Thu, 14 Jun 2007 01:43:04 -0000 Subject: one-time initialization of class members In-Reply-To: References: <1181772494.803499.266690@o11g2000prd.googlegroups.com> <1181778902.547599.147960@q19g2000prn.googlegroups.com> Message-ID: <1181785384.380731.224550@n15g2000prd.googlegroups.com> On Jun 13, 9:03 pm, Steven D'Aprano wrote: > On Wed, 13 Jun 2007 23:55:02 +0000, James Turk wrote: > > On Jun 13, 6:54 pm, Steven Bethard wrote: > >> James Turk wrote: > >> > Hi, > > >> > I have a situation where I have some class members that should only be > >> > done once. Essentially my problem looks like this: > > >> > class Base(object): > >> > dataset = None > > >> > def __init__(self, param): > >> > if type(self).dataset is None: > >> > # code to load dataset based on param, expensive > > >> > class ChildClass1(Base): > >> > def __init__(self): > >> > Base.__init__(self, data_params) > > >> > class AnotherChildClass(Base): > >> > def __init__(self): > >> > Base.__init__(self, other_data_params) > > >> > This seems to work, initialization is only done at the first creation > >> > of either class. I was just wondering if this is the 'pythonic' way > >> > to do this as my solution does feel a bit hackish. > > >> What should happen with code like:: > > >> ChildClass1('foo') > >> ChildClass1('bar') > > >> The 'param' is different, but 'dataset' should only get set the first time? > > >> STeVe > > > ChildClass doesn't take the parameter in it's constructor, it supplies > > it for the BaseClass. Every ChildClass of the same type should use > > the same dataset. > > Then each type of ChildClass should be a sub-class, and provide it's own > dataset: > > class BaseClass: > dataset = None > # blah blah blah... > > class ChildClass1(BaseClass): > dataset = SomethingUseful > > class ChildClass2(BaseClass): > dataset = SomethingElse > > -- > Steven. It actually occured to me that I could use a @classmethod to do the loading and take that out of the BaseClass constructor. What I have makes more sense and eliminates the unecessary constructors. ie. class BaseClass: @classmethod def loadData(params): #expensive load here class ChildClass1(BaseClass): dataset = BaseClass.loadData(params) This is pretty much along the lines of what you suggested, thank you for the hint in the right direction. I realized that this still doesn't meet my needs exactly as I only want the expensive dataset to be loaded if/when a class is actually used (there are potentially many of these and only a few will be used). I believe I have two options: 1) put each ChildClass in a separate file 2) in each ChildClass constructor put a check if the dataset has been loaded yet, so that the first time an instance is created it can call the BaseClass.loadData for now I have chosen the second option, which is to change the child classes to resemble class ChildClass(BaseClass): dataset = None def __init__(self): if BaseClass.dataset is None: self(type).dataset = BaseClass.loadData(params) I am still doing the self(type) access, but I like it more now that I've taken it out of the BaseClass constructor. From half.italian at gmail.com Wed Jun 13 03:53:18 2007 From: half.italian at gmail.com (half.italian at gmail.com) Date: Wed, 13 Jun 2007 00:53:18 -0700 Subject: Bytes/File Size Format Function In-Reply-To: <1181720934.824480.175540@n15g2000prd.googlegroups.com> References: <1181706472.008233.80050@a26g2000pre.googlegroups.com> <1181720934.824480.175540@n15g2000prd.googlegroups.com> Message-ID: <1181721198.956829.298920@a26g2000pre.googlegroups.com> On Jun 13, 12:48 am, half.ital... at gmail.com wrote: > On Jun 12, 8:47 pm, samuraisam wrote: > > > > > Quick file size formatting for all those seekers out there... > > > import math > > > def filesizeformat(bytes, precision=2): > > """Returns a humanized string for a given amount of bytes""" > > bytes = int(bytes) > > if bytes is 0: > > return '0bytes' > > log = math.floor(math.log(bytes, 1024)) > > return "%.*f%s" % ( > > precision, > > bytes / math.pow(1024, log), > > ['bytes', 'kb', 'mb', 'gb', 'tb','pb', 'eb', 'zb', 'yb'] > > [int(log)] > > ) > > Wait a sec...what if you send it a large amount of bytes? Say... > bigger than 2147483647. You'll get an OverflowError. I thought you > had my solution... > > ~Sean From a.schmolck at gmail.com Sat Jun 9 17:42:17 2007 From: a.schmolck at gmail.com (Alexander Schmolck) Date: Sat, 09 Jun 2007 22:42:17 +0100 Subject: Python's "only one way to do it" philosophy isn't good? References: <1181368143.874341.273140@r19g2000prf.googlegroups.com> Message-ID: Josiah Carlson writes: > James Stroud wrote: >> Terry Reedy wrote: >>> In Python, you have a choice of recursion (normal or tail) >> >> Please explain this. I remember reading on this newsgroup that an advantage >> of ruby (wrt python) is that ruby has tail recursion, implying that python >> does not. Does python have fully optimized tail recursion as described in >> the tail recursion Wikipedia entry? Under what circumstances can one count >> on the python interpreter recognizing the possibility for optimized tail >> recursion? > > Note that Terry said that you could do normal or tail recursion, he didn't > claim that either were optimized. Well yeah, but without the implication how do the two words "or tail" add to the information content of the sentence? > As for why tail calls are not optimized out, it was decided that being able > to have the stack traces (with variable information, etc.) was more useful > than offering tail call optimization I don't buy this. What's more important, making code not fail arbitrarily (and thus making approaches to certain problems feasible that otherwise wouldn't be) or making it a be a bit easier to debug code that will fail arbitrarily? Why not only do tail-call optimization in .pyo files and get the best of both worlds? > (do what I say). Where did you say run out of memory and fail? More importantly how do you say "don't run out of memory and fail"? 'as From carsten at uniqsys.com Fri Jun 15 14:51:27 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Fri, 15 Jun 2007 14:51:27 -0400 Subject: a_list.count(a_callable) ? In-Reply-To: <1181932795.3387.33.camel@dot.uniqsys.com> References: <1181850818.567840.251090@x35g2000prf.googlegroups.com> <1181853479.914070.217270@i13g2000prf.googlegroups.com> <1181855184.511137.100870@z28g2000prd.googlegroups.com> <1181916937.648267.163070@z28g2000prd.googlegroups.com> <1181930111.491700.133290@x35g2000prf.googlegroups.com> <1181932795.3387.33.camel@dot.uniqsys.com> Message-ID: <1181933487.3387.39.camel@dot.uniqsys.com> On Fri, 2007-06-15 at 14:39 -0400, Carsten Haese wrote: > class WhereTrue(object): > def __init__(self, func): > self.func = func > def __eq__(self, other): > return self.func(other) > > list1.count(WhereTrue(callable1)) > list2.count(WhereTrue(callable2)) P.S: Note, however, that this will only work if the list elements don't define __eq__ methods themselves. If they do, their __eq__ methods get called instead of WhereTrue's __eq__ method, leading to incorrect results. -- Carsten Haese http://informixdb.sourceforge.net From gagsl-py2 at yahoo.com.ar Fri Jun 22 00:55:37 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 22 Jun 2007 01:55:37 -0300 Subject: why __repr__ affected after __getattr__ overloaded? References: <1182483043.850101.110890@i13g2000prf.googlegroups.com> Message-ID: En Fri, 22 Jun 2007 00:30:43 -0300, Roc Zhou escribi?: > Now I have to design a class that overload __getattr__, but after > that, I found the __repr__ have been affected. This is a simple > example model: You are creating many attributes with value "inexistent", even special methods. Put a print statement and see what happens: > #!/usr/bin/env python > > class test: > def __init__(self): > self.x = 1 > def __getattr__(self, attr_name): > try: > return self.__dict__[attr_name] > except KeyError: print "Now creating:",attr_name > self.__dict__[attr_name] = 'inexistent' > return self.__dict__[attr_name] -- Gabriel Genellina From Afro.Systems at gmail.com Sun Jun 17 04:07:19 2007 From: Afro.Systems at gmail.com (Tzury) Date: Sun, 17 Jun 2007 08:07:19 -0000 Subject: Comparing UTF-8 into USC-2 and vice versa (newbie :-) ) In-Reply-To: <4674E74E.1080406@v.loewis.de> References: <1182064058.292960.319970@p77g2000hsh.googlegroups.com> <4674E74E.1080406@v.loewis.de> Message-ID: <1182067639.498945.25400@n60g2000hse.googlegroups.com> On Jun 17, 10:48 am, "Martin v. L?wis" wrote: > > I recently rewrote a .net application in python. > > The application is basically gets streams via TCP socket and handle > > operations against an existing database. > > The Database is SQLite3 (Encoded as UTF-8). > > The Networks streams are encoded as UCS-2. > > > Since in UCS-2, 'A' = '0041' and when I check with the built-in > > functions I get for unicode("A", "utf-8") = u'A' = u'\u0041'. I > > wonder what is the difference, and how can I safely encode/decode > > UCS-2 streams and match them with the UTF-8 representation > > In unicode("A", "utf-8"), the "utf-8" parameter does *not* mean > that the output is in UTF-8, but the *input*. > So "A" = '41' != '0041'. In UCS-2, the A consumes two bytes; in > UTF-8, it consumes only one byte. > > For different letters, that's different: For example, for u'\xf6', > the UCS-2 representation (big-endian) is '00F6', for UTF-8, it is > 'C3B6'. For u'\u20AC', the UCS-2 is '20AC', the UTF-8 is 'E282AC' > (i.e. three bytes). > > You should use Unicode objects in your program always, and encode > to or from UCS-2 or UTF-8 only when interfacing with the > network/database. > > HTH, > Martin Thanks Martin for this guideline From gregpinero at gmail.com Thu Jun 7 16:55:28 2007 From: gregpinero at gmail.com (gregpinero at gmail.com) Date: Thu, 07 Jun 2007 20:55:28 -0000 Subject: How does os.walk work? Message-ID: <1181249728.519175.305290@q66g2000hsg.googlegroups.com> In the example from help(os.walk) it lists this: 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 What I'm wondering is how does the "dirs.remove('CVS')" line prevent os.walk from visiting that directory? how does the walk function know what you do to the dirs variable? I tried looking at the code in os.py but it wasn't clear to me there either. Thanks, Greg From martin at v.loewis.de Mon Jun 25 17:33:44 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Mon, 25 Jun 2007 23:33:44 +0200 Subject: Internals and complexity of types, containers and algorithms In-Reply-To: References: Message-ID: <468034b8$0$22922$9b622d9e@news.freenet.de> > - Is there a brief description (not source) how the types tuple, > string, list and dict are represented internally. Is a list behind > the scenes just a double linked list or an array or a mixture of > these things? Sure, see below: - tuples are represented as arrays, with a single block for the entire objects (object header, tuple size, and data) - list are represented as arrays, with two memory blocks: one for object header and sizes, and the other one for the "guts", i.e. the actual data. The list uses over-allocation, to avoid resizing on each addition. - strings are implemented as arrays, with a single block for the entire string. In addition to header, size, and data, it also contains a cached hash and a pointer to the interned version of the string (if any). - dicts are implemented as hash tables, with open addressing. > Is a dict a tree or a hash array and what is the > collision mechanism? It's a hash array. Not sure what you mean by "collision mechanism" - perhaps "open addressing" is the answer? In case you also want to know the probing: j(n+1) = 5*j(n) + 1 + perturb(n) perturb(n+1) = perturb(n) >> 5 > Is the string an array with some header info? Exactly so. > - What is the big-O complexity of the most common algorithms for > these types and containers? Is it O(n), O(n*log(n)) or O(n**2)? > I mean inserting, appending (front or back), finding something > and so on. O(1) for indexed access in lists, tuples, and strings, and for computing the length of any container. O(n) for finding in lists, tuples, and strings. O(1) for inserting and finding in dictionaries, assuming few collisions, except when rehashing occurs. Amortized O(1) for inserting into lists. O(n) for removing from lists. O(1) for inserting inot > - Is this information somewhere in the web? Most likely. > Why is it not written in the documentation? Because nobody has contributed such documentation. > - When I want to use a representation of a game board like chess > in C/C++ I use an array[64] or bigger of int or char for the pieces. > What data structure or type would be useful in Python when the > performance ist most important? Is it list or string or an array > from a library or what else? Depends on whether and how you want to modify the chessboard. If you do want to modify, use a list. Regards, Martin From chowroc.z at gmail.com Fri Jun 22 01:56:42 2007 From: chowroc.z at gmail.com (Roc Zhou) Date: Fri, 22 Jun 2007 05:56:42 -0000 Subject: why __repr__ affected after __getattr__ overloaded? In-Reply-To: <1182491330.343267.122010@q19g2000prn.googlegroups.com> References: <1182483043.850101.110890@i13g2000prf.googlegroups.com> <1182491330.343267.122010@q19g2000prn.googlegroups.com> Message-ID: <1182491802.112209.322440@e9g2000prf.googlegroups.com> return hex(id(self)) On 6 22 , 1 48 , Roc Zhou wrote: > I know what's wrong. Thank you. And I think > try: > return self.__dict__[attr_name] > is unnecessary, because python will do it itself for us. > > So now I have to overload __str__, but how can I make self.__str__ > print as builtin str(): at here, I want get the result like: > > ? > > On 6 22 , 12 55 , "Gabriel Genellina" > wrote: > > > En Fri, 22 Jun 2007 00:30:43 -0300, Roc Zhou > > escribi?: > > > > Now I have to design a class that overload __getattr__, but after > > > that, I found the __repr__ have been affected. This is a simple > > > example model: > > > You are creating many attributes with value "inexistent", even special > > methods. Put a print statement and see what happens: > > > > #!/usr/bin/env python > > > > class test: > > > def __init__(self): > > > self.x = 1 > > > def __getattr__(self, attr_name): > > > try: > > > return self.__dict__[attr_name] > > > except KeyError: > > > print "Now creating:",attr_name > > > > self.__dict__[attr_name] = 'inexistent' > > > return self.__dict__[attr_name] > > > -- > > Gabriel Genellina From len-l at telus.net Wed Jun 27 21:28:16 2007 From: len-l at telus.net (Lenard Lindstrom) Date: Thu, 28 Jun 2007 01:28:16 GMT Subject: Python's "only one way to do it" philosophy isn't good? In-Reply-To: References: <7x3b0nmkk6.fsf@ruckus.brouhaha.com> <7xejjzmk7u.fsf@ruckus.brouhaha.com> <7xy7i7xjl5.fsf@ruckus.brouhaha.com> <1182872972.417776.78650@o11g2000prd.googlegroups.com> <7xtzsuy7fe.fsf@ruckus.brouhaha.com> <1182955743.076746.114790@i38g2000prf.googlegroups.com> Message-ID: Douglas Alan wrote: > > Lispers have long since understood how to write mapping function to > iterator converters using stack groups or continuations, but Common > Lisp never mandated stack groups or continuations for conforming > implementations. Scheme, of course, has continuations, and there are > implementations of Common Lisp with stack groups. > Those stack groups http://common-lisp.net/project/bknr/static/lmman/fd-sg.xml remind me of Python greenlets http://cheeseshop.python.org/pypi/greenlet . --- Lenard Lindstrom From marcoberi at gmail.com Tue Jun 5 12:18:51 2007 From: marcoberi at gmail.com (marcoberi at gmail.com) Date: Tue, 05 Jun 2007 16:18:51 -0000 Subject: Tkinter, tkMessagebox and overrideredirect Message-ID: <1181060331.167762.19180@q69g2000hsb.googlegroups.com> Hi everybody. I have this code snippet that shows a window without a titlebar (using overrideredirect) and two buttons on it: one quits and the other one brings up a simple tkMessageBox. On Windows (any flavour) the tkMessagebox brings up over the underlying window. On Linux (apparently any flavour) the tkMessagebox brings up under the underlying window. You can drag the popup window near the main window to discover if it's over or under it. Obviously I would like to show a popup that is over the main window! Before asking I tried, I read, I googled, I pulled my hair off, but no avail... Any hints? Thanks a lot for your time. Ciao. Marco. import tkMessageBox from Tkinter import * class App(): def __init__(self): self.root = Tk() self.root.overrideredirect(1) self.frame = Frame(self.root, width=320, height=200, borderwidth=5, relief=RAISED) self.frame.pack_propagate(False) self.frame.pack() self.bQuit = Button(self.frame, text="Quit", command=self.root.quit) self.bQuit.pack(pady=20) self.bHello = Button(self.frame, text="Hello", command=self.hello) self.bHello.pack(pady=20) def hello(self): tkMessageBox.showinfo("Popup", "Hello!") app = App() app.root.mainloop() From arkanes at gmail.com Fri Jun 8 08:59:06 2007 From: arkanes at gmail.com (Chris Mellon) Date: Fri, 8 Jun 2007 07:59:06 -0500 Subject: wxPython / Dabo demo shell ? In-Reply-To: <4646a$466901e6$83aef404$30670@news2.tudelft.nl> References: <4646a$466901e6$83aef404$30670@news2.tudelft.nl> Message-ID: <4866bea60706080559m55a80f50he95c910eb90f90ed@mail.gmail.com> On 6/8/07, stef wrote: > hello, > > I was impressed by the demo shell of wxPython, > and a few days ago (finally getting Dabo to work), > I saw Dabo uses the same demo shell. > > Is there any more information available about this shell, > because it seems a very nice / good way to show > (many) demos, in an organized way to newbies. > > thanks, > Stef mientki > -- The shell in the wxPython demo (but apparently not in the dabo demo, as per Ed's email) is from the wx.py package. It's quite trivial to add to your own applications, documentation is at http://www.wxpython.org/PyManual.html From stian at soiland.no Wed Jun 27 09:47:54 2007 From: stian at soiland.no (Stian Soiland) Date: Wed, 27 Jun 2007 14:47:54 +0100 Subject: What was that web interaction library called again? In-Reply-To: <77e5896b0706261405nce68e26re052a571c62fcc58@mail.gmail.com> References: <33E725AB-D965-4FC6-8207-E597EFE8F185@acm.org> <77e5896b0706261405nce68e26re052a571c62fcc58@mail.gmail.com> Message-ID: 2007/6/26, Omer Khalid : > On the RESTFul web service, I would like to piggy pack my own question two > is there a way to make the connection secure between two Restful service > running on GNU/linux? https? -- Stian S?iland Any society that would give up a little Manchester, UK liberty to gain a little security will http://soiland.no/ deserve neither and lose both. [Franklin] =/\= From twisted0n3 at gmail.com Fri Jun 22 17:00:50 2007 From: twisted0n3 at gmail.com (Twisted) Date: Fri, 22 Jun 2007 21:00:50 -0000 Subject: The Modernization of Emacs: terminology buffer and keybinding In-Reply-To: References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182272495.990807.99110@a26g2000pre.googlegroups.com> <87tzt3ihev.fsf@kobe.laptop> <1182370216.961241.6960@n60g2000hse.googlegroups.com> <85zm2ufjpb.fsf@lola.goethe.zz> <1182372592.803332.288260@u2g2000hsc.googlegroups.com> <1182373919.262388.100740@c77g2000hse.googlegroups.com> <85r6o6fhkb.fsf@lola.goethe.zz> <1182375045.626510.188170@m36g2000hse.googlegroups.com> Message-ID: <1182546050.465987.115740@q19g2000prn.googlegroups.com> On Jun 21, 12:09 pm, Robert Uhl wrote: > Twisted writes: > > >> > I have that exact URL now -- > >> >http://www.asktog.com/columns/027InterfacesThatKill.html > > >> Utterly unrelated to Emacs. > > > I think it is quite relevant. Clunky computer interfaces may not be so > > dramatically dangerous, but they certainly can hamper productivity. > > You're quite right. Windows/Mac user interfaces are so clunky that they > massively hamper productivity. This is a joke, right? > Emacs, OTOH, enables it. For example, > C-s is search forward; C-r is search backward ('reverse'); C-M-s is > search forward for a regular expression; C-M-r is search backward for a > regular expression. Aside from the collision with the standard in the case of C-s (should be save focused document if it has unsaved changes), these present no problem. The inability to find and use them without memorizing all those keystrokes does present a problem. > A Windows or Mac editor would have C-s for save, > and that's it. It might have C-f for find, but it'd pop up a dialogue > instead of offering an interactive search, causing a mental context > switch. Eh? In other words, it works the way it's supposed to. That dialogue will ordinarily be modeless but floating, so you can get it out of the way or use it to navigate the document, then edit the document without having to close the dialogue, and avoid the dialogue disappearing behind other things. New search can be typed in at the drop of a hat. Some editors have regular expression searches. All have a straightforward substring search. Generally if there's anything in the least arcane (e.g. regular expression searches) there's a ? button to pop up help, which goes directly to the search help. You can read this and tab back to the search dialogue with ease, and get them side by side without any mess or fuss. Of course the dialog offers search forward and usually search backward. And it normally also offers search-AND-REPLACE, to boot. Is this somehow not "interactive" enough for you? Versus having to memorize a bunch of keys. It also means no esc-meta-alt-ctrl-shift BS, as the document window needs to have only a few bindings, such as C-f and C-s, and only the one (C-f) for search; all the search bindings in the one window in emacs get replaced by just one binding in the document window and a bunch applicable to the find dialogue. And the find dialogue can be operated without knowing the bindings by mouse, and the bindings can be seen directly in the find dialogue by underlined letters on button labels (see that underlined N in "find Next"? It means you can hit alt-N while the dialogue has focus, followed by alt-tab to jump to the document with the next occurrence selected, or alt-N repeatedly to jump to later occurrences until you see the one you want, just in case you have rodent allergies). It has useful key bindings. It is also wise enough to make learning them optional, so you can learn the ones that speed up your most common tasks and spare the effort otherwise, where it would consume more time than it would eventually save you (less common tasks). With an emacs type interface, you only get to ignore the key bindings for commands you will NEVER use, rather than ones you use but infrequently. Forgetting the latter means a trip to the help every time, also. > Searching would interrupt one's flow of thought rather than being part of it. Where does this come from? From sean.farrow at seanfarrow.co.uk Fri Jun 8 11:40:41 2007 From: sean.farrow at seanfarrow.co.uk (Sean Farrow) Date: Fri, 8 Jun 2007 16:40:41 +0100 Subject: converting an int to a string Message-ID: Hi: I have the folling code: def parseTime(self, time): minutes =int(float(time)/60) seconds =int(float(time)-minutes*60) minutes =str(minutes) seconds =str(minutes) the statements that convert the minutes and seconds variables str(minutes) and str(seconds) don't seem to be working. Any idea why? is there any other way of doing this and perhaps using the $d interpolation operator? sean. From bignose+hates-spam at benfinney.id.au Thu Jun 21 19:31:26 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 22 Jun 2007 09:31:26 +1000 Subject: Google breaks international charset messages (was: Internationalised email subjects) References: <1182337500.638044.63470@e9g2000prf.googlegroups.com> <46791592$0$5719$edfadb0f@dread14.news.tele.dk> <1182346499.123234.279880@e9g2000prf.googlegroups.com> <1182417604.446766.47660@e9g2000prf.googlegroups.com> Message-ID: <87odj8x4tt.fsf_-_@benfinney.id.au> bugmagnet at gmail.com writes: > Seems some characters are missing from my last post. The line that > says: > > h = Header(' ', 'GB2312') > > should say: > > h = Header(' ', 'GB2312') Your message has this field in the header: Content-Type: text/plain; charset="us-ascii" which is why the non-ASCII characters don't appear. This is the fault of Google's charset munging. Please, people who use Google for mail and Usenet, kick them until they present "utf-8" as the default encoding, instead of downgrading to "us-ascii". -- \ "I lost a button-hole." -- Steven Wright | `\ | _o__) | Ben Finney From mclaugb at nospm.yahoo.com Tue Jun 19 07:23:38 2007 From: mclaugb at nospm.yahoo.com (mclaugb) Date: Tue, 19 Jun 2007 12:23:38 +0100 Subject: very simple shared dll with ctypes Message-ID: I have created a simple windows small_dll.dll exporting a function that does a computation using C and C++ classes which i wish to call from Python. I have read lots of ctypes documentation but I still dont quite understand how to call the function. As a test, I have written a much simpler mathematical function below to try to get it to work from Python. I am trying to call this from python by: >>from ctypes import * >>print cdll.small_dll.adder(c_double(5.343534),c_double(3.4432)) >>2223968 Can someone give me a few tips to get going! The DLL declaration is below. #include #if defined(_MSC_VER) #define DLL extern "C" __declspec(dllexport) #else #define DLL #endif DLL double adder(double a, double b){ double c; c=a+b; return c; } From robert.kern at gmail.com Tue Jun 26 12:53:42 2007 From: robert.kern at gmail.com (Robert Kern) Date: Tue, 26 Jun 2007 11:53:42 -0500 Subject: _hashlib portability issue In-Reply-To: <46811660.4060905@gmail.com> References: <46811660.4060905@gmail.com> Message-ID: Olivier Feys wrote: > Hi all, > > I build python 2.5 on linux-x86-64 (centos). > Why is lib-dynload/_hashlib.so dynamically linked with libssl.so.0.9.7 > and not with libssl.so that points on it (same thing for libcrypto.so)? > This causes problems when copying all the python distribution and > running it on a different os, where the theses lib versions are not > allways the same. > Is it possible to configure that ? I don't think so. I think that ld simply follows the symbolic links down to the actual file. I'm a bit hazy on this, though. `info ld` has not enlightened me, either. -- 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 nguyenhuuthanh at gmail.com Sat Jun 23 03:06:52 2007 From: nguyenhuuthanh at gmail.com (Genie T) Date: Sat, 23 Jun 2007 07:06:52 -0000 Subject: newbie question about unicode In-Reply-To: References: <1182571819.128093.18980@i13g2000prf.googlegroups.com> Message-ID: <1182582412.960114.282430@a26g2000pre.googlegroups.com> On Jun 23, 1:06 pm, "Gabriel Genellina" wrote: > En Sat, 23 Jun 2007 01:10:19 -0300, Genie T > escribi?: > > > can anybody tell me whether these two expressions have the same > > meanings? > > > s = u'' > > s1 = s.encode('utf-8') > > > AND > > > s1 = unicode(s,'utf-8') > > No - but consider this (assuming your terminal uses utf-8): > > py> u1 = u'' > py> s1 = u1.encode('utf-8') > py> > py> s2 = '' > py> u2 = s2.decode('utf-8') > py> > py> type(u1), type(u2) > (, ) > py> u1==u2 > True > py> type(s1), type(s2) > (, ) > py> s1==s2 > True > > -- > Gabriel Genellina Thanks, i'm clear now From deets at nospam.web.de Wed Jun 6 11:37:10 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 06 Jun 2007 17:37:10 +0200 Subject: Can os.remove followed by os.path.isfile disagree? References: <1181140547.279974.83550@q66g2000hsg.googlegroups.com> Message-ID: <5co2l6F31fu1eU2@mid.uni-berlin.de> ppaterson at gmail.com wrote: > Can os.path.isfile(x) ever return True after os.remove(x) has > successfully completed? (Windows 2003, Python 2.3) > > We had a couple of failures in a server application that we cannot yet > reproduce in a simple case. Analysis of the code suggests that the > only possible explanation is that the following occurs, > > os.remove(x) > .... stuff > if os.path.isfile(x): > raise "Ooops, how did we get here?" > file(x, "wb").write(content) > > We end up in the raise. By the time we get to look at the system the > file is actually gone, presumably because of the os.remove. > > The "stuff" is a handful of lines of code which don't take any > significant time to perform. There are no "try" blocks to mask a > failure in the os.remove call. > > > The application is multithreaded so it is possible that another thread > writes to the file between the "remove" and the "isfile", but at the > end of the failure the file is actually not on the filesystem and I > don't believe there is a way that the file could be removed again in > this scenario. Is the file on a network drive by any chance? Diez From damienlmoore at gmail.com Fri Jun 8 15:14:15 2007 From: damienlmoore at gmail.com (dmoore) Date: Fri, 08 Jun 2007 19:14:15 -0000 Subject: Bug/Weak Implementation? popen* routines can't handle simultaneous read/write? In-Reply-To: References: <1181232071.928835.301710@w5g2000hsg.googlegroups.com> <1181264380.441881.38570@i13g2000prf.googlegroups.com> Message-ID: <1181330055.380987.294550@p47g2000hsd.googlegroups.com> On Jun 8, 12:30 pm, Nick Craig-Wood wrote: > Windows has a really strange idea of non-blocking IO - it uses > something called overlapped io. You or in the FILE_FLAG_OVERLAPPED > flag when you create the file/pipe. You then pass in overlap buffers > for reading writing. > the wx guys appear to do it differently (unless FILE_FLAG_OVERLAPPED is implicit in the calls they make) take a look at: http://cvs.wxwidgets.org/viewcvs.cgi/wxWidgets/src/msw/utilsexc.cpp?rev=1.88&content-type=text/vnd.viewcvs-markup a reasonably well-documented wxExecute function handles all the messy win32 api calls and wraps the process in a wxProcess object and the streams in wxInputStream / wxOutputStream (also see the wxExecuteDDE function) From deets at nospam.web.de Sat Jun 30 04:13:58 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sat, 30 Jun 2007 10:13:58 +0200 Subject: Building a Python app with Mozilla In-Reply-To: <9qnhi.9511$c06.3368@newssvr22.news.prodigy.net> References: <9qnhi.9511$c06.3368@newssvr22.news.prodigy.net> Message-ID: <5emhm7F380g5gU1@mid.uni-berlin.de> > You apparently didn't look very hard. On the wxPython end of things > (which I have experience with), there is wxGlade, XRCed, Boa > Constructor, Dabo, etc. I don't know about Tkinter (I don't use it), > but I know that at least Qt has a very nice GUI designer and builder > (from Trolltech if you are willing to pay for it), and if I remember > correctly, Eric4 offers some tools to make PyQt editing nice and > friendly. I'm sure there are others. You're somewhat wrong regarding Qt. The designer is free (I did never use a commercial Qt, maybe there comes something additional - but IF I don't have the faintest idea what it could do that would make it better than the free designer.) And eric is cool and integrates with Qt (and is an example of a Qt-app itself), via launching the designer - but it hasn't have any gui-building stuff in there. Diez From pjb at informatimago.com Fri Jun 22 17:06:15 2007 From: pjb at informatimago.com (Pascal Bourguignon) Date: Fri, 22 Jun 2007 23:06:15 +0200 Subject: The Modernization of Emacs: terminology buffer and keybinding References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182272495.990807.99110@a26g2000pre.googlegroups.com> <87tzt3ihev.fsf@kobe.laptop> <1182370216.961241.6960@n60g2000hse.googlegroups.com> <85zm2ufjpb.fsf@lola.goethe.zz> <1182372592.803332.288260@u2g2000hsc.googlegroups.com> <1182373919.262388.100740@c77g2000hse.googlegroups.com> <85r6o6fhkb.fsf@lola.goethe.zz> <1182375045.626510.188170@m36g2000hse.googlegroups.com> <1182546050.465987.115740@q19g2000prn.googlegroups.com> Message-ID: <871wg3k8c8.fsf@thalassa.lan.informatimago.com> Twisted writes: > On Jun 21, 12:09 pm, Robert Uhl wrote: >> Twisted writes: >> >> >> > I have that exact URL now -- >> >> >http://www.asktog.com/columns/027InterfacesThatKill.html >> >> >> Utterly unrelated to Emacs. >> >> > I think it is quite relevant. Clunky computer interfaces may not be so >> > dramatically dangerous, but they certainly can hamper productivity. >> >> You're quite right. Windows/Mac user interfaces are so clunky that they >> massively hamper productivity. > > This is a joke, right? How do you call a Mac user interface that let a user work during 3 hours to do a simple modification to a MS-Word file that takes 15 seconds to do with emacs or a simple unix script? -- __Pascal Bourguignon__ http://www.informatimago.com/ NOTE: The most fundamental particles in this product are held together by a "gluing" force about which little is currently known and whose adhesive power can therefore not be permanently guaranteed. From http Tue Jun 26 13:13:58 2007 From: http (Paul Rubin) Date: 26 Jun 2007 10:13:58 -0700 Subject: Portable general timestamp format, not 2038-limited References: <1182544384.709759.235300@o11g2000prd.googlegroups.com> <20070625133843.9e25d0ab.steveo@eircom.net> <82b5l4-tvh.ln1@zoogz.gregorie.org> <7xbqf3lc7i.fsf@ruckus.brouhaha.com> <70c7l4-2gp.ln1@zoogz.gregorie.org> Message-ID: <7xlke6y6y1.fsf@ruckus.brouhaha.com> Martin Gregorie writes: > I don't recall the OP mentioning time interval computability - just a > requirement for sub second accuracy timestamps. That Y2038 is an issue suggests the OP wants a timestamp format that is future-proof and that means it should be good for all plausible applications. That would include computing intervals. > > If you want a precise timestamp and you don't > > want to deal with leap seconds, TAI is one approach. > > > TAI? Care to provide a reference? Same one already given: http://cr.yp.to/proto/utctai.html From compiledmonkey at gmail.com Tue Jun 5 15:01:01 2007 From: compiledmonkey at gmail.com (Chris Stewart) Date: Tue, 5 Jun 2007 15:01:01 -0400 Subject: web development without using frameworks Message-ID: <20d6f8950706051201mba83194hcbc4d17cd2439cd@mail.gmail.com> I'm interested in learning web based python without the use of fancy frameworks that are out there. I'm having a hard time coming up with resources and examples for this. Does anyone have anything that could be helpful? -- Chris Stewart compiledmonkey at gmail.com http://www.compiledmonkey.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Mon Jun 4 04:50:14 2007 From: __peter__ at web.de (Peter Otten) Date: Mon, 04 Jun 2007 10:50:14 +0200 Subject: int vs long References: <1180839659.196587.194200@p77g2000hsh.googlegroups.com> <7xr6otiv4l.fsf@ruckus.brouhaha.com> <1180895701.813483.326780@k79g2000hse.googlegroups.com> <7xabvgj33p.fsf@ruckus.brouhaha.com> <1hz4uas.7jeyyu192pb8tN%aleax@mac.com> Message-ID: Marc 'BlackJack' Rintsch wrote: > In , Peter Otten wrote: > >> Marc 'BlackJack' Rintsch wrote: >> >>>>>> from itertools import count >>>>>> from sys import maxint >>>>>> c = count(maxint) >>>>>> c.next() >>> 2147483647 >>>>>> c.next() >>> -2147483648 >>> >>> What I find most disturbing here, is that it happens silently. I would >>> have expected an exception instead of the surprise. >> >> This is fixed in Python2.5: >> >>>>> from itertools import count >>>>> import sys >>>>> c = count(sys.maxint) >>>>> c.next(), c.next() >> (2147483647, 2147483648L) > > Hm, my test above was from 2.5!? Then your installation is broken. What does >>> import itertools >>> itertools print? By the way, here's what I get if I force the wrong library upon python2.5: /usr/local/lib/python2.4/lib-dynload $ python2.5 Python 2.5 (r25:51908, Oct 3 2006, 08:48:09) [GCC 3.3.3 (SuSE Linux)] on linux2 Type "help", "copyright", "credits" or "license" for more information. sys:1: RuntimeWarning: Python C API version mismatch for module readline: This Python has API version 1013, module readline has version 1012. >>> import itertools __main__:1: RuntimeWarning: Python C API version mismatch for module itertools: This Python has API version 1013, module itertools has version 1012. >>> itertools >>> import sys >>> c = itertools.count(sys.maxint) >>> c.next(), c.next() (2147483647, -2147483648) Peter From nospam at nospam.com Thu Jun 14 00:56:51 2007 From: nospam at nospam.com (Mark T) Date: Wed, 13 Jun 2007 21:56:51 -0700 Subject: passing arguments to tcpserver classes References: Message-ID: "Eric Spaulding" wrote in message news:mailman.9058.1181745026.32031.python-list at python.org... > Is there an easy way to pass arguments to a handler class that is used by > the standard TCPServer? > > normally --> srvr =SocketServer.TCPServer(('',port_num), TCPHandlerClass) > > I'd like to be able to: srvr =SocketServer.TCPServer(('',port_num), > TCPHandlerClass, (arg1,arg2)) > > And have arg1, arg2 available via TCPHandlerClass.__init__ or some other > way. > > Where TCPHandlerClass: > > class TCPHandlerClass(SocketServer.StreamRequestHandler): > def handle(self): > #handle stream events here# > > > Thanks for any advice. > In the handler class, self.server refers to the server object, so subclass the server and override __init__ to take any additional server parameters and store them as instance variables. import SocketServer class MyServer(SocketServer.ThreadingTCPServer): def __init__(self, server_address, RequestHandlerClass,arg1,arg2): SocketServer.ThreadingTCPServer.__init__(self,server_address,RequestHandlerClass) self.arg1 = arg1 self.arg2 = arg2 class MyHandler(SocketServer.StreamRequestHandler): def handle(self): print self.server.arg1 print self.server.arg2 if __name__ == '__main__': srv = MyServer(('',5000),MyHandler,123,456) srv.serve_forever() --Mark From kelvin.you at gmail.com Thu Jun 7 12:01:07 2007 From: kelvin.you at gmail.com (kelvin.you at gmail.com) Date: Thu, 07 Jun 2007 16:01:07 -0000 Subject: Why can not catch the inner exception In-Reply-To: References: <1181215054.826742.75930@n15g2000prd.googlegroups.com> Message-ID: <1181232067.874362.321090@d30g2000prg.googlegroups.com> On 6 7 , 10 53 , "Mark T" wrote: > " " wrote in message > > news:1181215054.826742.75930 at n15g2000prd.googlegroups.com... > > > > > > > Please see the follow code, I can not catch the exception " IOError" > > raised from shutil.copyfile() , why? > > try: > > if (DEST_TYPE & TYPE_FTP): > > fn = oname > > ftpc.UploadFile(f, fn) > > else: > > fn = os.path.join(dst, oname) > > shutil.copyfile(f, fn) > > > .... other code.... > > > except [IOError, FtpcException],why: > > num = 0 > > print >>sys.stderr, "can not copy '%s' to '%s': > > %s"%(f, fn, why) > > ERR_NUM += 1 > > > I must do like this: > > try: > > if (DEST_TYPE & TYPE_FTP): > > fn = oname > > ftpc.UploadFile(f, fn) > > else: > > fn = os.path.join(dst, oname) > > try: > > shutil.copyfile(f, fn) > > except IOError: > > .... > > > .... other code.... > > > except [IOError, FtpcException],why: > > num = 0 > > print >>sys.stderr, "can not copy '%s' to '%s': > > %s"%(f, fn, why) > > ERR_NUM += 1 > > > Thanks! > > , > > Use a tuple (IOError,FtpcException) instead of a list in the except > statement and it works. > > -- - - > > - - Thank you! :-) From JoeSalmeri at hotmail.com Mon Jun 4 07:29:53 2007 From: JoeSalmeri at hotmail.com (Joe Salmeri) Date: Mon, 4 Jun 2007 07:29:53 -0400 Subject: Python 2.5.1 broken os.stat module References: <466140A6.1090100@v.loewis.de><-aOdnbFdroD_gP_bnZ2dnUVZ_uKknZ2d@comcast.com><4662750b$0$29898$9b622d9e@news.freenet.de> Message-ID: Perspective is often the source of problems with communication. You view timezones and DST as offsets from GMT. I understand and respect that perspective. When I think of timezones and DST I think of the timezone setting and the DST setting in Windows. These settings are two separate settings in Windows that can be configured individually and independent of each other. When I think of a time I think of somedate, sometime, Eastern Standard Time (EST) OR somedate, sometime, Eastern Standard Time Daylight Saving Time (EST DST) If you view things from my perspective then I would hope my comments become more clear. Last night I was talking to my wife about this discussion (I need to get a life :-)) and she came up with an analogy that I like even better than my TV analogy. Suppose she has a baby 01/02/2007 07:00 PM. Today, a time after DST has started for this region someone asks her when her baby was born. Here answer would be 01/02/2007 07:00 PM. If we ask Windows that same question it would be 01/02/2007 08:00 PM. Please see my other response to Martin because using your logic of "a DST change is a timezone change" that would mean that the textual representation of dates by Python 2.5.1 is WRONG. I don't believe that to be true but you cannot have it both ways, if a DST change is a timezone change then Python should show the same dates as Windows does, if it is not the same then Python should show the dates that it is. From rhamph at gmail.com Fri Jun 1 14:43:19 2007 From: rhamph at gmail.com (Rhamphoryncus) Date: Fri, 01 Jun 2007 18:43:19 -0000 Subject: Thread-safety of dict In-Reply-To: References: Message-ID: <1180723399.170061.310070@a26g2000pre.googlegroups.com> On Jun 1, 3:51 am, Duncan Booth wrote: > "Adam Olsen" wrote: > > So there you have it: if you're using a dict with custom classes (or > > anything other than str) across multiple threads, and without locking > > it, it's possible (though presumably extremely rare) for a lookup to > > fail even through the key was there the entire time. > > Nice work. > > It would be an interesting exercise to demonstrate this in practice, and I > think it should be possible without resorting to threads (by putting > something to simulate what the other thread would do into the __cmp__ > method). I had attempted to do so, but I lost interest when I realized I'd have to manipulate the memory allocator at the same time. ;) > I don't understand your reasoning which says it cannot stay in > ma_smalltable: PyDict_SetItem only calls dictresize when at least 2/3 of > the slots are filled. You can have 5 items in the small (8 slot) table and > the dictionary will resize to 32 slots on adding the 6th,the next resize > comes when you add the 22nd item. What you're missing is that a slot can be in any of 3 states: 1) Active. A key is here. If the current slot doesn't match lookdict() will try the next one. 2) Dummy. Used to be a key here, but now it's gone. lookdict() will try the next one. 3) NULL. Never was a key here. lookdict() will stop. lookdict() needs the NULL slots to stop searching. As keys are added and removed from the table it will get filled with dummy slots, so when the total number of active+dummy slots exceeds 2/3rds it will trigger a resize (to the same size or even a smaller size!) so as to clear out all the dummy slots (letting lookups finish sooner). -- Adam Olsen, aka Rhamphoryncus From bruno.desthuilliers at gmail.com Thu Jun 21 16:42:54 2007 From: bruno.desthuilliers at gmail.com (bruno.desthuilliers at gmail.com) Date: Thu, 21 Jun 2007 20:42:54 -0000 Subject: Inferring initial locals() In-Reply-To: <1182451904.703471.141000@n60g2000hse.googlegroups.com> References: <1182451904.703471.141000@n60g2000hse.googlegroups.com> Message-ID: <1182458574.630461.121290@o61g2000hsh.googlegroups.com> On Jun 21, 8:51 pm, George Sakkis wrote: > I wonder if there is a (preferably not too-hackish) solution to the > following introspection problem: given a callable and a number of > positional and/or keyword arguments, infer what would be the frame's > locals() right after the function is called. For example, given: > > def f(x, y=1, *a, **k): > z = x + y > w = len(a) - len (k) > return z * w > > I'd like to have a function > > def get_init_locals(callable, *args, **kwds): > # TODO > pass > > so that: > > >>> get_init_locals(f, 3) > > {'a': (), 'k': {}, 'x': 3, 'y': 1} You might be intersted in the 'inspect' module. From mail at microcorp.co.za Thu Jun 7 02:21:48 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Thu, 7 Jun 2007 08:21:48 +0200 Subject: ftplib error- Large file References: <1181147997.268014.50550@i38g2000prf.googlegroups.com> Message-ID: <017701c7a8ce$1570ecc0$03000080@hendrik> wrote: > Hi all, > > I'm using ftplib to transfer large files to remote sites. The process > seems to work perfectly with small files, but when the file gets to > large ~20GB I begin getting errors that sometimes seem to be non- > fatal, and other times the transfer does not complete. I've debugged > the hell out of the code, and can't figure out what is going on..is it > the remote site? Packet loss? > 20 gig is a big thing - what is your link speed, and how long does the thing run before falling over - Is your ISP maybe giving you or the remote site a new IP addy periodically? Are there any "anti jabber" precautions taken anywhere? you may have to break it up into smaller chunks and glue them together remotely... hth - Hendrik From sjmachin at lexicon.net Fri Jun 8 21:38:38 2007 From: sjmachin at lexicon.net (John Machin) Date: Fri, 08 Jun 2007 18:38:38 -0700 Subject: Working with fixed format text db's In-Reply-To: References: Message-ID: <1181353118.898321.156260@g37g2000prf.googlegroups.com> On Jun 9, 7:55 am, Jeremy C B Nicoll wrote: > Neil Cerutti wrote: > > On 2007-06-08, Jeremy C B Nicoll wrote: > > > Neil Cerutti wrote: > > >> Luckily, the output format has not changed yet, so issues with > > >> maintaining the above haven't arisen. > > > > The problem surely is that when you want to change the format > > > you have to do so in all files (and what about the backups > > > then?) and all programs simultaneously. > > > I don't have control of the format, unfortunately. It's an import > > file format for a commercial database application. > > You're saying your program merely has to read data files created by that > database app? It's not that you have a whole suite of programs that create > and read these files, nor that you have years worth of old files that would > need their format converted if the programs were changed? > > > It is not actually *hard* to do this with ad-hoc code, but then > > the program is indecipherable without a hardcopy of the spec in > > hand. And also, as you say, if the spec ever does change, the > > hand-written batch of ljust, rjust and slice will be somewhat of > > a pain to reconfigure. > > You could presumably define a list (of some sort, might be the wrong > terminology) that defines the 'name', type, length, justification and > padding of each field, and then make the explicit code you showed loop > through that list and do what's needed field by field. > > There's a risk that abstracting the definitions will make the code less > clear to anyone else; at least it's clear what the current stuff does. > > > But biggest weakness, to me, is that the specification is not in > > the code, or read and used by the code, and I think it should be. > > It'd be better if you could read the data layout spec from some file > produced by the database system. No chance perhaps of having the dat files > include some sort of dummy first record that contains the necessary info in > a form that you could interpret? The OP is *WRITING* not reading. From urbangabo at gmail.com Mon Jun 25 05:21:50 2007 From: urbangabo at gmail.com (Gabor Urban) Date: Mon, 25 Jun 2007 11:21:50 +0200 Subject: Emacs topic should be stopped.... Message-ID: Hi guys, I was going through most of this topic, but I find this not relevant on THIS mailing list....... A short summary: there are some people who are not disturbed by proven facts. They are mostly attackers of emacs/Xemacs or vim... Or even linux and open source. Quite funny, since this is a mailing list of an open source programming language. :-)))) Arguments and logic are not working, it's been a 'religious' flame topic. I am open to discuss this issue further in private...... Gabor -------------- next part -------------- An HTML attachment was scrubbed... URL: From no-sp at m-from.net Thu Jun 14 05:34:41 2007 From: no-sp at m-from.net (Giuseppe Di Martino) Date: Thu, 14 Jun 2007 11:34:41 +0200 Subject: for web application development References: <1181812584.392929.232670@o11g2000prd.googlegroups.com> Message-ID: Il Thu, 14 Jun 2007 09:16:24 +0000, james_027 ha scritto: > > My problem is looking for a web framework for python, that could > provide a natural way of developing web app. I am avoiding to learn > template language as much as possible. Currently, i'm playing with Pylons (http://pylonshq.com) and until now i'm happy ! Giuseppe From darrinth at gmail.com Tue Jun 12 08:49:52 2007 From: darrinth at gmail.com (Darrin Thompson) Date: Tue, 12 Jun 2007 08:49:52 -0400 Subject: Build problem, pyopenssl on win32 vs2003. Message-ID: I've been trying to build pyOpenSSL on Windows with Visual Studio 2003. I've hit the message below: building 'OpenSSL.SSL' extension creating build\temp.win32-2.5\Release\src\ssl C:\Program Files\Microsoft Visual Studio .NET 2003\Vc7\bin\cl.exe /c /nologo /Ox /MD /W3 /GX /DNDEBUG -Ic:\OpenSSL\include -Ic:\Python25\include -Ic:\Python25\PC /Tcsrc/ssl/connection.c /Fobuild\temp.win32-2.5\Release\src/ssl/connection.obj connection.c c:\cygwin\home\pandora\build-toolchain\build\pyOpenSSL-0.6\src\crypto\x509name.h(27) : error C2059: syntax error : '(' c:\cygwin\home\pandora\build-toolchain\build\pyOpenSSL-0.6\src\crypto\x509name.h(30) : error C2059: syntax error : '}' c:\OpenSSL\include\openssl\x509v3.h(185) : error C2059: syntax error : '(' c:\OpenSSL\include\openssl\x509v3.h(193) : error C2059: syntax error : 'type' c:\OpenSSL\include\openssl\x509v3.h(197) : error C2059: syntax error : '}' I dug in and looked at preprocessor output. For some reason, after winsock.h is included, X509_NAME is replaced with ((LPCSTR) 7). Oh, And I'm building against the windows binaries build by "shining light productions". Any ideas on how to fix this? -- Darrin From montyphyton at gmail.com Tue Jun 5 05:35:47 2007 From: montyphyton at gmail.com (montyphyton at gmail.com) Date: Tue, 05 Jun 2007 02:35:47 -0700 Subject: Who uses Python? In-Reply-To: <1180985830.288414.208850@q69g2000hsb.googlegroups.com> References: <1180985830.288414.208850@q69g2000hsb.googlegroups.com> Message-ID: <1181036147.620798.268520@p47g2000hsd.googlegroups.com> i use it for text mining, processing large text corpora for scientific purposes. i'm also working on some neat data mining tools written in python (called orange, in case someone's interested) walterbyrd je napisao/la: > I mean other than sysadmins, programmers, and web-site developers? > > I have heard of some DBAs who use a lot of python. > > I suppose some scientists. I think python is used in bioinformatics. I > think some math and physics people use python. > > I suppose some people use python to learn "programming" in general. > Python would do well as a teaching language. > > I would think that python would be a good language for data analysis. > > Anything else? Finance? Web-analytics? SEO? Digital art? From wildemar at freakmail.de Mon Jun 4 17:20:13 2007 From: wildemar at freakmail.de (Wildemar Wildenburger) Date: Mon, 04 Jun 2007 23:20:13 +0200 Subject: *Naming Conventions* In-Reply-To: <1180990280.960271.235550@h2g2000hsg.googlegroups.com> References: <1180909218.939713.112010@q69g2000hsb.googlegroups.com> <1180990280.960271.235550@h2g2000hsg.googlegroups.com> Message-ID: <4664820D.3060503@freakmail.de> bruno.desthuilliers at gmail.com wrote: > On Jun 4, 12:20 am, Ninereeds wrote: > >> First, for small loops with loop variables whose meaning is obvious >> from context, the most readable name is usually something like 'i' or >> 'j'. >> > > 'i' and 'j' are the canonical names for for loops indices in languages > that don't support proper iteration over a sequence. Using them for > the iteration variable of a Python for loop (which is really a > 'foreach' loop) would be at best confusing. > > While that is true, I guess it is commonplace to use i, j, k and n (maybe others) in constructs like for i in range(len(data)): do_stuff(data[i]) Or should the good python hacker do that differently? Hope not ;). /W From supercooper at gmail.com Wed Jun 13 09:36:45 2007 From: supercooper at gmail.com (supercooper) Date: Wed, 13 Jun 2007 13:36:45 -0000 Subject: Convert binary string to something meaningful?? Message-ID: <1181741805.699933.113610@q19g2000prn.googlegroups.com> I have this string that is being returned from a query on a DBISAM database. The field must be some sort of blob, and when I connect to the database thru ODBC in MS Access, the field type comes thru as OLE Object, and Access cannot read the field (it usually crashes Access). I can sorta pick out the data that I need (7.0, 28, 5TH PRINCIPAL MRD, 10.0 - and these occur in roughly the same place in every record returned from the db), but I am wondering if there is a way to convert this. I looked at the struct module, but I really dont know the format of the data for sure. For starters, could someone tell me what '\x00' more than likely is? Any hints on modules to look at or esp code snippets would be greatly appreciated. Thanks. \x9c \x01\x00\x007.0\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00 28.0\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00 10.0\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00WN \x00\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00\x10\xa3@ \x00\x00\x00\x00\x00\x10\x7f at NE NW SE \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00CONGRESS QTR\x00\x00\x00\x005\x00\x005TH PRINCIPAL MRD \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x0 0\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x0 0\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x0 0\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00 From mitko at qlogic.com Tue Jun 5 17:11:13 2007 From: mitko at qlogic.com (Mitko Haralanov) Date: Tue, 5 Jun 2007 14:11:13 -0700 Subject: Getting mount stats for filesystems In-Reply-To: <4665ba45$0$19674$9b622d9e@news.freenet.de> References: <46650e6c$0$25817$9b622d9e@news.freenet.de> <4665a7e9$0$24866$9b622d9e@news.freenet.de> <4665ba45$0$19674$9b622d9e@news.freenet.de> Message-ID: <20070605141113.653a35c9@opal.pathscale.com> On Tue, 05 Jun 2007 21:32:21 +0200 "Martin v. L?wis" wrote: > You could try to invoke getmntent(3). I'm not aware of a Python wrapper > for it, so you either try to write one yourself in C, or use ctypes to > write it in Python. I am looking at ctypes and it might do what I need but I can't figure out a way to convert a Python File object to a C FILE pointer (which is the needed argument for getmntent). Any ideas? -- Mitko Haralanov mitko at qlogic.com Senior Software Engineer 650.934.8064 System Interconnect Group http://www.qlogic.com ========================================== Fry: That clover helped my rat-fink brother steal my dream of going into space. Now I'll never get there. Leela: You went there this morning for donuts. From martin at v.loewis.de Thu Jun 21 16:01:16 2007 From: martin at v.loewis.de (=?ISO-8859-2?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Thu, 21 Jun 2007 22:01:16 +0200 Subject: Changing the names of python keywords and functions In-Reply-To: <1182452862.872909.206780@u2g2000hsc.googlegroups.com> References: <1182452862.872909.206780@u2g2000hsc.googlegroups.com> Message-ID: <467ad90c$0$22151$9b622d9e@news.freenet.de> > "<> OS"- (THIS IS MY IMAGINARY EXAMPLE OF KEYWORD), > > my program must write this code in some user file, but my > > program must read this command like: "import os".How > > can I do something like that?? The keywords are listed in Grammar/Grammar. You need to edit this file, then recompile. Regards, Martin From dak at gnu.org Sun Jun 24 02:56:58 2007 From: dak at gnu.org (David Kastrup) Date: Sun, 24 Jun 2007 08:56:58 +0200 Subject: The Modernization of Emacs: terminology buffer and keybinding References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182272495.990807.99110@a26g2000pre.googlegroups.com> <87tzt3ihev.fsf@kobe.laptop> <1182370216.961241.6960@n60g2000hse.googlegroups.com> <85zm2ufjpb.fsf@lola.goethe.zz> <1182372592.803332.288260@u2g2000hsc.googlegroups.com> <5dtk4tF34jrimU1@mid.dfncis.de> <1182375388.814275.227380@n2g2000hse.googlegroups.com> <87645h73ei.fsf@W0053328.mgh.harvard.edu> <1182548563.561252.82480@i13g2000prf.googlegroups.com> <1182666078.511962.280030@w5g2000hsg.googlegroups.com> Message-ID: <85veddet6t.fsf@lola.goethe.zz> Twisted writes: > On Jun 23, 8:35 pm, Robert Uhl wrote: >> Twisted writes: >> >> > For an example of the latter, consider opening a file. Can't remember >> > the exact spelling and capitalization of the file name? Sorry, bud, >> > you're SOL. Go find it in some other app and memorize the name, then >> > return to emacs. >> >> Once again I am forced to wonder if you have _ever_ actually used >> emacs. find-file has tab completion: hit tab without anything typed, and >> it displays _everything_ in the directory; type a few characters to >> narrow it down; hit tab to complete the filename and be done with it. >> >> Or of course you could use directory mode, which enables you to navigate >> around a directory tree, performing actions on files (including editing >> them). >> >> Then of course there's ido.el, which is even better: type a few >> characters from anywhere in the name, and it displays files matching >> those characters. > > Really? None of this happens if you just do the straightforward file- > open command, which should obviously at least provide a navigable > directory tree, but definitely does not. It definitely _does_ when you are using the mouse to open your file dialog. Again, _try_ a current version of Emacs before showing your ignorance. [Other nonsensical speculation deleted] -- David Kastrup, Kriemhildstr. 15, 44793 Bochum From bblais at bryant.edu Sat Jun 23 18:27:48 2007 From: bblais at bryant.edu (Brian Blais) Date: Sat, 23 Jun 2007 18:27:48 -0400 Subject: database design help Message-ID: <467D9E64.70803@bryant.edu> Hello, I am trying to design a system for people to submit a series of documents to a project. I want users to have the ability to submit updates to any documents, so that there should be a history (or sequence) for each document. I think in terms of python data structures, so the relational database organization is not all that clear to me (so I am trying to learn it!). I am using buzhug, but the concept should be the same in any rdb. So my conceptual structure would look something like: project1: document 1, document 1a, document 1b document 2 document 3, document 3a project 2: document 4, document 4a etc... I want to be able to query the history of any single document, so I can get a list of document 1, 1a, and 1b. or document 3 and 3a, etc... So I have something like this (omitting a few lines, for clarity) to set up the record structure: users.create(('name',str), ('email',str)) project.create( ('description',str), ('label',str), ('creation_date',date), ('submitter',users)) documents.create(('filename',str), ('submit',date), ('submitter',users), ('type',str), ('project',project)) with this structure, I can get a project with a series of documents, but each document doesn't have a history. My first thought (with Python data structures) is to use a list, but that's not an rdb concept. Do I make something like: document_sequences.create(('name',str),('project',project)) and then change documents so that it contains not only a project field, but a document_sequence field? Am I thinking about this correctly? Is there a resource I can read that goes through any of this? thanks, Brian Blais -- ----------------- bblais at bryant.edu http://web.bryant.edu/~bblais From eadmund42 at NOSPAMgmail.com Sat Jun 23 21:36:30 2007 From: eadmund42 at NOSPAMgmail.com (Robert Uhl) Date: Sat, 23 Jun 2007 19:36:30 -0600 Subject: The Modernization of Emacs References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182370894.001918.36590@k79g2000hse.googlegroups.com> <1182372821.298343.316860@g4g2000hsf.googlegroups.com> <1182375321.067664.190780@o61g2000hsh.googlegroups.com> <86hcp1l6hb.fsf@lola.quinscape.zz> <1182552254.233679.180790@o11g2000prd.googlegroups.com> Message-ID: nebulous99 at gmail.com writes: > > And both of them, though especially the latter, regarding what a > feeping creature emacs is. I like it. Every new version has great new abilities. > I don't suppose there's also a kitchen sink in there somewhere? Or is > that just nethack? Check out nethack.el . You can run nethack within emacs. This, of course, means that there _is_ a kitchen sink within emacs (when it's running nethack within itself)... -- Robert Uhl I don't think the Java folks are nuts for what they've done. I just don't like how hard they make certain simple and important things. --Kent M. Pitman From compiledmonkey at gmail.com Sun Jun 3 11:07:48 2007 From: compiledmonkey at gmail.com (Chris Stewart) Date: Sun, 3 Jun 2007 11:07:48 -0400 Subject: Why Python? Message-ID: <20d6f8950706030807u4c37ffb9xfa063edcc26d056f@mail.gmail.com> What is it about Python that makes it such a suitable language for you? For instance, why would you use it over something similarly portable as Java, or PHP? I know personally, in my small exposure to Python, I can see it as a great learning tool for a basic introduction to programming and even OOP. It's wonderful how your .py file can simply start making expressions without any overhead, import/using statements, class declarations, etc. -- Chris Stewart compiledmonkey at gmail.com http://www.compiledmonkey.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From evan at yelp.com Thu Jun 21 12:17:10 2007 From: evan at yelp.com (Evan Klitzke) Date: Thu, 21 Jun 2007 09:17:10 -0700 Subject: How to create a file with read access rights In-Reply-To: <1182439636.529600.126210@c77g2000hse.googlegroups.com> References: <1182439636.529600.126210@c77g2000hse.googlegroups.com> Message-ID: On 6/21/07, Johny wrote: > Is it possible to create a file on Linux with access rights? > For example > owner can read and write into the file > others can only read from the file > Thanks for replies Look at the documentation for os.open (for new files) and os.chmod (for existing files). -- Evan Klitzke From david.bear at asu.edu Thu Jun 7 18:40:48 2007 From: david.bear at asu.edu (David Bear) Date: Thu, 07 Jun 2007 15:40:48 -0700 Subject: Running a process every N days References: <1181255261.648057.184930@x35g2000prf.googlegroups.com> Message-ID: <6129003.7R4uPG4ZZ5@teancum> danmcleran at yahoo.com wrote: > What's the best way to run either an entire python process or a python > thread every N days. I'm running Python 2.4.3 on Fedora Core 5 Linux. > My code consists of a test and measurement system that runs 24/7 in a > factory setting. It collects alot of data and I'd like to remove all > data older than 30 days. My ideal solution would be something that > runs in the background but only wakes up to run every few days to > check for old data. > > Thanks, > > Dan McLeran And you can use cron to launch your python program? -- David Bear -- let me buy your intellectual property, I want to own your thoughts -- From stefan.behnel-n05pAM at web.de Tue Jun 19 02:22:44 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Tue, 19 Jun 2007 08:22:44 +0200 Subject: HTMLParser.HTMLParseError: EOF in middle of construct In-Reply-To: References: Message-ID: <46777634.703@web.de> Sergio Monteiro Basto wrote: > Can someone explain me, what is wrong with this site ? > > python linkExtractor3.py http://www.noticiasdeaveiro.pt > test > > HTMLParser.HTMLParseError: EOF in middle of construct, at line 1173, > column 1 > > at line 1173 of test file is perfectly normal . > > I like to know what I have to clean up before parse the html page > I send in attach the python code . You don't want to do these things with HTMLParser. lxml is much easier to use and supports broken HTML (as in the page you're parsing). Note that there is a SVN branch of lxml that comes with an html package (lxml.html) that provides a "clean()" function. Just parse the page with the HTML parser provided by the package (a few lines), then call the clean() function on it with the parameters you want to get rid of scripts and the like. The docs: http://codespeak.net/lxml/dev/ The SVN branch: http://codespeak.net/svn/lxml/branch/html/ You seem to be on Linux, so compiling lxml should be simple enough: http://codespeak.net/lxml/dev/build.html#subversion Have fun, Stefan From rene at korteklippe.de Mon Jun 11 09:02:13 2007 From: rene at korteklippe.de (=?UTF-8?B?UmVuw6kgRmxlc2NoZW5iZXJn?=) Date: Mon, 11 Jun 2007 15:02:13 +0200 Subject: How to get inputs for a python program that run from another python program In-Reply-To: <1181558827.965555.280600@r19g2000prf.googlegroups.com> References: <1181558827.965555.280600@r19g2000prf.googlegroups.com> Message-ID: <466d47d3$0$10191$9b4e6d93@newsspool4.arcor-online.net> Hi pradeep nair schrieb: > now wen i run hello1.py,i want the some function or utility in > hello1.py that can pass the keyboard i/p to hello.py . Have a look at subprocess.Popen http://docs.python.org/lib/module-subprocess.html -- Ren? From devicerandom at gmail.com Thu Jun 28 06:24:48 2007 From: devicerandom at gmail.com (massimo s.) Date: Thu, 28 Jun 2007 03:24:48 -0700 Subject: problem with hack using multiple inheritance for plugins Message-ID: <1183026288.857294.91620@q69g2000hsb.googlegroups.com> Before all, I'm not a professional programmer but just a biophysics ph.d. student, so if something makes you scream of horror, please forgive me... Ok, this is not straightforward at all. I am working on an application that uses plugins. Plugins are coded as small classes that become inherited by a main class ( a cmd.Cmd actually) in the following way: (see also this thread: http://groups.google.it/group/comp.lang.python/browse_thread/thread/4d6da027bb9249bd/0f95c60add4ef5ad ) --- ... def do_this(self, arg): ... print "THIS", arg ... >>> class Bar: ... def do_that(self, arg): ... print "THAT", arg ... >>> plugins = [Foo, Bar] >>> def make_command_class(*bases): ... return type(cmd.Cmd)("MyCli", bases + (cmd.Cmd,), {}) ... >>> cmd = make_command_class(*plugins)() >>> cmd.cmdloop() (Cmd) help Undocumented commands: ====================== help that this (Cmd) that one THAT one (Cmd) ----------- And it works. Now I'm trying to do the same trick for another base class, this time a WxPython frame. Also in this case, "plugging" seem to work, but with an important difference. In the command line plugin API, I define a _plug_init() method that is called in the main class __init__ . This for adding plugin-specific initializiations. That's what I do in the command line __init__: for plugin_name in self.config['plugins']: try: plugin=__import__(plugin_name) try: print type(self) eval('plugin.'+plugin_name +'Commands._plug_init(self)') except AttributeError: pass except ImportError: pass And it works flawlessly. Problem is, the exact same code when done using the wxFrame as the baseclass, doesn't work: #make sure we execute _plug_init() for every command line plugin we import for plugin_name in config['plugins']: try: plugin=__import__(plugin_name) try: print type(self) eval('plugin.'+plugin_name +'Gui._plug_init(self)') pass except AttributeError: pass except ImportError: pass with the following error: Traceback (most recent call last): File "hooke.py", line 801, in main() File "hooke.py", line 787, in main main_frame = make_gui_class(*GUI_PLUGINS)(None, -1, ('Hooke '+__version__)) File "hooke.py", line 308, in __init__ eval('plugin.'+plugin_name+'Gui._plug_init(self)') File "", line 1, in TypeError: unbound method _plug_init() must be called with dummyguiplugGui instance as first argument (got MainWindowPlugged instance instead) The problem seems to be that if I call type(self) before doing the eval('plugin... ) line: - in the working case, I get type - in the not working case, I get At this point, it seems too much a deep object-oriented hell to be able to dig it myself. Would you help me getting some cue on the problem? m. From nick at craig-wood.com Wed Jun 20 04:30:03 2007 From: nick at craig-wood.com (Nick Craig-Wood) Date: Wed, 20 Jun 2007 03:30:03 -0500 Subject: Python/C API bug (multithreading) References: Message-ID: Krzysztof W?odarczyk wrote: > I think I've found a bug in Python/C API and multithreading. You don't state your python version. There is an old bug about a similar issue :- http://mail.python.org/pipermail/python-dev/2005-May/053840.html http://sourceforge.net/tracker/index.php?func=detail&aid=1163563&group_id=5470&atid=105470 > Is there any simple way to fix this damned bug?? Locking, locking and more locking ;-) -- Nick Craig-Wood -- http://www.craig-wood.com/nick From warren at muse.com Sat Jun 9 18:22:51 2007 From: warren at muse.com (Warren Stringer) Date: Sat, 9 Jun 2007 15:22:51 -0700 Subject: Hooking exceptions outside of call stack In-Reply-To: <20070609213157.30678.763231875.divmod.quotient.13265@ohm> References: <002c01c7aad8$12963440$240110ac@Muse> <20070609213157.30678.763231875.divmod.quotient.13265@ohm> Message-ID: <002d01c7aae4$b7f2b330$240110ac@Muse> > Yes. Python doesn't have restartable exceptions. Perhaps you would like > to take a look at CL or Smalltalk? > > Jean-Paul Hmmm, I wonder if anyone suggest to Philippe Petit, as stepped out 110 stories off the ground, that perhaps he would like to take a look at a different tightrope? Oddly enough, you suggestion regarding "restartable exceptions" turn up a solution: http://www.chneukirchen.org/blog/archive/2005/03/restartable-exceptions.html Oops, wrong language. \~/ From hari.siri74 at gmail.com Thu Jun 21 21:16:59 2007 From: hari.siri74 at gmail.com (hari sirigibathina) Date: Thu, 21 Jun 2007 20:16:59 -0500 Subject: variable sub in a list- how to Message-ID: D- How can I substitute a variable into a list ? ex: list() var = 'Prog' list.append($Prog) //error occur here -- Warm Regards, Hari -------------- next part -------------- An HTML attachment was scrubbed... URL: From tjreedy at udel.edu Sun Jun 3 13:13:44 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 3 Jun 2007 13:13:44 -0400 Subject: Python 2.5.1 broken os.stat module References: <466140A6.1090100@v.loewis.de><-aOdnbFdroD_gP_bnZ2dnUVZ_uKknZ2d@comcast.com><4662750b$0$29898$9b622d9e@news.freenet.de> Message-ID: "Joe Salmeri" wrote in message news:NYWdnUCXk6mPUv_bnZ2dnUVZ_jKdnZ2d at comcast.com... | ""Martin v. L?wis"" wrote in message | news:4662750b$0$29898$9b622d9e at news.freenet.de... | >> The short explaination of this issue is that the timestamp shown when | >> you do a dir on a file that is on an NTFS volume changes by an hour | >> when DST starts and also when DST ends, even though the file has NOT | >> been modified!!! Note that this only happens if you have the setting | >> turned on to automatically adjust for DST (this is the default in | >> Windows). | > | > You are misinterpreting what you are seeing. Windows is not claiming | > that the modification time changes when DST starts. Instead, it is | > claiming that the *same* time now has a *different* textual | > representation, because the computer now has moved to a different | > time zone. Joe, read the last sentence again. Most of your reply shows that you have missed this basic point. A 'time zone', as far as the math (and Windows) is concerned, *IS* an offset from GMT. The shift from 'standard' to 'daylight' time is a one-hour change in the offset. That has the same effect as moving to the standard time zone one hour to the east. So Eastern Daylight Time is the same as Atlantic Standard Time (or whatever Canadians call the next zone for their maritime provinces). Similarly, 'Central Daylight Time' is an alias for 'Eastern Standard Time'. CDT and EST both translate to -5 (I believe) in Windows timezone lookup dictionary. Because there are multiple names and abbreviations for most or all timezones, Windows has to separately keep track of which one the user expects to see. [In my opinion, the Congressional mandate that we pretend to live somewhere to the east for over half the year is as arrogant and stupid as would be a mandate that we use 'adjusted Fahrenheit' (F - 10 degrees) during the summer so that temperatures 'seemed' lower. ;-] | > When you explicitly change the time zone of your computer, you will | > notice that all file time stamps immediately change also. What Martin meant, of course, is the presented text representation thereof. | It appears that you may have missed part of my tests. Sorry it was such a | long reply but I was trying to provide a lot of detail so that others had a | clear understanding of what was going on. | | I understand that the actual UTC time value for the file has *not* changed. | | That local textual representation of the modification timestamp is what | people and programs look at and work with and is what is displayed by the | dir command and what Explorer displays. And without a timezone attached, that 'local representation' is as ambiguous as any measurement without units. Is 45 hot or cool? | Changing the timezone will defintely change the "textual representation" of | all timestamps just as you say (even though the actual UTC value has *not* | changed), however, when DST starts/ends the "textual representation" of the | timestamps on some files WILL ALSO CHANGE when the automatically adjust for | DST setting is turned on. To repeat, turning DST on *IS* a timezone change. So you are talking about the *same* thing. | In the following comments I am referring to the textual representation of | the timestamp that the user is working with (I understand that the interal | UTC timestamp for the file has *not* changed). | | The issue occurs when the timestamp for the file is in a period when DST was | not in effect and DST is in effect for the current time OR when the | timestamp for the file is in a period when DST was in effect and DST is not | in effect for the current time. Because the timezones change. Geographically, UTC+X is the area where the relevant authorities mandate that clocks be set to offset X from UTC. When the clocks jump, those areas jump! In the US, at least, the UTC-6 area, for instance, jumps from where it was to what was previously the UTC-7 area. This spring, when there were different jump dates around the world, the overall configuration of zones (which areas had the same time) changed. Yes, a mess | While it is true that I did change the timezone in the first part of the | test (to establish the baseline), in the second part of the tests where the | difference you are referring to occured, the timezone was *not* changed, the | only thng that occured was that DST started. Which *is* a timezone change. | In that test the file had a timestamp of 01/01/2007 07:00 PM as shown by the | dir command results. As Martin said, that is not a timestamp. It is an information-stripped representation thereof. | When the date progressed to a point after DST had started Windows now | reports the timestamp on that *unmodified* file now is 01/01/2007 08:00 PM. Because Windows changed the timezone offset by one hour. Again, not a timestamp but an alternate info-deleted representation thereof. | I did not change the timezone, the only thing that occurred was DST started. Which *is* a timezone change. | The internal UTC timestamp did NOT change, the issue is in Windows textual | representation of that UTC timestamp to my local timezone and DST values, | Windows now reports that the modification timestamp on the file as 1 hour | later (again the actual UTC timestamp did *not* change). It is Windows' fault that it deletes the time scale indication. If there were a 'Congressional Stupidty' temperature scale (F-10) and Windows silently changed the scale for reporting historical temperature stamps (perhaps of max CPU temp each your, auto recorded on machines with such measurements), it would 'report' that such had changed, even thought they had not. | > That's because the user is misinterpreting the data that Windows | > reports. Windows isn't saying the file changed, Windows says that | > the timezone changed. | | You mixed up my tests, in that case as shown above the timezone did *not* | change, the only thing that changed was that DST started and the file was | created during a time when DST was not in effect. Need I repeat ;-? Terry Jan Reedy From claird at lairds.us Fri Jun 1 18:16:58 2007 From: claird at lairds.us (Cameron Laird) Date: Fri, 1 Jun 2007 22:16:58 +0000 Subject: Updated Jython Bibliography References: <1180731001.992210.125670@u30g2000hsc.googlegroups.com> Message-ID: In article <1180731001.992210.125670 at u30g2000hsc.googlegroups.com>, ed.taekema at gmail.com wrote: >To celebrate jython's recent progress I've updated my Jython >Bibliography to include new resources I've tripped over in the last >little while. Its available here: http://www.fishandcross.com/blog/?p=194 >Please let me know if I've missed anything. > 'Deserves a link from The Jython Wiki . Incidentally, if you want to extend your bibliography back another year, the second page of gushed about JPython back in '98, with another mention in . Notice also the reference to the developer.com item that summer. From adam at volition-inc.com Mon Jun 18 12:41:32 2007 From: adam at volition-inc.com (Adam Pletcher) Date: Mon, 18 Jun 2007 11:41:32 -0500 Subject: copy locked files In-Reply-To: <1182178224.486883.203330@q75g2000hsh.googlegroups.com> References: <1182178224.486883.203330@q75g2000hsh.googlegroups.com> Message-ID: <893A44FF792E904A97B7515CE34191460102D650@volimxs01.thqinc.com> Do you mean files marked in-use by the OS, like DLLs used by an open application? There shouldn't be anything preventing you from copying in-use files, or even read-only files if that's what you meant: import shutil shutil.copy('C:\\my_application\\test.dll', 'C:\\new_folder\\test.dll') Although you can't move or delete an in-use file, AFAIK. - Adam > -----Original Message----- > From: python-list-bounces+adam=volition-inc.com at python.org > [mailto:python-list-bounces+adam=volition-inc.com at python.org] > On Behalf Of rubbishemail at web.de > Sent: Monday, June 18, 2007 9:50 AM > To: python-list at python.org > Subject: copy locked files > > Hello, > > do you know of any way to copy locked / opened files under win xp? > I know there is something like "Volume Shadow Copy" but I > don't know how to use it. > Maybe someone already has a python solution? > > > Many thanks > > > Daniel > > -- > http://mail.python.org/mailman/listinfo/python-list > From rubbishemail at web.de Mon Jun 18 13:05:56 2007 From: rubbishemail at web.de (rubbishemail at web.de) Date: Mon, 18 Jun 2007 10:05:56 -0700 Subject: copy locked files In-Reply-To: References: <1182178224.486883.203330@q75g2000hsh.googlegroups.com> Message-ID: <1182186356.755892.177700@m36g2000hse.googlegroups.com> Hi Adam, On 18 Jun., 18:41, "Adam Pletcher" wrote: > Do you mean files marked in-use by the OS, like DLLs used by an open > application? I dont know the exact name, but some programs totally lock the files, like Visual Studio shutil.copy('C:\\a\\test\\test.ncb','C:\\b\test.ncb') IOError: [Errno 13] Permission denied: 'C:\\a\\test\\test.ncb' As soon as I quit the application I can copy the file. (I am writing a backup software which saves the changed files every few minutes. If there was a slight possibility to copy a file which is written at the same moment and therefore not consistent this is still better than no backup) > > There shouldn't be anything preventing you from copying in-use files, or > even read-only files if that's what you meant: That's exactly my opinion! > > Although you can't move or delete an in-use file, AFAIK. this seems to be easier, you can use inuse.exe http://support.microsoft.com/kb/228930/en-us Daniel From claird at lairds.us Sat Jun 30 21:00:54 2007 From: claird at lairds.us (Cameron Laird) Date: Sun, 1 Jul 2007 01:00:54 +0000 Subject: Reading image dimensions before it is loaded from a web form using python. References: <46869EE1.4020608@khine.net> Message-ID: <6vajl4-vf.ln1@lairds.us> In article , Evan Klitzke wrote: >On 6/30/07, Norman Khine wrote: >> Hello, >> I am writing an application using python that allows the user to upload >> an image to a folder on the server. >> >> Is there a way to get the size of the file before it has been uploaded >> onto the server and give an error if the size does not comply to the >> maximum size. > >The easiest way to do this is to simply restrict the maximum file >upload size. When the client makes the POST request you can see how >big it will be. This won't really give you the image dimensions of >course, but there's no simple way to find out that information without >uploading the entire image. . . . Maybe we disagree about "simple", but there *are* definite ways to do so. It's a bit involved--I fear that when Mr. Khine writes "image", he might have in mind not just .gif, .jpg, and .png, but perhaps also SVG, Flash, PDF, ...--but, yes, it's possible with most image formats to upload just a small portion of the header and test whether what follows meets the size requirements. From bdelmee at advalvas._REMOVEME_.be Sun Jun 24 18:14:49 2007 From: bdelmee at advalvas._REMOVEME_.be (=?ISO-8859-1?Q?Bernard_Delm=E9e?=) Date: Mon, 25 Jun 2007 00:14:49 +0200 Subject: cx_oracle In-Reply-To: References: Message-ID: Hi Lukas, you will need a working oracle OCI client middleware before cx_oracle can talk to your database. The easiest nowadays is the so-called instant client, which must be available from the otn.oracle.com site (downloads might require a free registration). Try to get sql*plus working (the standard Oracle command-line client), and cx should then pose no problem. Cheers, Bernard. From lobais at gmail.com Tue Jun 5 07:58:46 2007 From: lobais at gmail.com (Thomas Dybdahl Ahle) Date: Tue, 05 Jun 2007 13:58:46 +0200 Subject: subprocess leaves child living Message-ID: Hi, When I do a small program like from subprocess import Popen popen = Popen(["ping", "google.com"]) from time import sleep sleep(100) start it and kill it, the ping process lives on. Is there a way to ensure that the ping process is always killed when the python process is? I can't use atexit, as ping then isn't killed when python is killed "in the hard way" From hat at se-162.se.wtb.tue.nl Thu Jun 28 10:38:56 2007 From: hat at se-162.se.wtb.tue.nl (A.T.Hofkamp) Date: Thu, 28 Jun 2007 16:38:56 +0200 Subject: equality & comparison by default (was Re: Too many 'self' in python.That's a big flaw in this language.) References: <1182942154.185461.89620@e9g2000prf.googlegroups.com> <1i0cy8z.z94q5d1dxgexxN%aleax@mac.com> Message-ID: On 2007-06-28, Alan Isaac wrote: > A.T.Hofkamp wrote: > >>>>>a = Car2(123) >>>>>b = Car2(123) >>>>>a == b >> >> True >> >>>>>set([a,b]) >> >> set([Car2(123), Car2(123)]) >> >> I get a set with two equal cars, something that never happens with a set >> my math teacher once told me. > > > Then your math teacher misspoke. > You have two different cars in the set, > just as expected. Use `is`. > http://docs.python.org/ref/comparisons.html > > This is good behavior. Hmm, maybe numbers in sets are broken then? >>> a = 12345 >>> b = 12345 >>> a == b True >>> a is b False >>> set([a,b]) set([12345]) Numbers and my Car2 objects behave the same w.r.t. '==' and 'is', yet I get a set with 1 number, and a set with 2 cars. Something is wrong here imho. The point I intended to make was that having a default __hash__ method on objects give weird results that not everybody may be aware of. In addition, to get useful behavior of objects in sets one should override __hash__ anyway, so what is the point of having a default object.__hash__ ? The "one should override __hash__ anyway" argument is being discussed in my previous post. Albert From keramida at ceid.upatras.gr Mon Jun 25 14:28:22 2007 From: keramida at ceid.upatras.gr (Giorgos Keramidas) Date: Mon, 25 Jun 2007 21:28:22 +0300 Subject: The Modernization of Emacs: terminology buffer and keybinding References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182272495.990807.99110@a26g2000pre.googlegroups.com> <87tzt3ihev.fsf@kobe.laptop> <1182370216.961241.6960@n60g2000hse.googlegroups.com> <85zm2ufjpb.fsf@lola.goethe.zz> <1182372592.803332.288260@u2g2000hsc.googlegroups.com> <1182549094.366282.286740@m37g2000prh.googlegroups.com> Message-ID: <877iprhos9.fsf@kobe.laptop> On Fri, 22 Jun 2007 21:51:34 -0000, Twisted wrote: >> C-h i, C-x b RET is non-trivial?!? [...] > I'm sorry. I don't speak Chinese. > > I trust I've made my point. Not only does it insist you learn a whole > other language (though I'm guessing it's not actually Chinese -- > Greek, maybe), even when you know that's a bunch of keystrokes and > even what they are... > > HOW IN THE BLOODY HELL IS IT SUPPOSED TO OCCUR TO SOMEONE TO ENTER > THEM, GIVEN THAT THEY HAVE TO DO SO TO REACH THE HELP THAT WOULD TELL > THEM THOSE ARE THE KEYS TO REACH THE HELP?! No it's not Greek. I can assure you it isn't, because I *am* Greek. Now, regarding your shouting about the keys, have you tried using a recent GNU Emacs installation? The first thing that pops up when a new user runs Emacs looks like this: ,----------------------------------------------------------------------- | Welcome to GNU Emacs, a part of the GNU operating system. | | Type C-l to begin editing. | | Get help C-h (Hold down CTRL and press h) | Emacs manual C-h r | Emacs tutorial C-h t Undo changes C-x u | Buy manuals C-h C-m Exit Emacs C-x C-c | Browse manuals C-h i | Activate menubar F10 or ESC ` or M-` | (`C-' means use the CTRL key. `M-' means use the Meta (or Alt) key. | If you have no Meta key, you may instead type ESC followed by the character.) | | GNU Emacs 22.1.50.2 (i386-unknown-freebsd7.0, X toolkit) | of 2007-05-29 on kobe | Copyright (C) 2007 Free Software Foundation, Inc. | | GNU Emacs comes with ABSOLUTELY NO WARRANTY; type C-h C-w for full details. | Emacs is Free Software--Free as in Freedom--so you can redistribute copies | of Emacs and modify it; type C-h C-c to see the conditions. | Type C-h C-d for information on getting the latest version. `----------------------------------------------------------------------- Basic reading skills are necessary to parse this 'splash' screen, but it shouldn't be too hard to read a few lines of text which guide you about the proper key sequence to reach the tutorial, right? > Of course, Notepad is so easy to use it doesn't even need help, > despite which it's readily available. In case you forgot the bog- > standard (and therefore it IS self-evident) "F1" there's even a "Help" > menu in plain view as soon as you open a Notepad. There's also a "Help" menu in plain sight when you fire up Emacs with an X11 interface. I don't see why Notepad is special in any way here. > This is the lowly Notepad, which I'll freely admit is the rusty > bicycle of text editors, and it's much easier to use (including the > help) than the supposed Mercedes-Benz of editors. Isn't this always the case? The 'interface' of a tiny bicycle is something which even very young kids can master pretty fast. On the other hand, I'm relatively sure there's at least one valid reason we don't let pre-school aged children drive around Mercedes-Benz cars, isn't there? From spe.stani.be at gmail.com Sat Jun 2 07:40:37 2007 From: spe.stani.be at gmail.com (SPE - Stani's Python Editor) Date: Sat, 02 Jun 2007 04:40:37 -0700 Subject: Creating a distro of python... What would you include in it? In-Reply-To: <1180547257.472087.198630@p77g2000hsh.googlegroups.com> References: <1180538748.448426.182820@g4g2000hsf.googlegroups.com> <1180547257.472087.198630@p77g2000hsh.googlegroups.com> Message-ID: <1180784437.315996.245550@h2g2000hsg.googlegroups.com> On May 30, 7:47 pm, yuce wrote: > re: BJ?rn, I think selecting a GPL license will increase the number of > usable packages, since using Python license with GPL is perfectly fine > as long as the whole software is licensed under GPL [I am not really > sure it is a must to license the whole package under GPL] > > re: farksimm; I'd put (in nor particular order) > > - Python Imaging Library :http://www.pythonware.com/products/pil/ > > -wxPython:http://www.wxpython.org/ > > - ipython :http://ipython.scipy.org/moin/ > > - pycrypto :http://www.amk.ca/python/code/crypto > > - sqlalchemy :http://www.sqlalchemy.org/ > > - psycopg :http://www.initd.org/tracker/psycopg > > - docutils :http://docutils.sourceforge.net/ > > - NumPy/Numeric :http://numpy.scipy.org/ > > - if it's for Win32 also pywin32 :http://www.python.net/crew/mhammond/win32/ > > Yuce Feel free to include SPE. Stani -- http://pythonide.stani.be From tcrane at REMOVETHISuiuc.edu Tue Jun 12 09:42:41 2007 From: tcrane at REMOVETHISuiuc.edu (T. Crane) Date: Tue, 12 Jun 2007 08:42:41 -0500 Subject: file open default location Message-ID: Hi, How is the default path chosen in this instance: myFile = file('test.txt','w') Here I'm opening/creating a file but I have not specified the exact path, so how does Python determine where to 'put' this file? More to the point, how do I change what the default path is? Right now it's a networked drive that should not be getting my Python clutter. Interestingly, this network drive is also where I can find my _ipython folder from my ipython install as well as my .matplotlib folder. Can anyone tell me how to change where these folders and files go by default? thanks for any help, trevis From x31equsenet at gmail.com Thu Jun 28 01:20:17 2007 From: x31equsenet at gmail.com (Graham Breed) Date: Wed, 27 Jun 2007 22:20:17 -0700 Subject: Python's "only one way to do it" philosophy isn't good? References: <1182750077.570603.160240@q69g2000hsb.googlegroups.com> <7xir9cbm0g.fsf@ruckus.brouhaha.com> <7xejjzmk7u.fsf@ruckus.brouhaha.com> <7xy7i7xjl5.fsf@ruckus.brouhaha.com> <7x4pkt4xuz.fsf@ruckus.brouhaha.com> Message-ID: <1183008017.909963.314280@o11g2000prd.googlegroups.com> Dennis Lee Bieber wote: > But if these "macros" are supposed to allow one to sort of extend > Python syntax, are you really going to code things like > > macrolib1.keyword > > everywhere? I don't see why that *shouldn't* work. Or "from macrolib1 import keyword as foo". And to be truly Pythonic the keywords would have to be scoped like normal Python variables. One problem is that such a system wouldn't be able to redefine existing keywords. Lets wait for a concrete proposal before delving into this rats' cauldron any further. Graham From gagsl-py2 at yahoo.com.ar Fri Jun 22 23:26:11 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 23 Jun 2007 00:26:11 -0300 Subject: Internationalised email subjects References: <1182337500.638044.63470@e9g2000prf.googlegroups.com> <46791592$0$5719$edfadb0f@dread14.news.tele.dk> <1182346499.123234.279880@e9g2000prf.googlegroups.com> <1182417604.446766.47660@e9g2000prf.googlegroups.com> <1182417823.793678.323530@a26g2000pre.googlegroups.com> <467B5D56.7060208@v.loewis.de> <1182496538.387301.122670@i38g2000prf.googlegroups.com> <1182505762.845544.314940@e9g2000prf.googlegroups.com> Message-ID: En Fri, 22 Jun 2007 06:49:22 -0300, escribi?: > I've tried removing the encode('GB2312') line, so the code looks like > this: > > h = Header(subject, 'GB2312') > > However, this line still causes the following error message: > > Traceback (most recent call last): > File "/home/web88/html/app/sendmail.py", line 314, in > h = Header(subject, 'GB2312') > File "/usr/lib/python2.2/email/Header.py", line 188, in __init__ > self.append(s, charset, errors) > File "/usr/lib/python2.2/email/Header.py", line 272, in append > ustr = unicode(s, incodec, errors) > LookupError: unknown encoding: gb2312 ) It appears that you don't have the gb2312 codec - maybe it was not available with your rather old Python version (2.2). Upgrading to a newer version may help. -- Gabriel Genellina From bj_666 at gmx.net Fri Jun 22 04:09:37 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Fri, 22 Jun 2007 10:09:37 +0200 Subject: configparser shuffles all sections ? References: Message-ID: In , stef wrote: > I just used configparser for the first time and discovered that it > shuffled all my sections, and the contents of the sections too. The data is stored in dictionaries. > This makes human manipulation of the file impossible. Why so? Ciao, Marc 'BlackJack' Rintsch From borud-news at borud.no Wed Jun 27 06:31:28 2007 From: borud-news at borud.no (Bjorn Borud) Date: 27 Jun 2007 12:31:28 +0200 Subject: The Modernization of Emacs: terminology buffer and keybinding References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182272495.990807.99110@a26g2000pre.googlegroups.com> <87tzt3ihev.fsf@kobe.laptop> <1182370216.961241.6960@n60g2000hse.googlegroups.com> <85zm2ufjpb.fsf@lola.goethe.zz> <1182372592.803332.288260@u2g2000hsc.googlegroups.com> <1182373919.262388.100740@c77g2000hse.googlegroups.com> <85r6o6fhkb.fsf@lola.goethe.zz> <1182375045.626510.188170@m36g2000hse.googlegroups.com> <1182546050.465987.115740@q19g2000prn.googlegroups.com> <871wg3k8c8.fsf@thalassa.lan.informatimago.com> <1182546979.295368.146110@q19g2000prn.googlegroups.com> <87wsxviqol.fsf@thalassa.lan.informatimago.com> <1182552172.406571.116390@i38g2000prf.googlegroups.com> Message-ID: ["Kjetil S. Matheussen" ] | | Did you expect something specific before starting to read that book? | Thats a failure. SICP is a book you should read just for pure | pleasure. I was told by a lot of people I consider to be intelligent that this book would change how I think about writing software. it didn't. I didn't really know what to expect, but after reading it I did feel that its importance was greatly exaggerated. | > these people seemed to be | > completely disconnected from reality. | | Please don't write things like that without backing it up with some | reason. well, for one, Scheme lacked proper libraries for doing everyday things, so when I tried to use it I found myself writing a lot of library code that I shouldn't have had to deal with. but it is quite long ago, so things might have changed since then. -Bj?rn From len-l at telus.net Tue Jun 5 14:08:31 2007 From: len-l at telus.net (Lenard Lindstrom) Date: Tue, 05 Jun 2007 18:08:31 GMT Subject: magic names in python In-Reply-To: References: <1180939436.862957.127810@p77g2000hsh.googlegroups.com> Message-ID: Steven D'Aprano wrote: > On Mon, 04 Jun 2007 22:19:35 +0000, Lenard Lindstrom wrote: > >> What is "magic" about __init__ and __repr__? They are identifiers just >> like "foo" or "JustAnotherClass". They have no special meaning to the >> Python compiler. The leading and trailing double underscores represent >> no special incantation. It is just a naming convention. > > That's not quite true, as you point out: Disassemble the code object of a class statement. "__init__" is just an identifier, a Python name. So there is no "magic" here. > >> So a number of method names like __init__ and __repr__ have a >> pre-defined usage. > > That makes them magic, in the best possible way. I was careful to use the word "usage". Maybe I should have used "protocol" or "specification" here. A method named "write" is understood to have a particular definition and purpose. Is it "magic"? These methods are simply callbacks. And yes, these callbacks make Python flexible. > > >> In every other respect they are just normal methods. > > That is *almost* true. Or, to put it another way, that is wrong. Some of > the double-underscore magic methods are automatically called on the class > instead of the instance, bypassing normal inheritance. > They exist as Python functions in the class dictionary. They have no hidden flags that distinguish them from other class level function attributes. > >>>> import new >>>> class Test(object): > .... def foo(self): > .... return "foo called from the class" > .... def __str__(self): > .... return "__str__ called from the class" > .... >>>> obj = Test() >>>> obj.foo() > 'foo called from the class' >>>> str(obj) # calls obj.__str__ > '__str__ called from the class' > > Now see what happens when we add methods to the instance. > >>>> obj.foo = new.instancemethod( > .... lambda self: "foo called from the instance", obj, Test) >>>> obj.foo() > 'foo called from the instance' >>>> obj.__class__.foo(obj) # Check the method in the class is still there. > 'foo called from the class' > > So calling a random method like foo() goes through the usual procedure: > check the instance, then check the class. Now let's try it with a magic > method. > > >>>> obj.__str__ = new.instancemethod( > .... lambda self: "__str__ called from the instance", obj, Test) >>>> obj.__str__() > '__str__ called from the instance' >>>> str(obj) # calls obj.__str__() maybe? > '__str__ called from the class' > Yes, method lookup for an operation differs from attribute lookup in new-style classes. But it is a property of new-style classes, not the methods themselves. For instance, classic classes behave differently: >>> class Test: def __str__(self): return "__str__ called from the class" >>> obj = Test() >>> obj.__str__() '__str__ called from the class' >>> str(obj) '__str__ called from the class' >>> obj.__str__ = new.instancemethod( lambda self: "__str__ called from the instance", obj, Test) >>> str(obj) '__str__ called from the instance' >>> obj.__class__.__str__(obj) '__str__ called from the class' I do admit that the special methods are given special treatment by the type and ClassType types to ensure they are called by their corresponding operations. But this special treatment is restricted to the types themselves. In CPython an extension type can be written from scratch that treats special methods exactly as a new-style class does. Or an extension type can implement a completely novel approach. The point is, at some level, the machinery which defines special method "magic" is accessible to the programmer. So is it really "magic" or advanced technology? This comes down to the original posting not defining a "magic name". It does not mention what is so objectionable about __init__ and __repr__. I am claiming they are not as "magical" as they may first appear. -- Lenard Lindstrom From per9000 at gmail.com Mon Jun 4 02:43:56 2007 From: per9000 at gmail.com (per9000) Date: Mon, 04 Jun 2007 06:43:56 -0000 Subject: magic names in python Message-ID: <1180939436.862957.127810@p77g2000hsh.googlegroups.com> Hi, I recently started working a lot more in python than I have done in the past. And I discovered something that totally removed the pretty pink clouds of beautifulness that had surrounded my previous python experiences: magic names (I felt almost as sad as when I discovered the strange pink worms that eat you in nethack, not to mention the mind flayers - I really hate them). I guess all programming languages have magic names to some extent (f.x. classes in the "C-family" have constructors that must have the same name as the class (foo::foo) instead of foo.__init__). I just used a search engine a little on this topic and I found no comprehensive list of magic names in python. So my questions: * is there a comprehensive list of magic names in python (so far i know of __init__ and __repr__)? * are these lists complete or can magic names be added over time (to the python "core")? * are magic names the same in different python versions? I also tried (selected parts of(?)) the unittest package for use in Zope and it seemed functions that I created for my test with the magic prefix "test" were magic, other functions were not. So another question emerges: * is the use of magic names encouraged and/or part of good coding practice. Live long and prosper, Per -- Per Erik Strandberg home: www.pererikstrandberg.se work: www.incf.org also: www.spongswedencare.se From nospam at no.spam Wed Jun 13 06:12:14 2007 From: nospam at no.spam (=?ISO-8859-1?Q?Markus_Sch=F6pflin?=) Date: Wed, 13 Jun 2007 12:12:14 +0200 Subject: cStringIO change in 2.4 vs 2.5. Regression? In-Reply-To: References: Message-ID: Markus Sch?pflin wrote: [...] > I think I'll file a bug at SF... maybe someone else will spot something. Should have checked the bugtracker first... it was reported the day after my original post: http://sourceforge.net/tracker/index.php?func=detail&aid=1730114&group_id=5470&atid=105470 And it's a 2.5.1 regression, it does work in 2.5. Markus From orsenthil at users.sourceforge.net Wed Jun 27 00:35:27 2007 From: orsenthil at users.sourceforge.net (O.R.Senthil Kumaran) Date: Wed, 27 Jun 2007 10:05:27 +0530 Subject: New Thread- Supporting Multiline values in ConfigParser In-Reply-To: References: <1182780364.650693.10430@w5g2000hsg.googlegroups.com> Message-ID: <20070627043527.GB3539@gmail.com> * Gabriel Genellina [2007-06-25 22:26:47]: > And how would you detect a multiline value? > Because it is not a section nor looks like a new option? > > > I can guess, this portion in the _read function will require change, > > any change to this affects the whole of parsing. :-( Can someone who > > has done this before or understands ConfigParser better help me? > > > > # Section I am talking about > > if line[0].isspace() and cursect is not None > > and optname: > > > > value = line.strip() > > if value: > > cursect[optname] = "%s\n%s" % > > (cursect[optname], value) > > Yes, I guess so. > I'd try using this: > > if not self.SECTCRE.match(line) and not self.OPTCRE.match(line) and > cursect is not None and optname: > Thanks Gabriel, this suggestion worked and helped me understand the ConfigParser a bit better as well. -- O.R.Senthil Kumaran http://uthcode.sarovar.org From bjorns at gmail.com Mon Jun 11 19:33:56 2007 From: bjorns at gmail.com (Beorn) Date: Mon, 11 Jun 2007 16:33:56 -0700 Subject: A gotcha: Python pain point? Message-ID: <1181604836.292323.154510@z28g2000prd.googlegroups.com> Consider this example: >>> def funcs(x): ... for i in range(5): ... def g(): return x + i ... yield g I would expect the value of x used in g to be that at the function declaration time, as if you've pass g a (x=x) argument, especially after reading this post: http://lua-users.org/wiki/LuaScopingDiscussion But: >>> [ fun() for fun in list(funcs(1)) ] [5, 5, 5, 5, 5] Whereas: >>> [ fun() for fun in funcs(1) ] [1, 2, 3, 4, 5] This came up while discussing Python pain points at http://intertwingly.net/blog/2007/06/04/Python-Pain-Points#c1181602242 I can see how it works now, but I haven't found an easy-to-read documentation on this. I guess it's debatable if perhaps every i used in the loop shouldn't be a different i. It had me fooled, anyways. Rgds, Bjorn From michele.simionato at gmail.com Fri Jun 29 02:23:48 2007 From: michele.simionato at gmail.com (Michele Simionato) Date: Fri, 29 Jun 2007 06:23:48 -0000 Subject: Python's "only one way to do it" philosophy isn't good? In-Reply-To: References: <7xejjzmk7u.fsf@ruckus.brouhaha.com> <7xy7i7xjl5.fsf@ruckus.brouhaha.com> Message-ID: <1183098228.517915.12140@q75g2000hsh.googlegroups.com> On Jun 29, 6:44 am, Douglas Alan wrote: > > I've written plenty of Python code that relied on destructors to > deallocate resources, and the code always worked. You have been lucky: $ cat deallocating.py import logging class C(object): def __init__(self): logging.warn('Allocating resource ...') def __del__(self): logging.warn('De-allocating resource ...') print 'THIS IS NEVER REACHED!' if __name__ == '__main__': c = C() $ python deallocating.py WARNING:root:Allocating resource ... Exception exceptions.AttributeError: "'NoneType' object has no attribute 'warn'" in > ignored Just because your experience has been positive, you should not dismiss the opinion who have clearly more experience than you on the subtilities of Python. Michele From mailmaverick666 at gmail.com Wed Jun 20 00:38:31 2007 From: mailmaverick666 at gmail.com (rishi pathak) Date: Wed, 20 Jun 2007 10:08:31 +0530 Subject: Execute script on remote computer In-Reply-To: <0B5158DBDB894441A80F5928175235330589F243@postoffice.cybage.com> References: <0B5158DBDB894441A80F5928175235330589F243@postoffice.cybage.com> Message-ID: <180b672e0706192138h75c23a26g2f51d4b4870c9560@mail.gmail.com> Does the script resides on the remote machine or do we have to transfer the script to the remote machine.If remote and agent machine are linux then you can use rsh/ssh to do so. On 6/19/07, Vikas Saini wrote: > > I am trying to run the agent on one machine that will execute the script > of a remote machine. > > Could you please help me in this regards. > > > > vikas > > > "Legal Disclaimer: This electronic message and all contents contain > information from Cybage Software Private Limited which may be privileged, > confidential, or otherwise protected from disclosure. The information is > intended to be for the addressee(s) only. If you are not an addressee, any > disclosure, copy, distribution, or use of the contents of this message is > strictly prohibited. If you have received this electronic message in error > please notify the sender by reply e-mail to and destroy the original message > and all copies. Cybage has taken every reasonable precaution to minimize the > risk of malicious content in the mail, but is not liable for any damage you > may sustain as a result of any malicious content in this e-mail. You should > carry out your own malicious content checks before opening the e-mail or > attachment." > www.cybage.com > -- > http://mail.python.org/mailman/listinfo/python-list > -- Regards-- Rishi Pathak National PARAM Supercomputing Facility Center for Development of Advanced Computing(C-DAC) Pune University Campus,Ganesh Khind Road Pune-Maharastra -------------- next part -------------- An HTML attachment was scrubbed... URL: From owntheweb at gmail.com Fri Jun 29 15:23:01 2007 From: owntheweb at gmail.com (Ultrus) Date: Fri, 29 Jun 2007 19:23:01 -0000 Subject: Edit Audio Using Python? In-Reply-To: <1182436482.889795.159400@n2g2000hse.googlegroups.com> References: <1182353535.158899.128650@n2g2000hse.googlegroups.com> <1182356488.189503.122180@g4g2000hsf.googlegroups.com> <1182375392.825047.141120@w5g2000hsg.googlegroups.com> <1182436482.889795.159400@n2g2000hse.googlegroups.com> Message-ID: <1183144981.074536.21660@n2g2000hse.googlegroups.com> Thanks to Aaron, I was able to read and write audio data using Python's wave module. Trying to better understand the data I'm looking at, what does each element of the frame represent, and how do I convert a sample ranging from -32,768 to 32,768 back to a frame set like below? When using a 16 bit mono wav file, reading a frame of audio produces 2 numbers like this: import wave file = wave.open("myWave.wav") frame = file.readframes(1) #read first frame file.close #ord(frame[0]) = 0 to 256, ord(frame[1]) = 0 to 256, #possible max of 65,536, or sample with range of -32,768 to 32,768 From nagle at animats.com Wed Jun 27 12:23:45 2007 From: nagle at animats.com (John Nagle) Date: Wed, 27 Jun 2007 16:23:45 GMT Subject: PEP 3107 and stronger typing (note: probably a newbie question) In-Reply-To: References: <1182369568.941307.316260@p77g2000hsh.googlegroups.com> <5dveb4F360un0U1@mid.individual.net> <467a9209$0$22165$426a74cc@news.free.fr> <1182858785.886469.93060@n60g2000hse.googlegroups.com> <46824d8d$0$2324$426a74cc@news.free.fr> <46826e38$0$2818$426a74cc@news.free.fr> Message-ID: Stephen R Laniel wrote: > People on here have been ... ahhh ... *generous* about > explaining that Python is dynamic, and hence that static > typing doesn't make sense. I've got it. That's not really the issue. There are languages with no static typing, like Python, and there are languages with fullly enforced static typing, like Java. Both work. PEP 3107 is static typing without enforcement, which is not a good thing. It's one that's been tried, many times, as coding conventions. Microsoft code from the Windows 3.1 era was heavy on that sort of thing. Remember "Hungarian notation"? "LPSTR"? Yes, that stuff. Moving to C++ and strong typing was generally considered a major improvement in the Windows world. John Nagle From pruyu.chen at gmail.com Tue Jun 12 21:00:26 2007 From: pruyu.chen at gmail.com (Allen) Date: Tue, 12 Jun 2007 18:00:26 -0700 Subject: In C extension .pyd, sizeof INT64 = 4? In-Reply-To: <466efcdf$0$13674$9b622d9e@news.freenet.de> References: <1181642594.963433.132750@g37g2000prf.googlegroups.com> <466efcdf$0$13674$9b622d9e@news.freenet.de> Message-ID: <1181696426.081185.63170@a26g2000pre.googlegroups.com> On 6 13 , 4 06 , "Martin v. Lo"wis" wrote: > Allen schrieb: > > > My C extension works wrong, and debug it, found that sizeof (INT64) = > > 4, not 8. > > I compile on Windows XP platform. > > Please tell me how to fix it to support INT64? > > What *is* INT64? It's not a builtin type of standard C, it isn't > defined by Microsoft C, and it isn't predefined by Python. > > So it must be something that you have defined, and apparently > incorrectly. How did you define it? > > Regards, > Martin Thanks for your reply. I defined in this way: #ifndef WIN32 typedef long long INT64; #else typedef __int64 INT64; #endif I feel it strange that when I use INT64 as local variable, it will run error. When I change the local variable to be static or global, it will be ok. From thorsten at thorstenkampe.de Fri Jun 29 12:09:12 2007 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Fri, 29 Jun 2007 18:09:12 +0200 Subject: Looking for an interpreter that does not request internet access References: Message-ID: * James Alan Farrell (Tue, 26 Jun 2007 01:07:46 GMT) > I recently installed new anti-virus software and was surprised the > next time I brought up IDLE, that it was accessing the internet. > > I dislike software accessing the internet without telling me about it, > especially because of my slow dial up connection (there is no option > where I live), but also because I feel it unsafe. > > Can anyone recommend an interpreter that does not access the internet > when it starts (or when it is running, unless I specifically write a > program that causes it to do so, so as a browser)? Sorry, but this is really ridiculous. When you start Idle it explicitly tells you **************************************************************** Personal firewall software may warn about the connection IDLE makes to its subprocess using this computer's internal loopback interface. This connection is not visible on any external interface and no data is sent to or received from the Internet. **************************************************************** You shouldn't use any kind of software (Antivirus or Personal Firewall) if you have no idea how it's working or can't interpret the messages they give. If your Antivirus really told you that Idle is accessing the "Internet" than uninstall this crap. Thorsten From dborne at gmail.com Mon Jun 18 11:35:00 2007 From: dborne at gmail.com (Dave Borne) Date: Mon, 18 Jun 2007 10:35:00 -0500 Subject: smtp server simulation using Python In-Reply-To: References: Message-ID: <6e42ec490706180835x5e2d115dw206da222106c4882@mail.gmail.com> > I have a (web) development computer w/o an SMTP server and want to test > form generated e-mail using a dummy SMTP server that delivers the mail > message to a file, or better yet, to a text editor instead of actually > sending it. Here's a quick and dirty script I use this for email testing purposes - it's windows specific, but that's easy enough to change. import smtpd, os, time, asyncore class mailserver(smtpd.SMTPServer): def __init__(self): smtpd.SMTPServer.__init__(self, ('',25), None) print 'Mailsink listening on port 25' def process_message(self, peer, mailfrom, rcpttos, data): basepath='c:\\.maildump' print 'mail from: %s to: %s' %(mailfrom, repr(rcpttos)) for rcpt in rcpttos: rcpt = rcpt.split('@')[0] try: os.mkdir(basepath+'\\'+rcpt) except OSError: pass f = file(basepath+'\\'+rcpt+'\\'+mailfrom+time.strftime('%Y%m%d%H%M%S'), 'w') f.write(data) f.close() def loop (): x = mailserver() try: asyncore.loop(timeout=2) except KeyboardInterrupt: print'interrupt' x.close() if __name__=='__main__': loop() From robert.rawlins at thinkbluemedia.co.uk Fri Jun 8 09:44:14 2007 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins - Think Blue) Date: Fri, 8 Jun 2007 14:44:14 +0100 Subject: Binary / SOAPpy Message-ID: <003901c7a9d3$1a2fc3c0$4e8f4b40$@rawlins@thinkbluemedia.co.uk> Hello Guys, I have a WebService call which returns an array, the first element in that array is the binary for a zip file, however I'm having trouble writing that binary string into an actual file when it arrives, I've tried the following method. Result = call to the webservice that returns the array. file = open("Zips/1.zip", "wb") file.write(result[0]) file.close() But this throws the error message: file.write(result[0]) TypeError: argument 1 must be string or read-only buffer, not instance Does anyone know what I might be doing wrong? Once I've resaved this file can then unzip it and get at all its lovely content. Thanks for any input guys, Rob -------------- next part -------------- An HTML attachment was scrubbed... URL: From no_spam at no_spam.com Thu Jun 28 20:02:59 2007 From: no_spam at no_spam.com (James Alan Farrell) Date: Thu, 28 Jun 2007 20:02:59 -0400 Subject: Looking for an interpreter that does not request internet access References: <1182829811.698212.62490@u2g2000hsc.googlegroups.com> Message-ID: On Tue, 26 Jun 2007 03:50:11 -0000, John Roth wrote: >On Jun 25, 7:07 pm, James Alan Farrell wrote: >> Hello, >> I recently installed new anti-virus software and was surprised the >> next time I brought up IDLE, that it was accessing the internet. >> >> I dislike software accessing the internet without telling me about it, >> especially because of my slow dial up connection (there is no option >> where I live), but also because I feel it unsafe. >> >> Can anyone recommend an interpreter that does not access the internet >> when it starts (or when it is running, unless I specifically write a >> program that causes it to do so, so as a browser)? >> >> James Alan Farrell > >One of two things is going on. Either the anti-virus program you >installed is so clueless that it doesn't understand "localhost" or the >IP address equivalent, or IDLE (or it's subprocess) is opening the >socket in promiscuous mode. Either one will give you that symptom. > >There are definitely anti-virus products that are that clueless. >Scream at the vendor. > >I doubt if it's Idle, but I'm not in the mood to check the code to see >if it's doing it right. > >John Roth > > > Thanks to all who answered. The antivirus is McAfee, and I have found it clueless in many ways. Unfortunately the vendor is my place of employment, and if I am to work from home and log into their system, they require me to have it. Otherwise I have to go to the office. Management and IT there might well be clueless but I am new there and don't want to say that yet. From hat at se-126.se.wtb.tue.nl Fri Jun 1 06:44:25 2007 From: hat at se-126.se.wtb.tue.nl (A.T.Hofkamp) Date: Fri, 01 Jun 2007 12:44:25 +0200 Subject: interesting take on python OO References: <1180640052.617845.172400@m36g2000hse.googlegroups.com> <465fcc9d$0$29304$426a34cc@news.free.fr> Message-ID: On 2007-06-01, Bruno Desthuilliers wrote: > > FWIW, I still don't get why people insist on believing that C++ and Java > have anything to do with OO !-) > > (and yes, it's friday...) Good marketing. Albert From fabiofz at gmail.com Wed Jun 20 13:07:40 2007 From: fabiofz at gmail.com (Fabio Zadrozny) Date: Wed, 20 Jun 2007 14:07:40 -0300 Subject: Pydev 1.3.5 Released Message-ID: Hi All, Pydev and Pydev Extensions 1.3.5 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: o Import is now set in correct line even with multi-line imports. o Added option to disable the introduction of auto-imports. o Added option to remove modules that start with '_' from the imports (so, tokens would have to be found in __init__.py files). * Code Analysis: Having a list comprehension with a subscript was not being treated correctly. * Debugger: Working with jython. * Debugger: Working with wxPython. Release Highlights in Pydev: ---------------------------------------------- * Eclipse 3.3 Integration: Does not keep eclipse from a correct shutdown anymore. * Docstrings and code completion pop-up: o The docstrings are now wrapped to the size of the pop-up window. o The initial columns with whitespaces that are common for all the docstring is now removed. o The previous size of the pop-up window in completions is now restored. * Extract method refactoring: was not adding 'if' statement correctly on a specific case. * Organize imports: (Ctrl+Shift+O): comments are not erased in import lines when using it anymore. * Interpreter Config: solved a concurrency issue (which could issue an exception when configuring the interpreter). * Jython integration: can now work with a j9 vm. * Jython integration: those that don't use jython can now use eclipse without JDT (but it's still required for jython development). * Outline: o The comments are now set in the correct level (below module, class or method). o Comments are sorted by their position even when alphabetic sorting is in place. o Comments are added to the outline if they start or end with '---'. 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 -------------- next part -------------- An HTML attachment was scrubbed... URL: From bbxx789_05ss at yahoo.com Tue Jun 26 03:34:54 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: Tue, 26 Jun 2007 00:34:54 -0700 Subject: can't start Apache on Mac OS X--no listening sockets available? In-Reply-To: <1182841462.240341.321340@q69g2000hsb.googlegroups.com> References: <1182824632.015853.317970@g4g2000hsf.googlegroups.com> <1182826067.067254.247940@j4g2000prf.googlegroups.com> <1182838193.195172.206160@u2g2000hsc.googlegroups.com> <1182840123.203387.173210@q75g2000hsh.googlegroups.com> <1182841462.240341.321340@q69g2000hsb.googlegroups.com> Message-ID: <1182843294.719751.225690@o61g2000hsh.googlegroups.com> Well, I'm able to put html pages in /Library/Apache2/htdocs/ and access them in Safari as I would expect: http://localhost/test.htm and I can access the index.html page in that directory: http://localhost/index.html and it displays: It works! Apache 2.2.4 But, if I just use the address http://localhost/ in Safari, this is displayed: It works! Where is that coming from? Is the original index.html page(before I changed it and added "Apache 2.2.4") cached by Safari somehow? That doesn't make any sense to me because when I explicitly request index.html, I get the changed output. From NikitaTheSpider at gmail.com Fri Jun 1 10:29:30 2007 From: NikitaTheSpider at gmail.com (Nikita the Spider) Date: Fri, 01 Jun 2007 10:29:30 -0400 Subject: calling Postgresql stored procedure (written in plpython) References: <1180516688.022056.70220@q69g2000hsb.googlegroups.com> <1180685023.802141.168680@h2g2000hsg.googlegroups.com> Message-ID: In article <1180685023.802141.168680 at h2g2000hsg.googlegroups.com>, Alchemist wrote: > Thanks for your help. > > My stored procedure is written in pythonpl. I noticed that SELECT > queries are executed correctly (results are returned to my script) > whereas UPDATE queries are not being performed as the data is not > updated. Aha! So the problem is not really with how to call Postgres stored procs, but that you're not getting the results you expect from some calls. > I am using a database user with read/write access to the database. > > Is there a commit statement in plpython? (e.g. plpy.commit()) Did you try that? Did you check the documentation? > Why are UPDATEs failing? I'm not familiar with plpy but if it is compliant with the Python DBAPI (PEP 249) specification then, yes, it has a .commit() method and yes, you must call it after DDL statements. >From the PEP: "Note that if the database supports an auto-commit feature, this must be initially off." http://www.python.org/dev/peps/pep-0249/ In short, either turn on autocommit or start calling .commit(). -- Philip http://NikitaTheSpider.com/ Whole-site HTML validation, link checking and more From ed at leafe.com Fri Jun 8 10:12:41 2007 From: ed at leafe.com (Ed Leafe) Date: Fri, 8 Jun 2007 10:12:41 -0400 Subject: wxPython / Dabo demo shell ? In-Reply-To: <65129$4669612c$83aef404$15874@news1.tudelft.nl> References: <4646a$466901e6$83aef404$30670@news2.tudelft.nl> <4866bea60706080559m55a80f50he95c910eb90f90ed@mail.gmail.com> <65129$4669612c$83aef404$15874@news1.tudelft.nl> Message-ID: <6E9DDCE4-38ED-49DB-8AB9-EAF0669CB9DA@leafe.com> On Jun 8, 2007, at 10:01 AM, stef wrote: > I'm interested in the overall demo setup, > really beautiful and powerful, just one thing missing (user > configurable > tree). > > And if you can copy it, > I'm allowed to do so also ;-) You can certainly copy and customize the DaboDemo code. There is a folder named 'samples' that contains the the code for each individual demo. If you look at a few of those, you should be able to figure out how to create your own. The tree is created dynamically at startup, based on the files in the 'samples' directory, and each of those files' 'category' attribute. If you have any further questions, it would probably be best to post them to the dabo-users list. You can sign up for it at http:// leafe.com/mailman/listinfo/dabo-users -- Ed Leafe -- http://leafe.com -- http://dabodev.com From nano at nano.ono Fri Jun 15 17:30:36 2007 From: nano at nano.ono (nano) Date: Fri, 15 Jun 2007 14:30:36 -0700 Subject: Get the current date, python 2.2 Message-ID: Using python 2.2 what is the simplest way to get the current date value? I have looked in so many places. The question is often asked and the usual response indicates how to get the current date and time like now = time.localtime() I want just the date, like 2007-06-15. The value will go into a postgresql Date type column. Also, if postgres field of this type is set to time.localtime(), is the time portion of the date discarded, or stored 'invisibly', of will there be an error of some type? Just thought someone here might know. From evan at yelp.com Tue Jun 12 11:07:09 2007 From: evan at yelp.com (Evan Klitzke) Date: Tue, 12 Jun 2007 08:07:09 -0700 Subject: Pattern Classification Frameworks? Message-ID: Hi all, What frameworks are there available for doing pattern classification? I'm generally interested in the problem of mapping some sort of input to one or more categories. For example, I want to be able to solve problems like taking text and applying one or more tags to it like "romance", "horror", "poetry", etc. This isn't really my research specialty, but my understanding is that Bayesian classifiers are generally used for problems like this. I've had CRM114 recommended to me, but as far as I can tell there aren't any python bindings for this. From a few searches online, I've come across the Open Bayes project which is a Python library for working with Bayesian networks, and it also appears that DSPAM has some Python bindings, but from the cursory look I gave it it's hard to tell how general purpose the DSPAM engine is. Has anyone worked with any of these frameworks? Are there any other frameworks I should be aware of? Also, as a sidenote, are there any texts that anyone can recommend to me for learning more about this area? I'm a mathematician by training, so I'm not afraid to jump into reasonably advanced statistics papers/books if necessary. -- Evan Klitzke From showell30 at yahoo.com Thu Jun 14 21:17:10 2007 From: showell30 at yahoo.com (Steve Howell) Date: Thu, 14 Jun 2007 18:17:10 -0700 (PDT) Subject: SimplePrograms challenge In-Reply-To: Message-ID: <72084.88354.qm@web33506.mail.mud.yahoo.com> --- Steven Bethard wrote: > > How about including a driver? > > Yes, absolutely a good idea. Fortunately, the other > Steve borrowed the > time machine already and added this to the end:: > > for p in iter_primes(): > if p > 1000: break > print p > I think rzed (sorry for bad quoting) was (partly)making the point that we could have more explicitly showed how .next() worked. I'm fine with the current example, because I think the examples should solve problems at face value, and here it's very natural to use a loop with an iterator/generator (never mind the underlying magic), but I do think some future example should show how one can have more control over getting values from an iterator. ____________________________________________________________________________________ Looking for a deal? Find great prices on flights and hotels with Yahoo! FareChase. http://farechase.yahoo.com/ From horpner at yahoo.com Thu Jun 14 08:51:15 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Thu, 14 Jun 2007 12:51:15 GMT Subject: Method much slower than function? References: <1181781612.939800.238890@q19g2000prn.googlegroups.com> <%Q0ci.35541$G23.26580@newsreading01.news.tds.net> <4670e551$0$20040$426a74cc@news.free.fr> Message-ID: On 2007-06-14, Bruno Desthuilliers wrote: > Neil Cerutti a ?crit : > (snip) >> class bar: >> def readgenome(self, filehandle): >> self.s = ''.join(line.strip() for line in filehandle) > >=> > self.s = ''.join(line.strip() for line in filehandle if not > '>' in line) Thanks for that correction. -- Neil Cerutti I don't know what to expect right now, but we as players have to do what we've got to do to make sure that the pot is spread equally. --Jim Jackson From gagsl-py2 at yahoo.com.ar Wed Jun 27 01:39:52 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 27 Jun 2007 02:39:52 -0300 Subject: p & br using ElementTree? References: <4681e39a$1@griseus.its.uu.se> Message-ID: En Wed, 27 Jun 2007 01:12:10 -0300, Jan Danielsson escribi?: > This is probably a mind numbingly brain dead question.. But how do I > generate the following: > >

      Current date:
      2000-01-01

      > > ..using ElementTree? The

      element kind of needs two text blocks, > as far as I can tell? No, the date string goes into br's tail: py> import xml.etree.ElementTree as ET py> p=ET.fromstring py> p=ET.fromstring("

      Current date:
      2000-01-01

      ") py> p py> p.text 'Current date:' py> p.tail py> p[0] py> p[0].text py> p[0].tail '2000-01-01' See about infosets and the "mixed content" simplified model. -- Gabriel Genellina From half.italian at gmail.com Tue Jun 19 13:57:10 2007 From: half.italian at gmail.com (half.italian at gmail.com) Date: Tue, 19 Jun 2007 17:57:10 -0000 Subject: Windows XMLRPC Service In-Reply-To: References: <1182137125.879556.319030@g37g2000prf.googlegroups.com> <1182235519.964013.146800@a26g2000pre.googlegroups.com> Message-ID: <1182275830.571891.278580@n15g2000prd.googlegroups.com> On Jun 19, 10:21 am, "Gabriel Genellina" wrote: > En Tue, 19 Jun 2007 03:45:19 -0300, escribi?: > > > I can't quite figure out where to set the "socket timeout". I tried > > setting win32event.WAIT_TIMEOUT, but I'm pretty sure that's not the > > variable you were talking about. I did manage to make it multi- > > threaded by incorporating a different recipe, and I'm beginning to > > understand the control flow a bit better, but it doesn't seem to be > > doing what I expect. When SvcStop() is executed and calls > > win32event.SetEvent(self.hWaitStop), the while loop should break as > > win32event.WaitForSingleObject(self.hWaitStop, 0) returns zero at this > > point. But it doesn't do that. What am I missing? > > May be because you didn't set correctly the socket timeout. See the > comments below. > > > > > def SvcStop(self): > > self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) > > win32event.SetEvent(self.hWaitStop) > > #print "EVENT:", > > win32event.WaitForSingleObject(self.hWaitStop, 0) # returns 0 here > > That's OK, since you have set the event. > > > def SvcDoRun(self): > > self.server.register_instance(MyClass()) > > > #win32event.WAIT_TIMEOUT = 2 --- This just makes the loop > > never execute because > > # the WaitFor... part always returns 258 > > WAIT_TIMEOUT is 258. How do you see it is 2? > For example, see . > Python 2.5.1 + pywin32 210 prints this on my PC: > py> import win32event > py> win32event.WAIT_TIMEOUT > 258 > > > while win32event.WaitForSingleObject(self.hWaitStop, 0) == > > win32event.WAIT_TIMEOUT: > > self.server.handle_request() > > The loop above should keep running until hWaitStop is set, with a maximum > wait time (inside handle_request) corresponding to the socket timeout > value. > You can either: > - use socket.setdefaulttimeout() (in __init__, by example) before anything > else. This will set a global timeout for all sockets. > - modify the socket instance. Just add this method to your AsyncServer: > def server_activate(self): > SimpleXMLRPCServer.server_activate(self) > self.socket.settimeout(15) # for 15 secs > > -- > Gabriel Genellina > > def SvcDoRun(self): > > self.server.register_instance(MyClass()) > > > #win32event.WAIT_TIMEOUT = 2 --- This just makes the loop > > never execute because > > # the WaitFor... part always returns 258 > > WAIT_TIMEOUT is 258. How do you see it is 2? > For example, see . > Python 2.5.1 + pywin32 210 prints this on my PC: > py> import win32event > py> win32event.WAIT_TIMEOUT > 258 I meant here that *if* I set the WAIT_TIMEOUT to 2, then I see that behavior. > - use socket.setdefaulttimeout() (in __init__, by example) before anything > else. This will set a global timeout for all sockets. That was the one that did it. Thank you again Gabriel. I'll post back with something complete. ~Sean From horpner at yahoo.com Tue Jun 12 07:05:24 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Tue, 12 Jun 2007 11:05:24 GMT Subject: Python's "only one way to do it" philosophy isn't good? References: <1181368143.874341.273140@r19g2000prf.googlegroups.com> Message-ID: On 2007-06-12, Antoon Pardon wrote: > On 2007-06-11, Terry Reedy wrote: >> More so than supporters of most other languages, in particular >> Scheme? > > Well to my knowledge (which could be vastly improved), scheme > doesn't have some Zen-rules that include something like this. > > I tried to google for similar remarks in relation to scheme but > I got no results. Maybe your google skills are better. It's in _The Revised^%d Report on Scheme_, Introduction: 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. Of course, that was written well before Scheme had most of its current features. -- Neil Cerutti These people haven't seen the last of my face. If I go down, I'm going down standing up. --Chuck Person From gagsl-py2 at yahoo.com.ar Fri Jun 8 23:58:49 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 09 Jun 2007 00:58:49 -0300 Subject: read xml file from compressed file using gzip References: <1181278784.312152.99910@r19g2000prf.googlegroups.com> <4668E996.9020006@web.de> <1181303144.910159.326690@z28g2000prd.googlegroups.com> <1181307658.812854.143180@d30g2000prg.googlegroups.com> Message-ID: En Fri, 08 Jun 2007 10:00:58 -0300, flebber escribi?: >> I will, baby steps at the moment for me at the moment though as I am >> only learning and can't get gzip to work Try reading some tutorial from http://wiki.python.org/moin/BeginnersGuide -- Gabriel Genellina From chrisdillon06 at gmail.com Thu Jun 21 03:18:48 2007 From: chrisdillon06 at gmail.com (chrisdillon) Date: Thu, 21 Jun 2007 00:18:48 -0700 Subject: GET SATELLITE TV OM YOUR COMPUTER Message-ID: <1182410328.300602.268330@n60g2000hse.googlegroups.com> Why pay over $90.00 a month for Cable or Satellite TV services? Get over 3000 STATIONS on your PC or Laptop for free!! Instantly Turn your Computer into a Super TV http://chelsboy.ipodpsp.hop.clickbank.net/ From vinjvinj at gmail.com Tue Jun 26 11:04:10 2007 From: vinjvinj at gmail.com (vj) Date: Tue, 26 Jun 2007 08:04:10 -0700 Subject: Help needed with translating perl to python Message-ID: <1182870250.890390.28970@g37g2000prf.googlegroups.com> I have a perl script which connect to network stream using sockets. The scripts first logins in to the server and then parses the data comming from the socket. Statement 1: my $today = sprintf("%4s%02s%02s", [localtime()]->[5]+1900, [localtime()]->[4]+1, [localtime()]->[3]) ; Statement 2: my $password = md5_hex("$today$username") ; Statement group 3: $msglen = bcdlen(length($msg)) ; sub bcdlen { my $strlen = sprintf("%04s", shift) ; my $firstval = substr($strlen, 2, 1)*16 + substr($strlen, 3, 1) ; my $lastval = substr($strlen, 0, 1)*16 + substr($strlen, 1, 1) ; return chr($firstval) . chr($lastval) ; } From garrickp at gmail.com Thu Jun 21 15:16:15 2007 From: garrickp at gmail.com (Falcolas) Date: Thu, 21 Jun 2007 12:16:15 -0700 Subject: The Modernization of Emacs: terminology buffer and keybinding In-Reply-To: References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182272495.990807.99110@a26g2000pre.googlegroups.com> <87tzt3ihev.fsf@kobe.laptop> <1182370216.961241.6960@n60g2000hse.googlegroups.com> <85zm2ufjpb.fsf@lola.goethe.zz> <1182372592.803332.288260@u2g2000hsc.googlegroups.com> <1182373919.262388.100740@c77g2000hse.googlegroups.com> <85r6o6fhkb.fsf@lola.goethe.zz> <1182375045.626510.188170@m36g2000hse.googlegroups.com> Message-ID: <1182453375.531950.141460@m36g2000hse.googlegroups.com> On Jun 21, 10:09 am, Robert Uhl wrote: > You're quite right. Windows/Mac user interfaces are so clunky that they > massively hamper productivity. Emacs, OTOH, enables it. For example, > C-s is search forward; C-r is search backward ('reverse'); C-M-s is > search forward for a regular expression; C-M-r is search backward for a > regular expression. A Windows or Mac editor would have C-s for save, > and that's it. It might have C-f for find, but it'd pop up a dialogue > instead of offering an interactive search, causing a mental context > switch. Searching would interrupt one's flow of thought rather than > being part of it. Being a primarily windows user, I have to question your assertion that using ctrl-f for find causes a "mental context switch". For me, in 90% of the windows applications, finding something is as simple as ctrl-f, the phrase, hit enter. Not terribly different from your set of commands. The biggest difference is that if I need to use a Find feature I might not often use, I have a visual interface to all the related search functions. On the other hand, a terminal program would necessitate a memory search at best, or a trip to the help pages at worst. The best part of my windows knowledge is that it's transferable to most (all?) of the applications I work with. Find is usually ctrl-f. Undo is ctrl-z. Save is ctrl-s, yadda yadda. Such knowledge is rarely transferable from terminal programs in my experience -- what may be true for one program (emacs) is wildly different in another program (vi), and useless in yet another (pico). On the other hand, I can move from notepad to Word to Open Office to Notepad++, based on the availability at the terminal I'm on, with little difficulty. For the record, I use VIM when in terminals. Emacs isn't available on our *nix boxes. From gagsl-py2 at yahoo.com.ar Mon Jun 4 18:58:39 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 04 Jun 2007 19:58:39 -0300 Subject: Check for descriptors (in C) References: <1180894328.035886.248430@w5g2000hsg.googlegroups.com> <1hz4umw.1t47d7n1eu8w6hN%aleax@mac.com> Message-ID: En Sun, 03 Jun 2007 21:35:05 -0300, Alex Martelli escribi?: >> My actual use case: I want to check if an object (instance of a class >> that inherits from file) still uses the original write method or has >> overriden it. > > I'd check for identity between type(o).write and file.write -- seems a > more direct expression of that thought (and implementable with the C-API > just as well as with pure Python). Thanks! It looks obvious now :) -- Gabriel Genellina From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Tue Jun 19 17:13:42 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Tue, 19 Jun 2007 23:13:42 +0200 Subject: Python and (n)curses References: <1182211133.956524.160020@g4g2000hsf.googlegroups.com> <87y7igzapo.fsf@benfinney.id.au> <1182252362.643492.93890@n2g2000hse.googlegroups.com> <87myywyszg.fsf@benfinney.id.au> <1182260860.240519.3570@n60g2000hse.googlegroups.com> Message-ID: <5dqv86F35956oU3@mid.individual.net> pinkfloydhomer at gmail.com wrote: > On Jun 19, 3:27 pm, Ben Finney >> And as "peter" mentions, it awaits only someone doing that work >> and contributing it to Python. Those who can't see why it would >> be hard are welcome to do so. > > The classic answer. Yes, because of the classic problem with unsalaried software development. The top guys have more than enough to do, so the task is finding someone who will implement that. Or do it yourself. Don't you agree? BTW, this is no paid support. IMHO, you would do good reconsidering your attitude. Regards, Bj?rn -- BOFH excuse #255: Standing room only on the bus. From bugmagnet at gmail.com Thu Jun 21 05:20:04 2007 From: bugmagnet at gmail.com (bugmagnet at gmail.com) Date: Thu, 21 Jun 2007 09:20:04 -0000 Subject: Internationalised email subjects In-Reply-To: <1182346499.123234.279880@e9g2000prf.googlegroups.com> References: <1182337500.638044.63470@e9g2000prf.googlegroups.com> <46791592$0$5719$edfadb0f@dread14.news.tele.dk> <1182346499.123234.279880@e9g2000prf.googlegroups.com> Message-ID: <1182417604.446766.47660@e9g2000prf.googlegroups.com> Seems some characters are missing from my last post. The line that says: h = Header(' ', 'GB2312') should say: h = Header(' ', 'GB2312') From google at gakman.com Tue Jun 19 08:15:55 2007 From: google at gakman.com (google at gakman.com) Date: Tue, 19 Jun 2007 12:15:55 -0000 Subject: static python classes ? In-Reply-To: <1182254405.901790.189190@p77g2000hsh.googlegroups.com> References: <1182254405.901790.189190@p77g2000hsh.googlegroups.com> Message-ID: <1182255355.491845.44770@i13g2000prf.googlegroups.com> On Jun 19, 10:00 pm, Tom Gur wrote: > Hi, > > I'm new to python, and I can't seem to find in the docs how to create > the python equivalent of what's called in most OOP languages "static > classes", can you give me a hint ? Look for @staticmethod in http://docs.python.org/lib/built-in-funcs.html Example: class C: @staticmethod def f(arg1, arg2, ...): ... -- Gerald Kaszuba http://geraldkaszuba.com From stargaming at gmail.com Fri Jun 22 13:14:24 2007 From: stargaming at gmail.com (Stargaming) Date: Fri, 22 Jun 2007 19:14:24 +0200 Subject: howto run a function w/o text output? In-Reply-To: <1182531384.017220.218070@w5g2000hsg.googlegroups.com> References: <1182531384.017220.218070@w5g2000hsg.googlegroups.com> Message-ID: <467c0375$0$2763$9b622d9e@news.freenet.de> dmitrey schrieb: > hi all, > I have a > y = some_func(args) > statement, and the some_func() produces lots of text output. Can I > somehow to suppress the one? > Thx in advance, D. > Either rewrite it or pipe sys.stdout to some other file-like object but your console while running it. The StringIO (http://docs.python.org/lib/module-StringIO.html) module might help. From hniksic at xemacs.org Fri Jun 29 07:07:01 2007 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Fri, 29 Jun 2007 13:07:01 +0200 Subject: Looking for an interpreter that does not request internet access References: Message-ID: <87y7i381ey.fsf@mulj.homelinux.net> James Alan Farrell writes: > Hello, > I recently installed new anti-virus software and was surprised the > next time I brought up IDLE, that it was accessing the internet. > > I dislike software accessing the internet without telling me about it, > especially because of my slow dial up connection (there is no option > where I live), but also because I feel it unsafe. When I start up IDLE, I get this message: **************************************************************** Personal firewall software may warn about the connection IDLE makes to its subprocess using this computer's internal loopback interface. This connection is not visible on any external interface and no data is sent to or received from the Internet. **************************************************************** It would seem to explain the alarm you're seeing. From martin at v.loewis.de Fri Jun 1 00:56:34 2007 From: martin at v.loewis.de (=?ISO-8859-15?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Fri, 01 Jun 2007 06:56:34 +0200 Subject: Python 2.5.1 broken os.stat module In-Reply-To: References: <1180648618.295955.68600@x35g2000prf.googlegroups.com> Message-ID: <465fa702$0$2944$9b622d9e@news.freenet.de> > I created a file and specifically set the created date, last accessed date > and last write date to > > 01/02/2003 12:34:56 How did you do that? > In the case of my above test I know exactly what the timestamp on the file > is because I manually set it so that all 3 timestamps are the same. > Since Python 2.5.1 does not return the known values for that files > timestamps how can it not be a Python 2.5.1 bug? The program you've been using to set the time stamp to the old date may not be working correctly. > Further testing shows that the results are somewhat inconsistent, many times > the create and access date are correct but the Last Write timestamp is > wrong. It is generally off by one hour but I have seen situations where it > was +1 hour and other situations where it was -1 hour. In these cases, always ask yourself whether the time-zone of that time stamp is different from the current time zone. In particular, did these old time stamps live in non-DST, and the current time zone is a DST one? > I even found situations where the python timestamp was 1 minute later. (I > know about the 2 second timestamps on FAT, all my filesystems are NTFS). I > just found a situation where the python timestamp was 02:51 PM and the > windows timestamp was 02:12 PM. DST or timezone changes are not going to > make the results be off by 39 minutes? (My timezone is GMT - 5:00). Right. If that is reproducable, it is a bug. Please create a zip file containing this file, and submit a bug report to sf.net/projects/python. Regards, Martin From martin at v.loewis.de Tue Jun 12 23:55:34 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Wed, 13 Jun 2007 05:55:34 +0200 Subject: In C extension .pyd, sizeof INT64 = 4? In-Reply-To: <1181699066.050774.302040@x35g2000prf.googlegroups.com> References: <1181642594.963433.132750@g37g2000prf.googlegroups.com> <466efcdf$0$13674$9b622d9e@news.freenet.de> <1181696426.081185.63170@a26g2000pre.googlegroups.com> <1181699066.050774.302040@x35g2000prf.googlegroups.com> Message-ID: <466f6ab7$0$19414$9b622d9e@news.freenet.de> > I used INT64 and initialize its value from PyArg_ParseTuple. > The code is PyArg_ParseTuple(args, "l", &nValue). > It should be PyArg_ParseTuple(args, "L", &nValue). That's still incorrect. For the L format flag, use PY_LONG_LONG, not your own INT64 type. More generally: always use the type documented in http://docs.python.org/api/arg-parsing.html Regards, Martin From martin at v.loewis.de Sat Jun 2 06:30:19 2007 From: martin at v.loewis.de (=?ISO-8859-15?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sat, 02 Jun 2007 12:30:19 +0200 Subject: Python 2.5.1 broken os.stat module In-Reply-To: <0JCdnesCwLIHEcLbnZ2dnUVZ_tSunZ2d@comcast.com> References: <1180648618.295955.68600@x35g2000prf.googlegroups.com> <0JCdnesCwLIHEcLbnZ2dnUVZ_tSunZ2d@comcast.com> Message-ID: <466146BB.9030201@v.loewis.de> > File Name : P:\sw\Python\Lib\cgi.pyc > > python_access_ts: 05/31/2007 07:17 PM > win_access_ts : 05/31/2007 06:35 PM > > File Name : P:\sw\Python\Lib\code.pyc > > python_access_ts: 05/30/2007 07:59 PM > win_access_ts : 05/30/2007 07:22 PM I have analyzed these cases in more detail, and found that Windows (dir and Explorer) indeed reports incorrect last-access times. This is documented in http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/fsutil_behavior.mspx?mfr=true In essence, there are two places where the last-access time is stored: In the file itself, and in the directory. While the stamp in the file is constantly updated, the stamp in the directory is only updated if the difference exceeds one hour. This is done for performance reasons. Python 2.5 reports the true last access time, whereas dir, Explorer, and Python 2.4 report an access time that isn't quite the *last* access time. To see this for yourself, you can open a file, and watch the last-access time as reported by Windows not change, whereas Python reports a recent access (if the time stamp changes indeed, wait a few minutes, and access the file again - if the file hasn't been accessed for more than one hour, the first access will always update the time stamp right away). Regards, Martin From s.mientki at id.umcn.nl Tue Jun 5 08:19:03 2007 From: s.mientki at id.umcn.nl (stef) Date: Tue, 05 Jun 2007 14:19:03 +0200 Subject: how to convert a bitmap file to an array ? In-Reply-To: References: Message-ID: <3da6e$466554b7$83aef404$11190@news1.tudelft.nl> Stefan Sonnenberg-Carstens wrote: > stef schrieb: >> hello >> >> I can find all kind of procedures to convert an array to a bitmap >> (wxPython, PIL), >> but I can't find the reverse, >> either >> - convert a bitmap to an array >> or >> - read a bitmap file to an array >> >> thanks, >> Stef Mientki >> > Take a look at the "struct" module. > There you fill find pack/unpack, which can do what you need. thanks Stefan, but using struct, I need to know how a bitmap file is build, I don't know that (and I rather don't want to know that ;-) Any better solutions (I'm a spoiled Delphi user ;-) cheers, Stef Mientki From pietpot at gmail.com Tue Jun 5 04:44:32 2007 From: pietpot at gmail.com (Pieter Potgieter) Date: Tue, 5 Jun 2007 10:44:32 +0200 Subject: please help a newbie Message-ID: <7b66a29e0706050144w5a546e6ak51042085b68f4d1d@mail.gmail.com> Hi all I have a binary file of about 600kbytes - I want to break it up in file chunks of 1085 bytes - every file must have a new file name. The data is binary video frames (370 frames) - I want to play the data back into an embedded system frame/file by file. I am a complete Python newby - but have C/C++ skills. Please supply/help me with an snippet or example Thanks Pieter -------------- next part -------------- An HTML attachment was scrubbed... URL: From sjmachin at lexicon.net Mon Jun 4 08:16:24 2007 From: sjmachin at lexicon.net (John Machin) Date: Mon, 04 Jun 2007 05:16:24 -0700 Subject: excel library without COM In-Reply-To: <1180936346.272773.162540@q66g2000hsg.googlegroups.com> References: <1180918791.467050.186520@r19g2000prf.googlegroups.com> <1180936346.272773.162540@q66g2000hsg.googlegroups.com> Message-ID: <1180959384.545415.102340@n15g2000prd.googlegroups.com> On Jun 4, 3:52 pm, yuce wrote: > i think this one works pretty nice:http://www.python.org/pypi/xlrd Sure does :-) However the "rd" in "xlrd" is short for "ReaD". As Waldemar suggested, "xlwt" ("wt" as in WriTe) is more like what the OP needs. Cheers, John From jjl at pobox.com Wed Jun 6 18:07:36 2007 From: jjl at pobox.com (John J. Lee) Date: Wed, 06 Jun 2007 22:07:36 GMT Subject: How do you htmlentities in Python References: <1180965792.757685.132580@q75g2000hsh.googlegroups.com> <46643c3c$0$2892$6e1ede2f@read.cnntp.org> Message-ID: <871wgo4tz7.fsf@pobox.com> "Thomas Jollans" writes: > "Adam Atlas" wrote in message > news:1180965792.757685.132580 at q75g2000hsh.googlegroups.com... > > As far as I know, there isn't a standard idiom to do this, but it's > > still a one-liner. Untested, but I think this should work: > > > > import re > > from htmlentitydefs import name2codepoint > > def htmlentitydecode(s): > > return re.sub('&(%s);' % '|'.join(name2codepoint), lambda m: > > name2codepoint[m.group(1)], s) > > > > '&(%s);' won't quite work: HTML (and, I assume, SGML, but not XHTML being > XML) allows you to skip the semicolon after the entity if it's followed by a > white space (IIRC). Should this be respected, it looks more like this: > r'&(%s)([;\s]|$)' > > Also, this completely ignores non-name entities as also found in XML. (eg > %x20; for ' ' or so) Maybe some part of the HTMLParser module is useful, I > wouldn't know. IMHO, these particular batteries aren't too commonly needed. Here's one that handles numeric character references, and chooses to leave entity references that are not defined in standard library module htmlentitydefs intact, rather than throwing an exception. It ignores the missing semicolon issue (and note also that IE can cope with even a missing space, like "trés mal", so you'll see that in the wild). Probably it could be adapted to handle that (possibly the presumably-slower htmllib-based recipe on the python.org wiki already does handle that, not sure). import htmlentitydefs import re import unittest def unescape_charref(ref): name = ref[2:-1] base = 10 if name.startswith("x"): name = name[1:] base = 16 return unichr(int(name, base)) def replace_entities(match): ent = match.group() if ent[1] == "#": return unescape_charref(ent) repl = htmlentitydefs.name2codepoint.get(ent[1:-1]) if repl is not None: repl = unichr(repl) else: repl = ent return repl def unescape(data): return re.sub(r"&#?[A-Za-z0-9]+?;", replace_entities, data) class UnescapeTests(unittest.TestCase): def test_unescape_charref(self): self.assertEqual(unescape_charref(u"&"), u"&") self.assertEqual(unescape_charref(u"—"), u"\N{EM DASH}") self.assertEqual(unescape_charref(u"—"), u"\N{EM DASH}") def test_unescape(self): self.assertEqual( unescape(u"& < — — —"), u"& < %s %s %s" % tuple(u"\N{EM DASH}"*3) ) self.assertEqual(unescape(u"&a&"), u"&a&") self.assertEqual(unescape(u"a&"), u"a&") self.assertEqual(unescape(u"&nonexistent;"), u"&nonexistent;") unittest.main() John From __peter__ at web.de Mon Jun 4 06:04:39 2007 From: __peter__ at web.de (Peter Otten) Date: Mon, 04 Jun 2007 12:04:39 +0200 Subject: int vs long References: <1180839659.196587.194200@p77g2000hsh.googlegroups.com> <7xr6otiv4l.fsf@ruckus.brouhaha.com> <1180895701.813483.326780@k79g2000hse.googlegroups.com> <7xabvgj33p.fsf@ruckus.brouhaha.com> <1hz4uas.7jeyyu192pb8tN%aleax@mac.com> Message-ID: Marc 'BlackJack' Rintsch wrote: > Seems to be the same Python version, just build three days earlier and > with a different GCC version.??Weird. Indeed. Also, it seems to prove the explanation wrong that I just in response to Douglas' post... Peter From dan at coruskate.net Mon Jun 11 22:11:14 2007 From: dan at coruskate.net (Daniel Barlow) Date: Tue, 12 Jun 2007 03:11:14 +0100 Subject: The Concepts and Confusions of Prefix, Infix, Postfix and Fully Functional Notations In-Reply-To: <1181597817.867161.10510@h2g2000hsg.googlegroups.com> References: <1179936917.652372.24780@q69g2000hsb.googlegroups.com> <1180508453.226022.44230@q19g2000prn.googlegroups.com> <1181335574.107472.229370@x35g2000prf.googlegroups.com> <1181358616.792797.97720@k79g2000hse.googlegroups.com> <1181414625.121073.203940@g4g2000hsf.googlegroups.com> <0uHai.176367$nh4.13819@newsfe20.lga> <1181448558.120521.63250@g4g2000hsf.googlegroups.com> <0G_ai.1970$xg4.809@trnddc08> <1181525392.369255.138460@h2g2000hsg.googlegroups.com> <1181545345.788665.191690@q66g2000hsg.googlegroups.com> <1181597817.867161.10510@h2g2000hsg.googlegroups.com> Message-ID: <1181614274.14141.0@proxy02.news.clara.net> Tim Bradshaw wrote: > I think it's just obvious that this is the case. What would *stop* > you writing maintainable Perl? A grudge against humanity, usually -dan From kay.schluehr at gmx.net Fri Jun 1 13:17:56 2007 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Fri, 01 Jun 2007 10:17:56 -0700 Subject: subexpressions In-Reply-To: References: Message-ID: <1180718276.836399.187980@k79g2000hse.googlegroups.com> On Jun 1, 9:51 am, "Sergey Dorofeev" wrote: > Hello all! > > Please help, is there way to use sub-expressions in lambda? > For example, if I want to calculate sin(x^2)+cos(x^2) I must code: > lambda x: sin(x*x)+cos(x*x) > How to make x*x to be evaluated once? lambda x: (lambda y=x*x: math.sin(y)+math.cos(y))() Kay From joe at incomps.com Fri Jun 8 12:04:21 2007 From: joe at incomps.com (Joe) Date: Fri, 8 Jun 2007 10:04:21 -0600 Subject: Case-Insensitive Sorting of Multi-Dimensional Lists In-Reply-To: <8c7f10c60706080618m2fabe683i5cf4d9659471c1e1@mail.gmail.com> References: <020e01c7a94c$a7970750$0f01a8c0@desktop9> <8c7f10c60706080618m2fabe683i5cf4d9659471c1e1@mail.gmail.com> Message-ID: <02bc01c7a9e6$ad4f8330$0f01a8c0@desktop9> > Try: > > list.sort(key=lambda el: el[0].lower()) Now, I would like to be able to specify which index to sort by. I am not able to pass in external variables like: List.sort(key=lambda el: el[indexNumber].lower()) I am new to lambda and have searched for a few hours this morning, coming up empty handed. Is this possible? Thanks! Jough From ebgssth at gmail.com Mon Jun 4 19:14:34 2007 From: ebgssth at gmail.com (js ) Date: Tue, 5 Jun 2007 08:14:34 +0900 Subject: How do you htmlentities in Python In-Reply-To: <1180977447.745432.109040@q19g2000prn.googlegroups.com> References: <1180977447.745432.109040@q19g2000prn.googlegroups.com> Message-ID: Thanks you Matimus. That's exactly what I'm looking for! Easy, clean and customizable. I love python :) On 6/5/07, Matimus wrote: > On Jun 4, 6:31 am, "js " wrote: > > Hi list. > > > > If I'm not mistaken, in python, there's no standard library to convert > > html entities, like & or > into their applicable characters. > > > > htmlentitydefs provides maps that helps this conversion, > > but it's not a function so you have to write your own function > > make use of htmlentitydefs, probably using regex or something. > > > > To me this seemed odd because python is known as > > 'Batteries Included' language. > > > > So my questions are > > 1. Why doesn't python have/need entity encoding/decoding? > > 2. Is there any idiom to do entity encode/decode in python? > > > > Thank you in advance. > > I think this is the standard idiom: > > >>> import xml.sax.saxutils as saxutils > >>> saxutils.escape("&") > '&' > >>> saxutils.unescape(">") > '>' > >>> saxutils.unescape("A bunch of text with entities: & > <") > 'A bunch of text with entities: & > <' > > Notice there is an optional parameter (a dict) that can be used to > define additional entities as well. > > Matt > > -- > http://mail.python.org/mailman/listinfo/python-list > From twisted0n3 at gmail.com Tue Jun 26 20:16:19 2007 From: twisted0n3 at gmail.com (Twisted) Date: Wed, 27 Jun 2007 00:16:19 -0000 Subject: The Modernization of Emacs: terminology buffer and keybinding In-Reply-To: References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182272495.990807.99110@a26g2000pre.googlegroups.com> <87tzt3ihev.fsf@kobe.laptop> <1182370216.961241.6960@n60g2000hse.googlegroups.com> <85zm2ufjpb.fsf@lola.goethe.zz> <1182372592.803332.288260@u2g2000hsc.googlegroups.com> <5dtk4tF34jrimU1@mid.dfncis.de> <1182375388.814275.227380@n2g2000hse.googlegroups.com> <87645h73ei.fsf@W0053328.mgh.harvard.edu> <1182548563.561252.82480@i13g2000prf.googlegroups.com> Message-ID: <1182903379.098107.310320@k29g2000hsd.googlegroups.com> On Jun 26, 10:37 am, Bjorn Borud wrote: > ...and of course, in addition you have access to history so you can > easily find previous parameters and edit them. this makes it very > efficient when you need to fiddle about in deep directory trees in a > way no GUI can yet offer. > > ...and then there's bookmarking, which is very good for keeping a set > of files (and locations) handy for quick access. Good thing it has these. Bookmarking is quite natural and is THE way in GUIs to cope with deep directory structures. Bookmarking in a GUI is simple: you just open file-browser windows and park them in oft- visited places, to flip to whenever needed. Multitasking window systems are neat that way. Current versions of Windoze Explorer have a history and back and forward navigation buttons reminiscent of a Web browser, too. None of them turn into as big a PITA when lots of files have a lengthy, identical prefix either, which is a fairly common situation. That only causes difficulty at all when some column or window is sized too narrowly to show parts of the name past the prefix, forcing scrolling. Resizing it is then easy, thanks to the GUI, so unless the prefix is wide enough to cross the entire screen even if you set the font size down to 3... contrast that with tab completion, where to disambiguate you'll have to type the entire prefix and then part of the rest, THEN hit tab. If the prefix is long, you might be saving 3 keystrokes reducing 47 to 44, a gain in productivity of about 7%, a figure I'm sure you'll agree is somewhat underwhelming. Of course with a GUI it's spot-the-right-file-and-click, and just as fast whether the prefix is 4 characters long or 40. From pete.forman at westerngeco.com Wed Jun 20 05:44:57 2007 From: pete.forman at westerngeco.com (Pete Forman) Date: Wed, 20 Jun 2007 10:44:57 +0100 Subject: SimplePrograms challenge References: <1181603421.476263.102740@m36g2000hse.googlegroups.com> Message-ID: Andr? writes: > Ok, doctest-based version of the Unit test example added; so much > more Pythonic ;-) Sorry for being a bit picky but there are a number of things that I'm unhappy with in that example. 1) It's the second example with 13 lines. Though I suppose that the pragmatism of pairing the examples overriding an implicit goal of the page is itself Pythonic. 2) assert is not the simplest example of doctest. The style should be >>> add_money([0.13, 0.02]) 0.15 >>> add_money([100.01, 99.99]) 200.0 >>> add_money([0, -13.00, 13.00]) 0.0 3) which fails :-( So both the unittest and doctest examples ought to be redone to emphasize what they are doing without getting bogged down by issues of floating point representations. http://wiki.python.org/moin/SimplePrograms -- Pete Forman -./\.- Disclaimer: This post is originated WesternGeco -./\.- by myself and does not represent pete.forman at westerngeco.com -./\.- the opinion of Schlumberger or http://petef.port5.com -./\.- WesternGeco. From steve at REMOVE.THIS.cybersource.com.au Fri Jun 22 22:55:44 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sat, 23 Jun 2007 12:55:44 +1000 Subject: Python's "only one way to do it" philosophy isn't good? References: <1181368143.874341.273140@r19g2000prf.googlegroups.com> <7x3b0nmkk6.fsf@ruckus.brouhaha.com> Message-ID: On Fri, 22 Jun 2007 13:21:14 -0400, Douglas Alan wrote: > I.e., I could write a new object system for Lisp faster than I could > even begin to fathom the internal of CPython. Not only that, I have > absolutely no desire to spend my valuable free time writing C code. > I'd much rather be hacking in Python, thank you very much. Which is very valuable... IF you care about writing a new object system. I don't, and I think most developers don't, which is why Lisp-like macros haven't taken off. I simply don't want to think about object syntax, I just want it to work. I'm happy that Guido and the other Python-dev people have thought about it, and come up with a good syntax, and are conservative with their syntax changes. When I use somebody else's library, I don't want to have to learn their syntax, no matter how cunning they think it is. The cost is that if I do have a brilliant new idea for syntax to Python, it is hard for me to implement it. Nobody sensible denies that Python's model is cost-free. But I think the cost is worth it, in the same way that building houses out of bricks and mortar instead of plastic Lego blocks makes it really hard to redesign the layout of rooms in the house, but has other advantages. (Don't over-analyze the analogy. I'm not suggesting Lisp code is necessarily as fragile and easy to break as a house made of Lego would be, or that Python code is safe as houses.) -- Steven. From tjreedy at udel.edu Sat Jun 9 13:12:42 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 9 Jun 2007 13:12:42 -0400 Subject: interating over single element array References: <4Beai.13210$5j1.6184@newssvr21.news.prodigy.net><1181345593.788652.275380@h2g2000hsg.googlegroups.com> <1181391368.112303.284890@q75g2000hsh.googlegroups.com> Message-ID: "Basilisk96" wrote in message news:1181391368.112303.284890 at q75g2000hsh.googlegroups.com... | "Terry Reedy" wrote: | > Any what if 'filelist' is any iterable other than a string or list? Your | > code is broken, and unnecessarily so. So I would call the parameter | > 'files' and test for isinstance(files, str) #or basestring. And wrap if it | > is. | | Can you give an example of such an iterable (other than a tuple)? Tuple was the first thing I thought of, and one will break the list test. The next would be an iterator that walks a file hierarchy spitting out the names of non-directory files, or all files with a certain extension, or all files with a certain owner, or timestamp characteristic. | I'd certainly like to fix my 'fix' to work for a more general case. As I said, I think it as simple as changing 'not list' to 'is string'. tjr From bradfordh at gmail.com Wed Jun 6 20:09:10 2007 From: bradfordh at gmail.com (Tempo) Date: Wed, 06 Jun 2007 17:09:10 -0700 Subject: Copy a file from PDA Message-ID: <1181174950.689350.90580@q69g2000hsb.googlegroups.com> Are there libraries out there that will assist me in copying a file from my Dell Axim PDA (Windows Mobile) and putting the copy onto my desktop (Windows XP)? Thanks so much. From orsenthil at gmail.com Mon Jun 25 10:01:00 2007 From: orsenthil at gmail.com (Phoe6) Date: Mon, 25 Jun 2007 07:01:00 -0700 Subject: Reading multiline values using ConfigParser In-Reply-To: References: <1182394281.778904.315430@z28g2000prd.googlegroups.com> Message-ID: <1182780060.452410.139290@q69g2000hsb.googlegroups.com> On Jun 21, 7:34 pm, "John Krukoff" wrote: > > > > Is there anyway, I can include multi-line value in the configfile? I > > > > Following the link to RFC 822 (http://www.faqs.org/rfcs/rfc822.html) > > > indicates that you can spread values out over multiple lines as long as > > > there is a space or tab character imeediately after the CRLF. > > > Thanks for the response. It did work! > > > >>> config = ConfigParser() > > >>> config.read("Testcases.txt") > > ['Testcases.txt'] > > >>> output = config.get("Information", "Testcases") > > >>> print output > > > tct123 > > tct124 > > tct125 > > >>> output > > '\ntct123\ntct124\ntct125' > > > However, as I am going to provide Testcases.txt to be "user editable", > > I cannot assume or "ask users" to provide value testcases surronded by > > spaces. I got to figure out a workaround here. > > Sounds like you're stuck modifying ConfigParser to do what you want, or > writing your own configuration file parsing utilities. > > >From looking through the ConfigParser source, looks like all the parsing > > work is inside the _read method, so shouldn't be too painful to make a > subclass that does what you want. > I took the approach of Subclassing ConfigParser to support multiline values without leading white-spaces, but am struct at which position in _read I should modify to accomodate the non-leading whitespace based multiline values. I can guess, this portion in the _read function will require change, any change to this affects the whole of parsing. :-( Can someone who has done this before or understands ConfigParser better help me? # Section I am talking about if line[0].isspace() and cursect is not None and optname: value = line.strip() if value: cursect[optname] = "%s\n%s" % (cursect[optname], value) # _read method def _read(self, fp, fpname): cursect = None optname = None lineno = 0 e = None while True: line = fp.readline() if not line: break lineno = lineno + 1 # comment or blank line? if line.strip() == '' or line[0] in '#;': continue if line.split(None, 1)[0].lower() == 'rem' and line[0] in "rR": # no leading whitespace continue # continuation line print "line:%s\tcursect:%s\toptname:%s"%(line,cursect,optname) if line[0].isspace() and cursect is not None and optname: value = line.strip() if value: cursect[optname] = "%s\n%s" % (cursect[optname], value) # a section header or option header? else: # is it a section header? mo = self.SECTCRE.match(line) if mo: sectname = mo.group('header') if sectname in self._sections: cursect = self._sections[sectname] elif sectname == ConfigParser.DEFAULTSECT: cursect = self._defaults else: cursect = {'__name__':sectname} self._sections[sectname] = cursect # So sections can't start with a continuation line optname = None elif cursect is None: raise ConfigParser.MissingSectionHeaderError(fpname, lineno, line) # an option line? else: mo = self.OPTCRE.match(line) if mo: optname, vi, optval = mo.group('option','vi','value') if vi in ('=',':') and ';' in optval: # ';' is a comment delimiter only if it follows # a spacing character pos = optval.find(';') if pos != -1 and optval[pos-1].isspace(): optval = optval[:pos] optval = optval.strip() # allow empty values if optval == '""': optval = '' optname = self.optionxform(optname.rstrip()) cursect[optname] = optval else: if not e: e = ConfigParser.ParsingError(fpname) e.append(lineno, repr(line)) if e: raise e -- Senthil From ianc at acm.org Sun Jun 10 04:01:28 2007 From: ianc at acm.org (IanC) Date: Sun, 10 Jun 2007 09:01:28 +0100 Subject: Needed: FTP Upload Directory Tree script Message-ID: Hi, Does anyone know of a function or script to upload an entire subdirectory tree from a local file space to an FTP server? The Python distribution comes with "ftpmirror.py", which performs a mirror download of a directory tree, but I need the "Upload" version of this. Thanks for any hints -- -- Ian -- ianc at acm.org --- From vasudevram at gmail.com Sun Jun 24 15:22:13 2007 From: vasudevram at gmail.com (vasudevram) Date: Sun, 24 Jun 2007 19:22:13 -0000 Subject: Do eval() and exec not accept a function definition? (like 'def foo: pass) ? In-Reply-To: References: Message-ID: <1182712933.359638.22880@e16g2000pri.googlegroups.com> On Jun 24, 6:28 am, Jean-Paul Calderone wrote: > On Sun, 24 Jun 2007 11:17:40 +1000, Steven D'Aprano wrote: > >On Sat, 23 Jun 2007 19:58:32 +0000, vasudevram wrote: > > >> Hi group, > > >> Question: Do eval() and exec not accept a function definition? (like > >> 'def foo: pass) ? > > >eval() is a function, and it only evaluates EXPRESSIONS, not code blocks. > > Actually, that's not exactly true: > > >>> x = compile('def foo():\n\tprint "hi"\n', '', 'exec') > >>> l = {} > >>> eval(x, l) > >>> l['foo']() > hi > >>> > > Jean-Paul Thanks, all. Will check out the replies given. - Vasudev From bj_666 at gmx.net Wed Jun 27 07:41:02 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Wed, 27 Jun 2007 13:41:02 +0200 Subject: Too many 'self' in python.That's a big flaw in this language. References: <1182942154.185461.89620@e9g2000prf.googlegroups.com> Message-ID: In <1182942154.185461.89620 at e9g2000prf.googlegroups.com>, hide1713 at gmail.com wrote: > I'm currently using Python. I find that a instance variable must > confined with self, > for example: > class a: > def __init__(self): > self.aa=10 > def bb(self): > print self.aa # See .if in c++,I could use aa to change that > variable > > That's a big inconvenience in coding ,especially when you have lot of > variable > If you method need 10 variables ,you have to type "self" for 10 times > and that also makes your variable longer. > >>From My point,I think this only help python interpreter to deside > where to look for. > Is there anyone know's how to make the interpreter find instance name > space first? > Or any way to make programmer's life easier? Use a shorter name than `self` or an editor with auto completion. If a name in a function or method is local or global is decided at compile time, not at run time. So at least every assignment to an instance attribute must have the ``self.`` in front or the compiler sees the name as local to the method. Changing this would slow down the interpreter because every name has to be looked up in the instance dict every time to decide if it's an attribute or a local name. Another drawback of your proposed "magic" is that attributes can be assigned, deleted or delegated dynamically at run time. So your bare `aa` name can change meaning from instance attribute to local name or vice versa over the time. You must have very compelling reasons to ask for changes that spare you some keystrokes by the way. Pythonistas usually don't like sacrificing readability for fewer characters. Most source code will be written once but must be read and understood a couple of times, so it's more important to have clear than short code. With `self` in place you always know which names are local and which are attributes. Ciao, Marc 'BlackJack' Rintsch From steve at holdenweb.com Fri Jun 1 07:09:50 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 01 Jun 2007 07:09:50 -0400 Subject: subexpressions In-Reply-To: References: Message-ID: Sergey Dorofeev wrote: > "Peter Otten" <__peter__ at web.de> wrote in message > news:f3oo0p$c7c$03$1 at news.t-online.com... >>>>> Please help, is there way to use sub-expressions in lambda? >>>>> For example, if I want to calculate sin(x^2)+cos(x^2) I must code: >>>>> lambda x: sin(x*x)+cos(x*x) >>>>> How to make x*x to be evaluated once? >>>>>>> (lambda x: [sin(x2) + cos(x2) for x2 in [x*x]][0])(.5) == sin(.5*.5) >>>>>>> + >>>> cos(.5*.5) >>>> True >>>> >>>> The real answer is of course: Use a function. >>> But what about something like >>> >>> lambda x: sin(y)+cos(y) where y=x*x >>> >>> ? >>> May be this could be a PEP? If there is no straight way to do this. >> def f(x): >> y = x*x >> return sin(y) + cos(y) >> >> What is not straightforward about that? > > This code is needed once in a map, so I don't want 3+ extra lines. > Solution seemed so simple... > I always considered python as languague, where simple things do not require > extensive coding. > Moreover, this construction is common thing in functional programming. > > Stop thinking of three lines as "extensive coding" and your problem disappears immediately. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden ------------------ Asciimercial --------------------- Get on the web: Blog, lens and tag your way to fame!! holdenweb.blogspot.com squidoo.com/pythonology tagged items: del.icio.us/steve.holden/python All these services currently offer free registration! -------------- Thank You for Reading ---------------- From ocollioud at gmail.com Mon Jun 4 09:32:43 2007 From: ocollioud at gmail.com (olive) Date: Mon, 04 Jun 2007 13:32:43 -0000 Subject: Python, Dutch, English, Chinese, Japanese, etc. In-Reply-To: References: <1180958764.491893.130160@h2g2000hsg.googlegroups.com> Message-ID: <1180963963.036424.62850@q69g2000hsb.googlegroups.com> Lol! What is a "sharp hair boss" ? My boss does not look like a punk ! But he does want me to dance "la Java". From bignose+hates-spam at benfinney.id.au Fri Jun 22 06:41:14 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 22 Jun 2007 20:41:14 +1000 Subject: PEP 3107 and stronger typing (note: probably a newbie question) References: <1182448413.966430.299590@m36g2000hse.googlegroups.com> <7xhcp0fom4.fsf@ruckus.brouhaha.com> Message-ID: <87tzt0tgol.fsf@benfinney.id.au> Paul Rubin writes: > I think it was a real loss that Python 3.0 proposals were closed > before PyPy was widely deployed and we had a chance to get more > experience with it. I think it's great that we're going to get Python 3.0 soon, and that Python 4.0 proposals will benefit from a long period of familiarity with widely-deployed PyPy :-) -- \ "I bought some batteries, but they weren't included; so I had | `\ to buy them again." -- Steven Wright | _o__) | Ben Finney From gagsl-py2 at yahoo.com.ar Wed Jun 27 01:40:30 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 27 Jun 2007 02:40:30 -0300 Subject: How to destroy a Frame with condition References: <1ef9860e0706262139u41cd3db9g23647880f8ad609e@mail.gmail.com> Message-ID: En Wed, 27 Jun 2007 01:39:22 -0300, senthil arasu escribi?: > In my code logic I need to check the frame existence and then destroy a > frame. > I dont know how to code this condition. > In Python tutorials what i reffered, "if "condition given only for > integers(like if x>0:) > > I need some one to help me. > > This is my condition > > If iframe==NULL//if frame not available > iframe.destroy() That does not look like Python code - and in any case, it does not make much sense. If iframe is NULL you can't call a method on it. In Python, usually the symbol None is used when you want to say "nothing" (like NULL, null, or nil in another languages). But unlike other languages, None is an actual object - a singleton, there exist exactly one instance of it, that is, all references to None along the whole program refer to the same and unique object. To test is something is None or anything else, you use the "is" operator. It tests object identity (whether both operands are in fact the same thing). Your code above (reversed) would be: if iframe is not None: iframe.destroy() This will call the destroy() method of iframe, only when iframe is not the None object itself. -- Gabriel Genellina From Omer.Khalid at cern.ch Tue Jun 26 17:05:27 2007 From: Omer.Khalid at cern.ch (Omer Khalid) Date: Tue, 26 Jun 2007 23:05:27 +0200 Subject: What was that web interaction library called again? In-Reply-To: <33E725AB-D965-4FC6-8207-E597EFE8F185@acm.org> References: <33E725AB-D965-4FC6-8207-E597EFE8F185@acm.org> Message-ID: <77e5896b0706261405nce68e26re052a571c62fcc58@mail.gmail.com> On the RESTFul web service, I would like to piggy pack my own question two is there a way to make the connection secure between two Restful service running on GNU/linux? Thanks, Omer On 6/26/07, Kathryn Van Stone wrote: > > > > So does anyone know of any equivalent library for testing RESTful web > services. > > In particular it needs to be able to handle more than 'GET' or "POST" > http calls. > > -Kathy Van Stone > kvs at acm.org > > -- > http://mail.python.org/mailman/listinfo/python-list > -- ---------------------------------------------------------- CERN ? European Organization for Nuclear Research, IT Department, CH-1211 Geneva 23, Switzerland Phone: +41 (0) 22 767 2224 Fax: +41 (0) 22 766 8683 E-mail : Omer.Khalid at cern.ch Homepage: http://cern.ch/Omer.Khalid -------------- next part -------------- An HTML attachment was scrubbed... URL: From showell30 at yahoo.com Thu Jun 14 22:07:18 2007 From: showell30 at yahoo.com (Steve Howell) Date: Thu, 14 Jun 2007 19:07:18 -0700 (PDT) Subject: SimplePrograms challenge In-Reply-To: <6a2ccd190706141900u738491bbgbb6d0ecc043f2172@mail.gmail.com> Message-ID: <463361.39257.qm@web33511.mail.mud.yahoo.com> --- Joe Riopel wrote: > How about this one for recursion and control flow: > > >>> def hcd(m,n): > ... r = m % n > ... if( r > 0 ): > ... hcd(n, r) > ... else: > ... print "hcd = %d" % (n,) > ... > >>> hcd(119, 544) > hcd = 17 > >>> > > It calculates the highest common denominator for m > and n. Plus it's E1 > in TAoCP by Knuth. > I'm a little wary of having the page contain too many mathematical examples, although I admit that I've already included Fibonacci and Eratosthenes. (And your example shares in common with those two that it's a classic example.) Feel free to post your example on the page, but please use slightly more descriptive identifiers (e.g. change hcd to highest_common_denominator or largest_common_denominator), and also have the program print out the results. Thanks. -- Steve ____________________________________________________________________________________ Yahoo! oneSearch: Finally, mobile search that gives answers, not web links. http://mobile.yahoo.com/mobileweb/onesearch?refer=1ONXIC From hat at se-162.se.wtb.tue.nl Thu Jun 28 09:19:53 2007 From: hat at se-162.se.wtb.tue.nl (A.T.Hofkamp) Date: Thu, 28 Jun 2007 15:19:53 +0200 Subject: equality & comparison by default (was Re: Too many 'self' in python.That's a big flaw in this language.) References: <1182942154.185461.89620@e9g2000prf.googlegroups.com> <1i0cy8z.z94q5d1dxgexxN%aleax@mac.com> Message-ID: On 2007-06-27, Alex Martelli wrote: > A.T.Hofkamp wrote: > >> I think that again now with the default implementation of the >> object.__eq__ and object.__hash__ methods. I believe these methods should >> not exist until the programmer explicitly defines them with a suitable >> notion of equivalence. >> >> Anybody have a good argument against that? :-) > > It's very common and practical (though not ideologically pure!) to want > each instance of a class to "stand for itself", be equal only to itself: > this lets me place instances in a set, etc, without fuss. Convenience is the big counter argument, and I have thought about that. I concluded that the convenience advantage is not big enough, and the problem seems to be what "itself" exactly means. In object oriented programming, objects are representations of values, and the system shouldn't care about how many instances there are of some value, just like numbers in math. Every instance with a certain value is the same as every other instance with the same value. You can also see this in the singleton concept. The fact that it is a pattern implies that it is special, something not delivered by default in object oriented programming. This object-oriented notion of "itself" is not what Python delivers. Python 2.4.4 (#1, Dec 15 2006, 13:51:44) [GCC 3.4.4 20050721 (Red Hat 3.4.4-2)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> class Car(object): ... def __init__(self, number): ... self.number = number ... def __repr__(self): ... return "Car(%r)" % self.number ... >>> 12345 == 12345 True >>> Car(123) == Car(123) False So in Python, the default equivalence notion for numbers is based on values, and the default equivalence notion for objects assumes singleton objects which is weird from an object oriented point of view. Therefore, I concluded that we are better off without a default __eq__ . The default existence of __hash__ gives other nasty surprises: >>> class Car2(object): ... def __init__(self, number): ... self.number = number ... def __repr__(self): ... return "Car2(%r)" % self.number ... def __eq__(self, other): ... return self.number == other.number ... Above I have fixed Car to use value equivalence (albeit not very robust). Now if I throw these objects naively in a set: >>> a = Car2(123) >>> b = Car2(123) >>> a == b True >>> set([a,b]) set([Car2(123), Car2(123)]) I get a set with two equal cars, something that never happens with a set my math teacher once told me. Of course, I should have defined an appropiate __hash__ method together with the __eq__ method. Unfortunately, not every Python programmer has always had enough coffee to think about that when he is programming a class. Even worse, I may get a class such as the above from somebody else and decide that I need a set of such objects, something the original designer never intended. The problem is then that something like "set([Car2(123), Car2(124)])" does the right thing for the wrong reason without telling me. Without a default __hash__ I'd get at least an error that I cannot put Car2 objects in a set. In that setup, I can still construct a broken set, but I'd have to write a broken __hash__ function explicitly rather than implicitly inheriting it from object. > I don't want, in order to get that often-useful behavior, to have to > code a lot of boilerplate such as > def __hash__(self): return hash(id(self)) > and the like -- so, I like the fact that object does it for me. I'd I understand that you'd like to have less typing to do. I'd like that too if only it would work without major accidents by simple omission such as demonstrated in the set example. Another question can be whether your coding style would be correct here. Since you apparently want to have singleton objects (since that is what you get and you are happy with them), shouldn't you be using "is" rather than "=="? Then you get the equivalence notion you want, you don't need __eq__, and you write explicitly that you have singleton objects. In the same way, sets have very little value for singleton objects, you may as well use lists instead of sets since duplicate **values** are not filtered. For lists, you don't need __hash__ either. The only exception would be to filter multiple inclusions of the same object (that is what sets are doing by default). I don't know whether that would be really important for singleton objects **in general**. (ie wouldn't it be better to explicitly write a __hash__ based on identity for those cases?) > have no objection if there were two "variants" of object (object itself > and politically_correct_object), inheriting from each other either way > 'round, one of which kept the current practical approach while the other > made __hash__ and comparisons abstract. Or you define your own base object class "class Myobject(object)" and add a default __eq__ and __hash__ method. This at least gives an explicit definition of the equivalence notion for your application. > In Python 3000, ordering comparisons will not exist by default (sigh, a > modest loss of practicality on the altar of purity -- ah well, saw it > coming, ever since complex numbers lost ordering comparisons), but > equality and hashing should remain just like now (yay!). I didn't try that, but it seems like a good decision. Ordering based on identity may change with each invocation of the program! Albert From Leo.Kislov at gmail.com Thu Jun 28 04:17:51 2007 From: Leo.Kislov at gmail.com (Leo Kislov) Date: Thu, 28 Jun 2007 01:17:51 -0700 Subject: Portable general timestamp format, not 2038-limited In-Reply-To: <7x7ipoy6cf.fsf@ruckus.brouhaha.com> References: <1182544384.709759.235300@o11g2000prd.googlegroups.com> <20070625133843.9e25d0ab.steveo@eircom.net> <82b5l4-tvh.ln1@zoogz.gregorie.org> <7xbqf3lc7i.fsf@ruckus.brouhaha.com> <70c7l4-2gp.ln1@zoogz.gregorie.org> <7xlke6y6y1.fsf@ruckus.brouhaha.com> <7x645al8kc.fsf@ruckus.brouhaha.com> <1182894003.920335.317620@a26g2000pre.googlegroups.com> <7x7ipoy6cf.fsf@ruckus.brouhaha.com> Message-ID: <1183018671.058603.194500@e16g2000pri.googlegroups.com> On Jun 27, 10:51 pm, Paul Rubin wrote: > The difficulty/impossibility of computing intervals on UTC because of > leap seconds suggests TAI is a superior timestamp format. If you care about intervals you'd better keep timestamps in SI seconds since some zero time point (just like OP wanted). TAI timestamps are pretty useless IMHO. They need to be converted to decimal/float for interval calculations and they don't represent any legal time. -- Leo From carsten at uniqsys.com Sun Jun 17 14:41:54 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Sun, 17 Jun 2007 14:41:54 -0400 Subject: sqlite3 bug?? In-Reply-To: <46757cf6$0$27845$db0fefd9@news.zen.co.uk> References: <46752230$0$31685$db0fefd9@news.zen.co.uk> <46753426$0$30325$fa0fcedb@news.zen.co.uk> <1182091411.108272.286280@o61g2000hsh.googlegroups.com> <46757cf6$0$27845$db0fefd9@news.zen.co.uk> Message-ID: <1182105714.3162.15.camel@localhost.localdomain> On Sun, 2007-06-17 at 19:26 +0100, mark carter wrote: > Carsten Haese wrote: > > On Sun, 2007-06-17 at 07:43 -0700, 7stud wrote: > >> Please report the whole docs as a bug. > > > > I imagine the author appreciates constructive criticism. This is not > > constructive criticism. > > > > In other words: Pointing out specific shortcomings and ways to correct > > them, such as what the OP is doing, is helpful. Calling the entire docs > > a bug is not helpful. > > You'll be pleased to know that I was specific, and I suggested a change > that I thought would be good. I know, and I acknowledged that. Maybe you missed that OP = original poster = You. -- Carsten Haese http://informixdb.sourceforge.net From steve at REMOVE.THIS.cybersource.com.au Fri Jun 15 22:27:02 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sat, 16 Jun 2007 12:27:02 +1000 Subject: Should: "for k,v in **dictionary_instance" work? References: <1181935045.323196.287810@n2g2000hse.googlegroups.com> Message-ID: On Fri, 15 Jun 2007 19:17:25 +0000, keithgabryelski wrote: > Does it make sense to provide this syntax for iterating key/value > pairs from a dictionary? > > for k,v in **dict(): > print k,v > > why is this not the same as: > > for k,v in dict().items(): > print k,v Because *t and **d already have well-defined meanings, and that's not what **d would mean. In a function definition, *t collects positional arguments into a tuple and **d collects keyword arguments into a dictionary. In a function call, they expand them again. For example: function(1, 2, 3, a=4, b=5, c=6) ==> t = (1, 2, 3); d = {'a':4, 'b':5, 'c':6} function(*t, **d) ==> function(1, 2, 3, a=4, b=5, c=6) Currently, *t and **d are syntax errors outside of function calls and definitions. (Any other places?) But if they were allowed, what would they mean? For consistency, we would expect the following: t = tuple(1, 2, 3) for item in *t: # same as "for item in 1, 2, 3:" print item Even if it were allowed, it would be pointless: it would just expand the tuple only to collect it again. What would **d mean? d = dict(a=1, b=2, c=3) for key, value in **d: # same as "for key, value in 'a': 1, 'b': 2, 'c': 3:" print key, value For starters, that would mean changing the syntax of Python to allow key:value assignments outside of a dict constructor. I can't think of a reason to do so, but even if there is, we have the same problem as for the tuple expansion: it would pointlessly expand the dict, only to collect it again. Maybe you don't care about consistency and you just want the compiler to accept "for k,v in **d" as syntactic sugar for "for k,v in d.items()". Or perhaps d.iteritems() would be a better choice. In that case, Python isn't very big on syntactic sugar merely for saving a few characters of typing, so you're unlikely to convince those who would need convincing. > for that matter, why the heck doesn't a dictionary default to > returning a tuple > k,v pair from its iterator? When dictionaries were first made iterable, in Python 2.2 if I recall correctly, there was debate about whether "for thing in dict:" should be equivalent to iterating over the keys, the values or both. In particular, people pointed out that there were just as many, or slightly more, examples of "for k,v in dict.items()" as "for k in dict.keys()" in the standard library. So there is a good case for making iterating over a dictionary equivalent to iterating over the keys and values. But the deciding point was the correspondence between "for x in dict" and "if x in dict". In fact, Python then, and now, included a fall-back iterator protocol: if __getitem__ is defined, iteration over an object is equivalent to repeatedly calling __getitem__. You can read the PEP that covers some of these issues here: http://svn.python.org/projects/peps/trunk/pep-0234.txt -- Steven. From skip.montanaro at gmail.com Thu Jun 7 09:57:11 2007 From: skip.montanaro at gmail.com (Skip Montanaro) Date: Thu, 7 Jun 2007 08:57:11 -0500 Subject: Lack of += and -= operators in Pyrex? Message-ID: <60bb7ceb0706070657y5fadb720ha2165e56ecf25ae4@mail.gmail.com> I'm experimenting a bit with Pyrex and like it pretty well so far. While converting a module from Python to Pyrex I noticed it complains about the use of the += and -= assignment operators. The fix is obviously pretty trivial. I didn't notice any mention in the Pyrex docs as a difference between Python and Pyrex though. Was I mistaken? In case it makes any difference, the structure of the couple statements I needed to change was obj.attr.subattr += self.attr Thx, Skip From horpner at yahoo.com Wed Jun 6 11:37:55 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Wed, 06 Jun 2007 15:37:55 GMT Subject: lists - append - unique and sorted References: <1181143597.563633.241640@o5g2000hsb.googlegroups.com> Message-ID: On 2007-06-06, rhXX wrote: > hi, > > can i append a item to a list using criterias: > > - UNIQUE - if there already exist don't append Consult the Python Docs about sets. > and/or > > - SORTED - INSERT in the correct place using some criteria? Consult the Python Docs about the heapq module. -- Neil Cerutti Beethoven wrote fewer symphonies than Haydn and Mozart because he wrote longer, and besides he went death. --Music Lit Essay From bbxx789_05ss at yahoo.com Fri Jun 22 17:28:37 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: Fri, 22 Jun 2007 14:28:37 -0700 Subject: Adding method to a class on the fly In-Reply-To: <1182547391.088804.68260@x35g2000prf.googlegroups.com> References: <1182538969.522044.209560@q19g2000prn.googlegroups.com> <1182543862.369337.36880@z28g2000prd.googlegroups.com> <1182547065.295969.258820@g37g2000prf.googlegroups.com> <1182547391.088804.68260@x35g2000prf.googlegroups.com> Message-ID: <1182547717.817307.77420@x35g2000prf.googlegroups.com> On Jun 22, 3:23 pm, askel wrote: > sorry, of course last line should be: > Dummy().method2('Hello, world!') ..which doesn't meet the op's requirements. From rpw3 at rpw3.org Mon Jun 25 03:02:20 2007 From: rpw3 at rpw3.org (Rob Warnock) Date: Mon, 25 Jun 2007 02:02:20 -0500 Subject: The Modernization of Emacs: terminology buffer and keybinding References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182731526.329068.101540@c77g2000hse.googlegroups.com> Message-ID: <6IidnRMu2ZPh9eLbnZ2dnUVZ_h2pnZ2d@speakeasy.net> Robert Uhl wrote: +--------------- | However, the only two which matter are GNU emacs and XEmacs. | Both have supported a GUI for 16 years now. I don't have | XEmacs installed, so I cannot tell you if it has the tutorial. | I would be truly surprised if it didn't. +--------------- It does. And the default startup splash screen tells you how to access it. -Rob ----- Rob Warnock 627 26th Avenue San Mateo, CA 94403 (650)572-2607 From stefan.behnel-n05pAM at web.de Tue Jun 26 07:09:15 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Tue, 26 Jun 2007 13:09:15 +0200 Subject: Installing python under the linux In-Reply-To: <1182845417.526433.59690@c77g2000hse.googlegroups.com> References: <1182800785.231113.199750@n2g2000hse.googlegroups.com> <1182802267.969628.156960@o61g2000hsh.googlegroups.com> <1182845417.526433.59690@c77g2000hse.googlegroups.com> Message-ID: <4680F3DB.6040901@web.de> vedrandekovic at v-programs.com wrote: > is there any folder with that basic Python > on ubuntu linux where can I find file "Grammar" and change the names > of python keywords. AFAICT, the Grammar file is not part of the binary installation. So, download the Python source distribution from python.org and unpack it if you want to play with it. Stefan From martin at v.loewis.de Tue Jun 12 16:06:55 2007 From: martin at v.loewis.de (=?GB2312?B?Ik1hcnRpbiB2LiBMbyJ3aXMi?=) Date: Tue, 12 Jun 2007 22:06:55 +0200 Subject: In C extension .pyd, sizeof INT64 = 4? In-Reply-To: <1181642594.963433.132750@g37g2000prf.googlegroups.com> References: <1181642594.963433.132750@g37g2000prf.googlegroups.com> Message-ID: <466efcdf$0$13674$9b622d9e@news.freenet.de> Allen schrieb: > My C extension works wrong, and debug it, found that sizeof (INT64) = > 4, not 8. > I compile on Windows XP platform. > Please tell me how to fix it to support INT64? What *is* INT64? It's not a builtin type of standard C, it isn't defined by Microsoft C, and it isn't predefined by Python. So it must be something that you have defined, and apparently incorrectly. How did you define it? Regards, Martin From half.italian at gmail.com Wed Jun 13 03:48:54 2007 From: half.italian at gmail.com (half.italian at gmail.com) Date: Wed, 13 Jun 2007 00:48:54 -0700 Subject: Bytes/File Size Format Function In-Reply-To: <1181706472.008233.80050@a26g2000pre.googlegroups.com> References: <1181706472.008233.80050@a26g2000pre.googlegroups.com> Message-ID: <1181720934.824480.175540@n15g2000prd.googlegroups.com> On Jun 12, 8:47 pm, samuraisam wrote: > Quick file size formatting for all those seekers out there... > > import math > > def filesizeformat(bytes, precision=2): > """Returns a humanized string for a given amount of bytes""" > bytes = int(bytes) > if bytes is 0: > return '0bytes' > log = math.floor(math.log(bytes, 1024)) > return "%.*f%s" % ( > precision, > bytes / math.pow(1024, log), > ['bytes', 'kb', 'mb', 'gb', 'tb','pb', 'eb', 'zb', 'yb'] > [int(log)] > ) Wait a sec...what if you send it a large amount of bytes? Say... bigger than 2147483647. You'll get an OverflowError. I thought you had my solution... ~Sean From gagsl-py2 at yahoo.com.ar Thu Jun 14 19:42:39 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 14 Jun 2007 20:42:39 -0300 Subject: save class References: <1181784016.454693.42340@o11g2000prd.googlegroups.com> <1181787082.712869.72770@z28g2000prd.googlegroups.com> <1181847914.603957.174200@n15g2000prd.googlegroups.com> Message-ID: En Thu, 14 Jun 2007 16:05:14 -0300, nik escribi?: > On Jun 13, 10:04 pm, Josiah Carlson > wrote: >> Gabriel Genellina wrote: >> > En Wed, 13 Jun 2007 23:11:22 -0300, nik escribi?: >> >> It would seem that I want to actually save the source code for the >> >> class. I know that I could of course open up an editor and just make >> >> it, but my ideal would be to have the base class, Map, be able to >> make >> >> the sub-classes. I don't want the class definition. What I want is an >> >> actual class that I could later import and use somewhere else. I am >> >> planning to have each one of these map objects contain a different >> >> dictionary and then be able to import the map into the application, >> >> but have certain methods defined in the Map super-class to draw data >> >> out of the specific map's specific dictionary. I hope that makes >> >> sense. >> > And are you sure you actually need different subclasses? Will you >> > construct them several instances of each subclass? From the above >> > description I feel you want just different Map *instances*, each with >> > its own dict, not different *subclasses*. >> >> What you said, and that his solution sounds like a Java approach to the >> problem (subclass an abstract base class that calls specific methods on >> the subclass to "do the right thing"). >> >> To offer the OP source he can use... >> >> class Map: >> def __init__(self): >> self.dict = {} >> def DoSomething(self): >> #do something with self.dict >> >> Every instance gets a new dictionary. Now, if he actually wants to >> change the behavior of the DoSomething method, of course then it would >> make sense to subclass Map. >> >> - Josiah > > I am hoping to change the self.dict for each subclass. I realize that > I could save self.dict to file and then load in different dicts each > time I get a new instance of class. But I want to be able to make > subclasses of map that each have different self.dict. Then when I need > to use them, just import the module and use the specific dict, instead > of having to keep track of a separate dictionary file. I am new to As Josiah said, I still don't see why do you want a *subclass*. If the only difference between your "subclasses" is their dict, they're not subclasses but just Map *instances*. Let's say, have a class Person, with attributes "name" and "email". If I want to represent two different persons, I would create two Person *instances*: Person(name="Gabriel", email="gagsl-py2 at ...") and Person(name="nik", email="nikbaer at ...") Classes try to capture behavior and structure; instances contain state (very roughly said). One *could* use two subclasses here, and in certain circumstances it may be useful, but it's not the most common case. > this, but I thought that this would be a regular thing to do in > python, because people must make classes in the interactive console > and then export them somehow for later use. I've never done that. I only use the interactive interpreter for testing purposes, I never "develop" code inside the interpreter. -- Gabriel Genellina From martin at v.loewis.de Fri Jun 1 03:56:18 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Fri, 01 Jun 2007 09:56:18 +0200 Subject: Thread-safety of dict In-Reply-To: References: Message-ID: <465FD122.9030108@v.loewis.de> > So there you have it: if you're using a dict with custom classes (or > anything other than str) across multiple threads, and without locking > it, it's possible (though presumably extremely rare) for a lookup to > fail even through the key was there the entire time. That could be fixed by adding a generation counter to the dictionary, right? Then an adversary would have to arrange for the generation counter to roll over for lookdict to not notice that the dictionary was modified. Regards, Martin From kw at codebykevin.com Sat Jun 2 16:52:10 2007 From: kw at codebykevin.com (Kevin Walzer) Date: Sat, 02 Jun 2007 16:52:10 -0400 Subject: Non-blocking subprocess call In-Reply-To: References: <442be$4661b3e7$4275d90a$6641@FUSE.NET> Message-ID: <4661D87A.1070202@codebykevin.com> Josiah Carlson wrote: > > If you are talking about non-blocking reading and writing from the > subprocess, there isn't natively. But there is a cookbook entry: > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/440554 > > - Josiah Any idea why this feature was removed from the language? It seems pretty essential to me. -- Kevin Walzer Code by Kevin http://www.codebykevin.com From me at privacy.net Sun Jun 3 04:45:36 2007 From: me at privacy.net (Mark Carter) Date: Sun, 03 Jun 2007 09:45:36 +0100 Subject: Python rocks In-Reply-To: <1hz3e3u.e9p5xz1u3ekfhN%aleax@mac.com> References: <4661700a$0$19261$da0feed9@news.zen.co.uk> <4661adda$0$19256$da0feed9@news.zen.co.uk> <1hz3e3u.e9p5xz1u3ekfhN%aleax@mac.com> Message-ID: <46627fb2$0$19248$da0feed9@news.zen.co.uk> Alex Martelli wrote: > Josiah Carlson wrote: > >>> pitfall of Python is knowing whether an operation is destructive or not. >> If it returns None, it probably changes the content of an object. > > A reasonable heuristic, but with lots of exceptions, alas: > somedict.get(somekey) > will often return None without performing any change, while > somelist.pop() > does modify somelist but typically returns non-None. > > The use of trailing-exclamation-point (by convention) to indicate > "mutating methods" is a nice plus in languages that allow it. Actually, that'd be nice to have in Python. And whilst we're about it, might as well go the whole hog and allow hyphens in names, too. From antroy at gmail.com Thu Jun 7 05:36:55 2007 From: antroy at gmail.com (Ant) Date: Thu, 07 Jun 2007 09:36:55 -0000 Subject: Help a C++ escapee! In-Reply-To: References: Message-ID: <1181209015.714157.124300@q75g2000hsh.googlegroups.com> Hi Simon, > When run, I come unstuck here: > > self.clientSocket, self.clientAddress = network.accept() > > I get a nameError on 'network', yet it is one in the global namespace, > defined in server.py before CServerThread.Listen() is called. You have imported everything from socketManager in server.py, but socketManager knows nothing about any globals defined in the server module! You'd need to import it in socketManager.py: from server import network However this may not work, since you have circular dependencies in your code - server requires socketManager and vice versa. Even if this does work it is bad practice, and is an indication that your classes are in the wrong modules, or that your classes need refactoring somewhat. A simple solution would be to pass an instance of the CNetworkManager into CServerThread. i.e. ... def Listen(self): self.threadArray =[] self.ch = 0 while self.ch < self.maxClients: #Create a thread listening to each socket self.newThreadObject = CServerThread(self) self.newThreadObject.start() self. threadArray.append(self.newThreadObject) self.ch=self.ch+1 class CServerThread(threading.Thread): def __init__(self, network): self.network = network def run(self): while (1): self.clientSocket, self.clientAddress = self.network.accept() ... HTH. -- Ant... http://antroy.blogspot.com/ From geoff.bache at pobox.com Mon Jun 11 09:01:45 2007 From: geoff.bache at pobox.com (geoffbache) Date: Mon, 11 Jun 2007 06:01:45 -0700 Subject: Threads, signals and sockets (on UNIX) In-Reply-To: <466D3AD3.5040100@hotmail.com> References: <466D2FF6.2070209@web.de> <1181563003.508142.23870@g4g2000hsf.googlegroups.com> <466D3AD3.5040100@hotmail.com> Message-ID: <1181566905.705839.82270@q66g2000hsg.googlegroups.com> > > You could probably use the Asyncore stuff to do it as well (with a lot > less stuff). This looked interesting. But it seems the asyncore stuff operates at the socket level, whereas I've currently just got a standard synchronous SocketServer and the socket operations themselves are kind of hidden beneath this layer. Can you point me at anything that might tell me how to combine Asyncore with SocketServer, preferably without having to mess with the internals of SocketServer too much :) Geoff From dak at gnu.org Wed Jun 20 16:35:12 2007 From: dak at gnu.org (David Kastrup) Date: Wed, 20 Jun 2007 22:35:12 +0200 Subject: The Modernization of Emacs: terminology buffer and keybinding References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182272495.990807.99110@a26g2000pre.googlegroups.com> <87tzt3ihev.fsf@kobe.laptop> <1182370216.961241.6960@n60g2000hse.googlegroups.com> Message-ID: <85zm2ufjpb.fsf@lola.goethe.zz> Twisted writes: > On the other hand, being actively beginner-hostile leads to nobody > adopting the tool. Then again, if you don't mind being the last > generation that'll ever use it, then I guess you're okay with > that. If it suits its existing users, the rest of us will just > continue to use something else. > > I continue to suspect that there's an ulterior motive for making and > keeping certain software actively beginner-hostile; a certain macho > elitism also seen with light aircraft pilots and commented on at > www.asktog.com (exact URL escapes me; sorry). You are babbling. Emacs is amazingly beginner-friendly for the power and flexibility it provides. You can sit a beginner at an Emacs session and have him start editing and learning. You can't do the same, say, with vi or a clone: the least you need is a vi helpsheet/cheat cup. With Emacs, the help sheet is helpful but optional (most people would be eyed strangely anyway if they kept a cheat barrel around at their workplace). -- David Kastrup, Kriemhildstr. 15, 44793 Bochum From horpner at yahoo.com Wed Jun 20 11:30:21 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Wed, 20 Jun 2007 15:30:21 GMT Subject: static python classes ? References: <1182254405.901790.189190@p77g2000hsh.googlegroups.com> <5dq518F35ubh4U1@mid.uni-berlin.de> <5dquobF35956oU1@mid.individual.net> <1hzzw9t.1723qye101q38xN%aleax@mac.com> Message-ID: On 2007-06-20, Alex Martelli wrote: > Neil Cerutti wrote: > >> In C++ they are used most often for factory functions, since they >> conveniently have access to the class's private members, and >> don't want or need an existing instance. Python seems to have >> adopted this use-case (ConfigParser, for example), but without a >> need for it (code organization?). > > What staticmethod does ConfigParser have? Can't recall one > offhand. I misremembered which module I had recently seen it in: it was datetime, not ConfigParser. And ('datetime.today') is, as you point out, a class method rather than a static method. Thanks for the correction. > I think Python more commonly uses classmethod, rather than > staticmethod, for factories (i.e. a la Smalltalk, not a la > C++). In that case the advantage wrt a function _is_ there: > when you subclass, you can get instances of the new class, > rather than the base class, from the factory: > >>>> class zap(dict): pass > ... >>>> z = zap.fromkeys(range(4)) >>>> z > {0: None, 1: None, 2: None, 3: None} >>>> type(z) > >>>> > > If dict_fromkeys was a plain function (or if fromkeys was a > staticmethod rather than a classmethod of dict) then z would be > an instance of dict, rather than one of zap (unless you also > specifically passed the desired class, kind of cumbersome). Thanks. That makes much more sense than my misunderstanding did. ;) -- Neil Cerutti Ask about our plans for owning your home --sign at mortgage company From steve at REMOVE.THIS.cybersource.com.au Fri Jun 22 21:24:53 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sat, 23 Jun 2007 11:24:53 +1000 Subject: is this a valid import sequence ? References: <4f97$467c254d$d443bb3a$9522@news.speedlinq.nl> Message-ID: On Fri, 22 Jun 2007 21:43:40 +0200, Stef Mientki wrote: > This might be a very weird construction, > but it's the most easy way in translating another language into Python (for simulation). > > Although it works, I like to know if this a valid construction: Since it works, how can it NOT be a valid construction? However, using global variables is almost always a bad idea. Passing parameters around is really cheap in Python, that's almost always a better solution. -- Steven. From jaeltong at yahoo.co.uk Mon Jun 11 05:32:50 2007 From: jaeltong at yahoo.co.uk (jaeltong at yahoo.co.uk) Date: Mon, 11 Jun 2007 02:32:50 -0700 Subject: Regular Text In-Reply-To: References: <1181552035.275951.68010@g4g2000hsf.googlegroups.com> Message-ID: <1181554370.583984.70530@q66g2000hsg.googlegroups.com> Wow, that is fast. Thanks. > In your code, you should use string literals like > > my_path = r"C:\Programs\Python\new" > my_path = "C:\\Programs\\Python\\new" > > But you said "a program to retrieve the filepath" - and I understand that > you dont have a string literal, and you compute it somehow. Escape > characters should not be a problem then. Have you verified the contents of > the text file? With notepad? I meant, I used a GUI-Tkinter Script to retrieve the input(the directory). my program is supposed to 1. get the directory from the GUI Script, with my_path= FieldValue.insert(n, variable.get()) 2. open a text file 3. and edit a filepath in the file, 4 then saving as another new file... if that is the case, how should I do, in order to get the input in the correct format?? From me at privacy.net Sun Jun 17 09:16:20 2007 From: me at privacy.net (mark carter) Date: Sun, 17 Jun 2007 14:16:20 +0100 Subject: sqlite3 bug?? In-Reply-To: References: <46752230$0$31685$db0fefd9@news.zen.co.uk> Message-ID: <46753426$0$30325$fa0fcedb@news.zen.co.uk> David Wahler wrote: > On 6/17/07, mark carter wrote: >> Anyone else getting these problems? > > See http://www.python.org/dev/peps/pep-0249/ (emphasis mine): > > .commit() OK, I tried that, and I appear to be cooking. The funny thing is, I could have sworn that I tried that a few days ago, and it didn't work. Weird. Appears to be working now, though, so I guess I must have been doing something kooky. Should I also explicitly close the cursor and connection, or is that taken care of "automagically"? I'm seriously thinking about reporting the commit() thing as a doc bug in python, as this isn't mentioned at http://docs.python.org/lib/module-sqlite3.html and I think it's exactly the kind of thing that should be mentioned in the examples. From S.Mientki-nospam at mailbox.kun.nl Sat Jun 2 10:39:14 2007 From: S.Mientki-nospam at mailbox.kun.nl (Stef Mientki) Date: Sat, 02 Jun 2007 16:39:14 +0200 Subject: subexpressions In-Reply-To: References: Message-ID: <45023$46618025$d443bb3a$19391@news.speedlinq.nl> Steve Howell wrote: >> def f(x): y = x*x; return sin(y)+cos(y); >> > > Although I know valid trigonometry is not the point of > this exercise, I'm still trying to figure out why > anybody would ever take the square of an angle. > What's the square root of pi/4 radians? Maybe he meant sin(x)^2 + cos(x)^2 which is well known demodulation technique if you create two signals 90 degrees out of phase. Stef From mip at fastwebnet.it Tue Jun 5 18:18:07 2007 From: mip at fastwebnet.it (ZioMiP) Date: Wed, 06 Jun 2007 00:18:07 +0200 Subject: which "GUI module" you suggest me to use? In-Reply-To: <1181081726.486363.290660@d30g2000prg.googlegroups.com> References: <1181081726.486363.290660@d30g2000prg.googlegroups.com> Message-ID: Matimus ha scritto: >> I know that WxPython work only under Windows > > Hmm, there seems to be some disparity between what you know and the > truth... > > WxPython works everywhere (Windows, Linux, MacOS), and it works well. > Also, it has web widgets that come standard (wx.html.HtmlWindow). > > Matt > Thanks for this ^_^ so I think I'll try to migrate to wx From cor at clsnet.nl Fri Jun 22 19:53:21 2007 From: cor at clsnet.nl (Cor Gest) Date: 22 Jun 2007 23:53:21 +0000 Subject: The Modernization of Emacs: terminology buffer and keybinding References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182272495.990807.99110@a26g2000pre.googlegroups.com> <87tzt3ihev.fsf@kobe.laptop> <1182370216.961241.6960@n60g2000hse.googlegroups.com> <85zm2ufjpb.fsf@lola.goethe.zz> <1182372592.803332.288260@u2g2000hsc.googlegroups.com> <1182549094.366282.286740@m37g2000prh.googlegroups.com> <87bqf7fwmg.fsf@telesippa.clsnet.nl> <1182553682.197778.138500@g37g2000prf.googlegroups.com> Message-ID: <877ipvfswe.fsf@telesippa.clsnet.nl> Some entity, AKA nebulous99 at gmail.com, wrote this mindboggling stuff: (selectively-snipped-or-not-p) > On Jun 22, 6:32 pm, Cor Gest wrote: > > > HOW IN THE BLOODY HELL IS IT SUPPOSED TO OCCUR TO SOMEONE TO ENTER > > > THEM, GIVEN THAT THEY HAVE TO DO SO TO REACH THE HELP THAT WOULD TELL > > > THEM THOSE ARE THE KEYS TO REACH THE HELP?! > > > > What's your problem ? > > > > Ofcourse a mere program-consumer would not look what was being > > installed on his/her system in the first place ... > > So after some trivial perusing what was installed and where : > > WOW Look, MA ! .... it's all there! > > > > lpr /usr/local/share/emacs/21.3/etc/refcard.ps > > or your install-dir........^ ^ > > or your version.............................^ > > So now we're expected to go on a filesystem fishing expedition instead > of just hit F1? One small step (backwards) for a man; one giant leap > (backwards) for mankind. :P that's M-` Escape-Backtick in a CLI, for you, thank you very much ... Function-Keys do not work in in a vt100 terminal. You really are that shallow, aren't you ? and lazy too, huh ? > copyright and not copyleft, so much for the "free as in speech" too, > and nevermind the "free as in beer". Download & print the junk then. Ofcourse you pay your ISP for the priviledge & give some treehuggers a nervous brakedown in the process. Cor -- (defvar MyComputer '((OS . "GNU/Emacs") (IPL . "GNU/Linux"))) The biggest problem LISP has, is that it does not appeal to dumb people If that fails to satisfy read the HyperSpec, woman frig or Tuxoharata mailpolicy @ http://www.clsnet.nl/mail.php From jeremy at omba.demon.co.uk Fri Jun 8 17:55:31 2007 From: jeremy at omba.demon.co.uk (Jeremy C B Nicoll) Date: Fri, 8 Jun 2007 22:55:31 +0100 Subject: Working with fixed format text db's References: Message-ID: Neil Cerutti wrote: > On 2007-06-08, Jeremy C B Nicoll wrote: > > Neil Cerutti wrote: > >> Luckily, the output format has not changed yet, so issues with > >> maintaining the above haven't arisen. > > > > The problem surely is that when you want to change the format > > you have to do so in all files (and what about the backups > > then?) and all programs simultaneously. > > I don't have control of the format, unfortunately. It's an import > file format for a commercial database application. You're saying your program merely has to read data files created by that database app? It's not that you have a whole suite of programs that create and read these files, nor that you have years worth of old files that would need their format converted if the programs were changed? > It is not actually *hard* to do this with ad-hoc code, but then > the program is indecipherable without a hardcopy of the spec in > hand. And also, as you say, if the spec ever does change, the > hand-written batch of ljust, rjust and slice will be somewhat of > a pain to reconfigure. You could presumably define a list (of some sort, might be the wrong terminology) that defines the 'name', type, length, justification and padding of each field, and then make the explicit code you showed loop through that list and do what's needed field by field. There's a risk that abstracting the definitions will make the code less clear to anyone else; at least it's clear what the current stuff does. > But biggest weakness, to me, is that the specification is not in > the code, or read and used by the code, and I think it should be. It'd be better if you could read the data layout spec from some file produced by the database system. No chance perhaps of having the dat files include some sort of dummy first record that contains the necessary info in a form that you could interpret? -- Jeremy C B Nicoll - my opinions are my own. From pavlovevidence at gmail.com Fri Jun 29 23:23:07 2007 From: pavlovevidence at gmail.com (Carl Banks) Date: Fri, 29 Jun 2007 20:23:07 -0700 Subject: overriding base class In-Reply-To: References: Message-ID: <1183173787.142422.73120@u2g2000hsc.googlegroups.com> On Jun 29, 7:36 pm, alf wrote: > Hi, > > I want to develop a following lib: > > lib space user space > > A -> B -> | -> user_class > > however A and B are abstrac enough to have following: > > user_super_base_class -> | -> A -> B -> | -> user_class > > user space lib space user spaca > > Any idea how to do that? One possibility is to use multiple inheritance to get the same effect. This is easy in Python but wouldn't work in C++. Note: it's very important use new-style classes, however, so always inherit from object or some other new-style class. First, in the library space define A and B. Notice that even though A derives from object, it calls the "base" class's method. class A(object): def method(self): print "calling A.method" super(A,self).method() class B(A): def method(self): print "calling B.method" super(B,self).method() In user space, declare the base class as so. Note that super is not called because this is the "real" base. class SuperBase(object): def method(self): print "calling SuperBase.method" Then, the user class. We use multiple inheritance here, and put SuperBase at the end. The effect is the same as if A had been derived from SuperBase. class User(B,SuperBase): def method(self): print "calling User.method" super(User,self).method() Calling this User().method() produces the following output: calling User.method calling B.method calling A.method calling SuperBase.method Notice that A.method calls SuperBase.method, quite unintuitively for someone not used to Python's MRO rules. Basically, whenever you have multiple bases, Python creates a consistent ordering of the bases, called the Method Resolution Order (MRO), according to precedence. You can exploit this to "insert" a super base class at the bottom. You can see what the MRO of a class is with the __mro__ attribute. For example, User.__mro__ is: (, , , , ) Even though A didn't derive directly from SuperBase, it acts as if it had been, because it's right before SuperBase in the MRO. Now that I've suggested that, I highly recommend you be sure you're very acquainted with new-style objects and method resolution order before attempting this. You need extra care when using MI, even though this use of it is rather tame. Cark Banks From mccredie at gmail.com Wed Jun 20 14:02:12 2007 From: mccredie at gmail.com (Matimus) Date: Wed, 20 Jun 2007 18:02:12 -0000 Subject: need help with re module In-Reply-To: References: Message-ID: <1182362532.927017.20760@d30g2000prg.googlegroups.com> On Jun 20, 9:58 am, linuxprog wrote: > hello > > i have that string "helloworldok" and i want to > extract all the text , without html tags , the result should be some > thing like that : helloworldok > > i have tried that : > > from re import findall > > chaine = """helloworldok""" > > print findall('[a-zA-z][^(<.*>)].+?[a-zA-Z]',chaine) > > >>> ['html', 'hell', 'worl', 'anyt', 'ag>o'] > > the result is not correct ! what would be the correct regex to use ? This: [^(<.*>)] is a set that contains everything but the characters "(","<",".","*",">" and ")". It most certainly doesn't do what you want it to. Is it absolutely necessary that you use a regular expression? There are a few HTML parsing libraries out there. The easiest approach using re might be to do a search and replace on all tags. Just replace the tags with nothing. Matt From stefan.behnel-n05pAM at web.de Sat Jun 9 13:46:16 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Sat, 09 Jun 2007 19:46:16 +0200 Subject: Gzip - gunzip using zlib In-Reply-To: <1181358947.291489.85950@q19g2000prn.googlegroups.com> References: <1181358947.291489.85950@q19g2000prn.googlegroups.com> Message-ID: <466AE768.2050805@web.de> flebber wrote: > Hi Can anyone show me a working example of how to use gzip to > decompress a file. I have read the docs at python.org and had many > goes at it but just can't get it to work. According to your other post, you are trying to open a ZIP archive using gzip. Use the zipfile module instead. Stefan From keithgabryelski at gmail.com Fri Jun 15 15:17:25 2007 From: keithgabryelski at gmail.com (keithgabryelski at gmail.com) Date: Fri, 15 Jun 2007 19:17:25 -0000 Subject: Should: "for k,v in **dictionary_instance" work? Message-ID: <1181935045.323196.287810@n2g2000hse.googlegroups.com> Does it make sense to provide this syntax for iterating key/value pairs from a dictionary? for k,v in **dict(): print k,v why is this not the same as: for k,v in dict().items(): print k,v for that matter, why the heck doesn't a dictionary default to returning a tuple k,v pair from its iterator? Pax, Keith Ps, I'm sure someone has thought of these things before, probably been answered before, but I'm sure I didn't find reference to them when i searched. From roy at panix.com Sun Jun 17 11:15:46 2007 From: roy at panix.com (Roy Smith) Date: Sun, 17 Jun 2007 08:15:46 -0700 Subject: Embedding unit tests in source files? Message-ID: <1182093346.170792.109970@p77g2000hsh.googlegroups.com> I'm starting a new project and am thinking of embedding my unit tests right in the source files. I've used unittest before, and I'm happy with it, but I've always used it with the source code in one file and the unit tests in another. I figure if I just put a if __name__ == '__main__": import unittest blah, blah, blah block at the end of each source file, I'll end up with a cleaner project structure. I can run the unit tests just by executing each source file. Any comments from people who have organized their Python projects this way? Did it work out well? It seems like what you give up is the ability to aggregate tests in a hierarchy of test suites. In theory, that sounds like something you might want to do, but in practice, I've never found it that useful, so I don't think I'll miss it. I know about doctest, but I'm happy with unittest and don't see any reason to change. From bruno.42.desthuilliers at wtf.websiteburo.oops.com Wed Jun 6 07:26:46 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Wed, 06 Jun 2007 13:26:46 +0200 Subject: *Naming Conventions* In-Reply-To: References: <1180909218.939713.112010@q69g2000hsb.googlegroups.com> <1180990280.960271.235550@h2g2000hsg.googlegroups.com> Message-ID: <466699e9$0$2308$426a74cc@news.free.fr> Neil Cerutti a ?crit : > On 2007-06-04, Michael Hoffman wrote: >> Wildemar Wildenburger wrote: >>> While that is true, I guess it is commonplace to use i, j, k >>> and n (maybe others) in constructs like >>> >>> for i in range(len(data)): >>> do_stuff(data[i]) >>> >>> Or should the good python hacker do that differently? Hope not >>> ;). >> Well, yes, I would do: >> >> for item in data: >> do_stuff(item) >> >> or, if using enumerate: >> >> for item_index, item in enumerate(data): >> do_stuff(item_index, item) >> >> I agree with Bruno that i and j should be used only for >> indices, but I'm usually less terse than that. > > I find i and j preferable to overly generic terms like "item." > Since 'i' and 'j' are canonically loop indices, I find it totally confusing to use them to name the iteration variable - which is not an index. At least, 'item' suggests that it's an object, and a part of the collection - not just an index you'll have to use to subscript the container. Also, and as far as I'm concerned, I certainly dont find 'i' and 'j' *less* generic than 'item' !-) I agree that except for uber-generic code or quick throw-away script 'item' is probably not a very good name, but then nor are 'i' and 'j'... From kyosohma at gmail.com Thu Jun 21 11:22:57 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Thu, 21 Jun 2007 08:22:57 -0700 Subject: Adding Python to the path in Windows In-Reply-To: References: <1182437575.810986.205610@n2g2000hse.googlegroups.com> Message-ID: <1182439377.009844.320760@q75g2000hsh.googlegroups.com> On Jun 21, 10:10 am, Duncan Booth wrote: > k... at thenortheastgroup.com wrote: > > I have many users using two different versions of python, 2.4 and > > 2.5. I am running Python scripts on their computers programmatically, > > but I can't run it with the full path because they have different > > versions installed. I need to run it like 'python {script name}'. So > > I need to add Python to the path. How do I do this permanently > > without going to each computer and setting it through the GUI? I > > tried creating a Windows batch script using setx, but the user had to > > be an administrator. > > > Or is there any other way I can run whatever version of Python happens > > to be installed with a single command? Anyone have any ideas? Such a > > simple issue, there must be a simple solution. (of course, this is > > Windows). > > Assuming they have Python installed normally there will be file > associations set up for .py and .pyw, so all you need to do to type in > the script name: Python itself does not need to be in the path. > N.B. You do need to include the .py extension unless you can arrange to > edit the PATHEXT environment variable. > > e.g. > > C:\Temp>type t.py > import sys > print sys.version > > C:\Temp>t.py > 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit (Intel)] > > C:\Temp>assoc .py > .py=Python.File > > C:\Temp>ftype Python.File > Python.File="C:\Python25\python.exe" "%1" %* If your users aren't programmers, then why not just run Python over the network? That's what we do at my place of employment. The only machines that have Python actually installed are development machines. Mike From hjenea at earthlink.net Tue Jun 5 19:10:41 2007 From: hjenea at earthlink.net (Horace Enea) Date: Tue, 05 Jun 2007 16:10:41 -0700 Subject: copying generatrors Message-ID: Does anyone have code to copy a generator? Here is what I'd like to do: def foo(): yield 1 yield 2 yield 3 f = foo() g = copy(foo) print f.next() 1 print f.next() 2 print g.next() 1 Thanks, Horace From twisted0n3 at gmail.com Sat Jun 23 23:59:24 2007 From: twisted0n3 at gmail.com (Twisted) Date: Sun, 24 Jun 2007 03:59:24 -0000 Subject: The Modernization of Emacs: terminology buffer and keybinding In-Reply-To: References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182272495.990807.99110@a26g2000pre.googlegroups.com> <87tzt3ihev.fsf@kobe.laptop> <1182370216.961241.6960@n60g2000hse.googlegroups.com> <85zm2ufjpb.fsf@lola.goethe.zz> <1182372592.803332.288260@u2g2000hsc.googlegroups.com> <1182373919.262388.100740@c77g2000hse.googlegroups.com> <85r6o6fhkb.fsf@lola.goethe.zz> <1182375045.626510.188170@m36g2000hse.googlegroups.com> <85myyufgwj.fsf@lola.goethe.zz> <1182375528.985142.293900@q69g2000hsb.googlegroups.com> <1182545268.055596.228700@i38g2000prf.googlegroups.com> <1182547318.325617.16370@o11g2000prd.googlegroups.com> Message-ID: <1182657564.912472.55570@g4g2000hsf.googlegroups.com> On Jun 23, 10:36 am, Martin Gregorie wrote: > However, there's a case he missed, probably through never using a CAD > system. All the good ones can be driven either by mouse, or by > non-chorded key sequences or any combo the user likes. The essence of > CAD is very accurate pointing but all too many mice move slightly when > clicked. Fortunately a decent CAD system offers the possibility of > purely pointing with the mouse and doing everything else with the other > hand on the keyboard. The result is both fast and extremely accurate. Actually, what I prefer in (2D and 3D) visual design apps is the ability to snap to some kind of grid/existing vertices, and to zoom in close. Then small imprecisions in mouse movement can be rendered unimportant. > An interface design point that nobody has yet mentioned here is that > there are four different types of user that map onto a grid: > > casual dedicated > untrained 1 2 > expert 3 4 > > I first ran across grid this in "Design of Man-Computer Dialogs" by > James Martin and its been very useful in systems interface design. > > The problem with almost all current GUIs is that they are aimed at types > 1 and 3 users - this certainly applies to Windows, OS X and Gnome > desktops with the emphasis on type 1. vi and microEmacs, OTOH, are aimed > at type 3 and 4 users. The problem of course being the complete exclusion of type 1 users. Everyone starts out as type 1, and I don't think type 2 occurs in practise. You'd have to be some kind of religious nut to be "dedicated" while still "untrained", rather than only as a result of experience. Apps that provide no traction for a type 1 user will not see much adoption except in an environment of immersion, mentoring, or desperation. I wonder which of the three explains the majority of emacs users, and of vi users, and whether those prove to be the same one. :) (Actually, there'll be a single or a small number of class-2 users: the original developers, who presumably became dedicated before having much experience *using* the tool. Their experiences are atypical however, and their knowledge of the internals probably means they're type 4 by the time they actually use it to do more than debug it. Unsurprisingly, never experiencing it as a type 1 themselves they tend to be inconsiderate of future type 1 users...this is normal, and requires effort to avoid, in much the way blinkered views of stuff and seeing what you want to see can be normal, and efforts like using double-blind studies may be needed to avoid bias in evaluating, say, a new drug. That such efforts are needed should not be seen as disparaging the programmer or the drug-studier, but as merely reflecting human nature, and as a simple pragmatic requirement if one is to maximize utility.) > Its very difficult indeed to design an interface that suits both > untrained and expert users. One with a bog-standard UI but also a "console" or command prompt, scripting language, and customizable bindings? Funnily enough I can count the software I've seen with that range of capabilities (so able to satisfy type 1, 3, AND 4 users) on one hand. Here's the list, in fact: ROM BASICs and QBasic (on any really ancient microcomputer, and old pre-Windows PCs, respectively; the former came with printed manuals and you could just run prepackaged software from disks very easily; QBasic had mouse and menu support, but an immediate mode command line. You might not count ROM BASICS as as friendly, due to the lack of menus and such, but then at that time in history NOTHING had menus and such! And comprehensive introductory use manuals came with those, and with pre-Windows PCs (DOS also had a decent and easy to navigate help system). Most other BASICs and programming environments more generally lack an integrated environment with an immediate mode prompt. Eclipse actually sort of does, but the evaluate line can't be used really arbitrarily and I've found it touchy, and rarely use it. Hypercard (found commonly on old Macs; had a command prompt you could access to directly communicate to an interpreter). Fractint (fractal graphics making software for old pre-Windows PCs; had a similar prompt, accessed by typing 'g', but also had extensive help and menus readily controlled by stock keyboard commands such as the arrow keys, and later a Windows port with menus and mouse support). Quake and descendants (yes, the games. Easy to just use the menus and play the game. Advanced users could hit ~ to drop down a console and do a few things. Really advanced ones made config files to rebind weapons and make chat macros to fire off a taunting sentence with a single keystroke -- no more embarrassment getting fragged while typing it in longhand in mid-game. Super-advanced ones got at the QuakeC and made bots, flag-capture mode mods, and other enhancements and utilities. And sometimes cheats.) There's probably some more out there, but I've yet to see such desirable things as: * The paint program with the usual interface, except you can also do stuff like hit ~ and type "resample files:c:\foo\*.jpg width:640 height:480 preserveAspectRatio:true doNotEnlarge:false" * The word processor with the usual interface, except you can also do stuff like hit ~ and type "format leftIndent 2 where paragraph begins 'Quotation: '" * The word processor with the usual interface where I can define logical styles, then change them in only one place and affect every pre-existing occurrence retroactively. * The word processor with the usual interface where I can also view an underlying markup representation and hand-hack that, and which likely has the capabilities of the first two as a direct consequence of the implied architecture. Only please, proper functional markup, not macros like LaTeX or (shudder) winword. I don't want it to be possible for documents of dubious origin to make it start sneezing, or any of the general ugliness that follows TeX around like its shadow. Documents that look as nice when displayed and printed, sure, but just as nice under the hood if you please. * Something as powerful as Mathematica, but with a more straightforward basic-use interface as well as access to a fancy interpreter. * The operating system where you can do powerful stuff with a command line and a script or two, but can also get by without either. (Windows fails the former. Linux fails the latter.) * For that matter, the operating system whose GUI takes the concept behind OLE to its logical conclusion, and lets the user separately choose and configure their text editing, this-editing, that-editing, whosit-viewing, and the like components, and those components are used in building more complex applications. All the alternatives would of course adhere to a common interface for a particular sort of component, of course. (An OO language like Java lends itself to this, what with interfaces and inheritance and dynamic class loading!) When I run my browser and go to GG to make a post I'd get a text entry field that was actually my choice in a box, with the usual capabilities such as spellchecking available, and its own little menu bar at the top and suchlike. I'd be able to save the contents to disk without futzing around with the clipboard and launching Notepad, and later reload, in case the web site was prone to eating the odd submission. My Jave IDE would display code in the same editor (the interface should therefore support the using application externally driving coloring/highlighting, as well as jump-to-line and similar capabilities). Of course the editor wouldn't itself be Java-aware, which might not be useful, for example composing a usenet post. Instead it would provide a variety of abilities to the embedding application, which may or may not use them. What it would provide being its particular internal search, spell check, key bindings, etc. > About the closest I've seen have been > keyboard driven menu structures which have been designed so the user can > build their own "command sequences" that traverse menu levels without > showing the menus, as long as items are selected correctly from each > level. Many CAD systems approximate to this but I've yet to see a > graphical desktop, IDE, or editor menu structure that came close. The bog-standard alt, this, that sequences on Windows "come close"; they do make the menus display, but otherwise they do exactly what you want, and you can ignore the menus blinking around in your peripheral vision. When I go to save a file with unsaved changes my first inclination is ctrl+S; if the app doesn't support that the very next thing I try is alt, f, s, before resorting to the mouse. From bugmagnet at gmail.com Fri Jun 22 03:15:38 2007 From: bugmagnet at gmail.com (bugmagnet at gmail.com) Date: Fri, 22 Jun 2007 07:15:38 -0000 Subject: Internationalised email subjects In-Reply-To: <467B5D56.7060208@v.loewis.de> References: <1182337500.638044.63470@e9g2000prf.googlegroups.com> <46791592$0$5719$edfadb0f@dread14.news.tele.dk> <1182346499.123234.279880@e9g2000prf.googlegroups.com> <1182417604.446766.47660@e9g2000prf.googlegroups.com> <1182417823.793678.323530@a26g2000pre.googlegroups.com> <467B5D56.7060208@v.loewis.de> Message-ID: <1182496538.387301.122670@i38g2000prf.googlegroups.com> Thanks Martin, The "Some Chinese characters" are loaded from a MySQL table and are encoded in GB2312 format. I've added the following line at the top of the code: # -*- coding: GB2312 -*- I've also added the following line into the code: h = Header(subject.encode('GB2312'), 'GB2312') Note that the 'subject' variable consists of GB2312 encoded text, so I am not sure if it is necessary to call the subject.encode('GB2312') method. When I try to execute this code, I get the following error: File "/home/web88/html/app/test.py", line 17, in Header(subject.encode('GB2312'), 'GB2312') LookupError: unknown encoding: GB2312 Any idea what may be wrong? From steve at REMOVE.THIS.cybersource.com.au Sat Jun 23 21:17:40 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sun, 24 Jun 2007 11:17:40 +1000 Subject: Do eval() and exec not accept a function definition? (like 'def foo: pass) ? References: <1182628712.254361.79530@i38g2000prf.googlegroups.com> Message-ID: On Sat, 23 Jun 2007 19:58:32 +0000, vasudevram wrote: > > Hi group, > > Question: Do eval() and exec not accept a function definition? (like > 'def foo: pass) ? eval() is a function, and it only evaluates EXPRESSIONS, not code blocks. eval("2+3") # works eval("x - 4") # works, if x exists eval("print x") # doesn't work exec is a statement, and it executes entire code blocks, including function definitions, but don't use it. Seriously. ESPECIALLY don't use it if you are exec'ing data collected from untrusted users, e.g. from a web form. > I wrote a function to generate other functions using something like > eval("def foo: ....") > but it gave a syntax error ("Invalid syntax") with caret pointing to > the 'd' of the def keyword. You don't need eval or exec to write a function that generates other functions. What you need is the factory-function design pattern: def factory(arg): def func(x): return x + arg return func And here it is in action: >>> plus_one = factory(1) >>> plus_two = factory(2) >>> plus_one(5) 6 >>> plus_two(5) 7 -- Steven. From fred at adventistcare.org Mon Jun 25 12:47:17 2007 From: fred at adventistcare.org (Sells, Fred) Date: Mon, 25 Jun 2007 12:47:17 -0400 Subject: Help With Better Design Message-ID: > IMHO ... untested > > class LightBulb: > def __init__(self, on=False): self.IsOn = on > > def turnOn(self): self.switchIt(True) > def turnOff(self):self.switchIt(False) > > def switchIt(self, turnon): > if self.isOn==turnon: print "The Switch is Already %s" % (["ON", "OFF"][self.isOn]) > else: self.isOn = turnon #or alternatively =!self.isOn > > def __repr__(self): return ["ON", "OFF"][self.IsOn] > > > > > --- apollonius2 at gmail.com wrote: > > > > > > ON = "ON" > > > OFF = "OFF" > > > > > > class LightBulb: > > > def __init__(self, initial_state): > > > self.state = initial_state > > > > > > def TurnOn(self): > > > if self.state == OFF: > > > self.state = ON > > > else: > > > print "The Bulb Is Already ON!" > > > > > > def TurnOff(self): > > > if self.state == ON: > > > self.state = OFF > > > else: > > > print "The Bulb Is Aleady OFF!" > > > > > > > I've written code that looks a lot like that, and it's > > a perfectly acceptable pattern IMHO. I don't bother > > with the variables ON and OFF, though, as they add no > > clarity to simply using 'ON' and 'OFF' for the states. > > > > > > > [...] > > > The test portion of the code is actually longer than > > > the class > > > itself :-) > > > > That's usually a good thing! It means your code is > > concise, and your tests are exhaustive. (But that > > doesn't mean you can't also refactor your tests.) > > > > > > > > > > ______________________________________________________________ > > ______________________ > > Be a better Globetrotter. Get better travel answers from > > someone who knows. Yahoo! Answers - Check it out. > > http://answers.yahoo.com/dir/?link=list&sid=396545469 > > -- > > http://mail.python.org/mailman/listinfo/python-list > > > From mmanns at gmx.net Fri Jun 29 00:21:11 2007 From: mmanns at gmx.net (mmanns at gmx.net) Date: Fri, 29 Jun 2007 00:21:11 -0400 Subject: equality & comparison by default (was Re: Too many 'self' in python.That's a big flaw in this language.) References: <1182942154.185461.89620@e9g2000prf.googlegroups.com> <1i0cy8z.z94q5d1dxgexxN%aleax@mac.com> Message-ID: <20070629002111.0d35878e@localhost> On Fri, 29 Jun 2007 00:47:16 -0300 "Gabriel Genellina" wrote: > __hash__ and equality tests are used by the dictionary > implementation, and the default implementation is OK for immutable > objects. That is probably why inf == inf yields True. In this unique case, I do not like the default implementation. Martin From wim.vogelaaratmc2worlddotorg Sat Jun 16 03:03:13 2007 From: wim.vogelaaratmc2worlddotorg (Wim Vogelaar) Date: Sat, 16 Jun 2007 09:03:13 +0200 Subject: IndentationError: unexpected indent References: <467134fe$0$66966$dbd49001@news.wanadoo.nl> <5dfqgiF34u6dtU2@mid.individual.net> Message-ID: <46738b1e$0$12015$dbd4b001@news.wanadoo.nl> > How is he supposed to run MS notepad on X11? :) > I am saying MS notepad, but any software (running on Linux) showing you clearly the tabs will help. It would also be very convenient when python would deal with tabs in a human friendly way. Wim Vogelaar, http://home.wanadoo.nl/w.h.vogelaar/ From jstroud at mbi.ucla.edu Sat Jun 9 06:16:01 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sat, 09 Jun 2007 03:16:01 -0700 Subject: Python's "only one way to do it" philosophy isn't good? In-Reply-To: References: <1181368143.874341.273140@r19g2000prf.googlegroups.com> Message-ID: Terry Reedy wrote: > In Python, you have a choice of recursion (normal or tail) Please explain this. I remember reading on this newsgroup that an advantage of ruby (wrt python) is that ruby has tail recursion, implying that python does not. Does python have fully optimized tail recursion as described in the tail recursion Wikipedia entry? Under what circumstances can one count on the python interpreter recognizing the possibility for optimized tail recursion? James ===== Disclaimer: Mention of more than one programming language in post does not imply author's desire to begin language v. language holy battle. The author does not program in [some or all of the other languages mentioned aside from the language topical to the newsgroup] and has no opinions on the merits or shortcomings of said language or languages. ===== From g.brandl at gmx.net Thu Jun 7 15:22:34 2007 From: g.brandl at gmx.net (Georg Brandl) Date: Thu, 07 Jun 2007 21:22:34 +0200 Subject: Bragging about Python In-Reply-To: <46681369$0$12126$3b214f66@tunews.univie.ac.at> References: <46681369$0$12126$3b214f66@tunews.univie.ac.at> Message-ID: Mathias Panzenboeck schrieb: > Steve Howell schrieb: >> --- "pinkfloydhomer at gmail.com" >> wrote: >> >>> Is there a resource somewhere on the net that can be >>> used to quickly >>> and effectively show Python's strengths to >>> non-Python programmers? >>> Small examples that will make them go "Wow, that >>> _is_ neat"? >>> >> >> 15 small programs here: >> >> http://wiki.python.org/moin/SimplePrograms >> > > IMHO a few python goodies are missing there. "It's a Wiki." ;) Georg -- Thus spake the Lord: Thou shalt indent with four spaces. No more, no less. Four shall be the number of spaces thou shalt indent, and the number of thy indenting shall be four. Eight shalt thou not indent, nor either indent thou two, excepting that thou then proceed to four. Tabs are right out. From steve at REMOVE.THIS.cybersource.com.au Sat Jun 2 10:05:17 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sun, 03 Jun 2007 00:05:17 +1000 Subject: subexpressions References: Message-ID: On Sat, 02 Jun 2007 05:54:51 -0700, Steve Howell wrote: >> >> def f(x): y = x*x; return sin(y)+cos(y); >> > > Although I know valid trigonometry is not the point of > this exercise, I'm still trying to figure out why > anybody would ever take the square of an angle. > What's the square root of pi/4 radians? Approximately 0.886 radians. It corresponds to the angle of a point on the unit circle quite close to (sqrt(2/5), sqrt(3/5)), or if you prefer decimal approximations, (0.632, 0.775). Angles are real numbers (in the maths sense), so sqrt(pi/4) radians is just as reasonable an angle as pi/4 radians. Both are irrational numbers (that is, can't be written exactly as the ratio of two integers). -- Steven From senwin30 at gmail.com Thu Jun 28 19:07:25 2007 From: senwin30 at gmail.com (senthil arasu) Date: Thu, 28 Jun 2007 18:07:25 -0500 Subject: HTML Page Rendering Support in WxPython Frame Message-ID: <1ef9860e0706281607j25a44862jf1db3289fb30d3e3@mail.gmail.com> Hi, Currently Iam integrating GUI Framework in Python. As per design design,I need to use tab buttons to launch different HTML pages in same frame(without launching seperate window ). I have already tried with webbrowser class & WxPython GUI kit. Iam unable to get the expected result. I am wanted to be clear..!whether python supports my design or i need to go for some other option I need somebody to help me. thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: From cbigam at somewhereelse.nucleus.com Fri Jun 22 12:11:58 2007 From: cbigam at somewhereelse.nucleus.com (Colin B.) Date: Fri, 22 Jun 2007 16:11:58 GMT Subject: I need some cleanings tips and advice. References: <1182528064.446459.49420@n2g2000hse.googlegroups.com> Message-ID: <467bf4c9@news.nucleus.com> In comp.lang.perl.misc CleaningTips at gmail.com wrote: > Me and my buddy made a website called www.stupidpinheads.com, its > basically a free forum and free blog driven web site dedicated as a > source people can goto to find out how to clean and remove stains from > pretty much anything. Problem is, as of yet, you couldn't find out how > to clean anything right now cause the site is new and no one has found > it yet. Let's see if I get this right. You create a website for a subject that you know nothing about. Then you try to solicit content in a bunch of programming language newsgroups. Wow, that's pretty pathetic, even for a google-groups poster! Begone with you. From steve at holdenweb.com Mon Jun 18 21:46:54 2007 From: steve at holdenweb.com (Steve Holden) Date: Mon, 18 Jun 2007 21:46:54 -0400 Subject: List sequential initialization In-Reply-To: <4866bea60706121326k25215c12l6a6578138d840242@mail.gmail.com> References: <1181670619.086709.116730@g37g2000prf.googlegroups.com> <466ee02b$0$10192$9b4e6d93@newsspool4.arcor-online.net> <1181675079.553239.43010@d30g2000prg.googlegroups.com> <4866bea60706121326k25215c12l6a6578138d840242@mail.gmail.com> Message-ID: Chris Mellon wrote: > On 6/12/07, HMS Surprise wrote: >> Thanks for the explaination. It didn't seem natural and from the >> tutorial I read: >> >> A value can be assigned to several variables simultaneously: >> >> >>> x = y = z = 0 # Zero x, y and z >> >> >> Maybe I infer too much.... >> > > And yet, your answer is right there. > > "A value can be assigned to several variables simultaneously" > > When you say want a value assigned to several variables, Python > doesn't assume that you actually mean you want 2 different values > assigned to them. The crucial difference between a = b = "ab" a = "a" and a = b = ['a', 'b'] a.append('c') is that in the first case two names are bound to the immutable object "ab". Then the first name is rebound to a different immutable object. In the second example, both names are bound to the same mutable object, a list. That object is then modified. The modification can be performed using either name, and both names continue to point to the same (but now mutated) object. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From MI5Victim at mi5.gov.uk Fri Jun 22 22:18:12 2007 From: MI5Victim at mi5.gov.uk (MI5Victim at mi5.gov.uk) Date: 23 Jun 2007 02:18:12 GMT Subject: MI5 Persecution: A new Kafka? 3/10/95 (5104) Message-ID: Newsgroups: uk.misc,soc.culture.british,uk.media,uk.politics From: jackson at soldev.tti.com (Dick Jackson) Subject: Re: What it's like to be watched by the security services Message-ID: <1995Oct13.225312.6514 at ttinews.tti.com> Sender: usenet at ttinews.tti.com (Usenet Admin) Nntp-Posting-Host: soldev Organization: Citicorp-TTI at Santa Monica (CA) by the Sea References: <813188298snz129.os2.7 at blackcat.demon.co.uk> Date: Fri, 13 Oct 1995 22:53:12 GMT Lines: 34 In article bu765 at torfree.net (Mike Corley) writes: > >Strangers in the street have recognized me on sight many times, and shown >awareness of the current thread of abuse. To give you one example, in 1992 >I was seriously ill, and a manager at work somewhat humouroursly said that >"it wasn't fair" that people were bullying me. A few days later, I >attended for the first time a clinic in London as an outpatient, and on my >way out was accosted by someone who asked if "they had paid my fare", with >emphasis on the word "fare". He repeated the word several times in this >different context; that they should have paid my "fare", each time >emphasising the word. > >For two and a half years from the time their harassment started until >November 1992 I refused to see a psychiatrist, because I reasoned that I >was not ill of my own action or fault, but through the stress caused by >harassment, and that a lessening of the illness would have to be >consequent to a removal of its immediate cause, in other words a cessation >of harassment. I also reasoned that since they were taunting me with jokes >about mental illness, if I were to seek treatment then the abusers would >think that they had "won" and been proved "right". I have so far not contributed to this tread, it has been unpleasant in my opinion. However, I was struck by the resemblance of the above passages to the writing of Franz Kafka. Viz. while from an objective viewpoint it seems to refer to a abnormal world, in a strange way it does resonate strongly at other levels. Mr. Corley, have you tried to write for publication? I honestly think it might lead somewhere positive. Dick Jackson (serious for a change and expecting to get beaten up) 5104 From kyosohma at gmail.com Fri Jun 22 10:05:10 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Fri, 22 Jun 2007 14:05:10 -0000 Subject: rsync module? In-Reply-To: References: Message-ID: <1182521110.194346.212670@k79g2000hse.googlegroups.com> On Jun 21, 7:40 pm, "Evan Klitzke" wrote: > Are there any python modules for accessing rsync from python? I would > like to be able to rsync files from a python script to a remote server > running an rsync daemon. I'm well aware that I can invoke rsync using > subprocess, os.system, etc., but I am curious if there is a way to do > it directly. > > -- > Evan Klitzke I found the following doing a quick Google search: http://www.vdesmedt.com/~vds2212/rsync.html http://freshmeat.net/projects/pysync/ http://www.nongnu.org/rdiff-backup/ Mike From martin at see.sig.for.address Mon Jun 25 13:36:33 2007 From: martin at see.sig.for.address (Martin Gregorie) Date: Mon, 25 Jun 2007 18:36:33 +0100 Subject: Portable general timestamp format, not 2038-limited In-Reply-To: <20070625133843.9e25d0ab.steveo@eircom.net> References: <1182544384.709759.235300@o11g2000prd.googlegroups.com> <20070625133843.9e25d0ab.steveo@eircom.net> Message-ID: <82b5l4-tvh.ln1@zoogz.gregorie.org> Steve O'Hara-Smith wrote: > On Mon, 25 Jun 2007 11:17:27 GMT > Roedy Green wrote: > >> On Sun, 24 Jun 2007 18:14:08 -0700, rem642b at yahoo.com (Robert Maas, >> see http://tinyurl.com/uh3t) wrote, quoted or indirectly quoted >> someone who said : >> >>> - Stick to astronomical time, which is absolutely consistent but >>> which drifts from legal time? >> depends what you are measuring. IF you are doing astronomy, your >> advice would apply. If you are doing payrolls, you want effectively to >> pretend the leap seconds never happened, just as Java does. > > Which leaves you about 30 seconds out by now - smelly. > Easy solution: always read Zulu time directly from a recognized real-time clock and store the result in a database as a ccyymmddhhmmssfff ASCII string where fff is milliseconds). By "recognized real-time clock) that I mean an atomic clock and distribution network such as GPS or (in the UK or Germany) an MSF low frequency radio broadcast. NTP using tier-1 sources may do the job too. The clock interface may need to be JINI because most suitable receivers have serial interfaces. This is certainly accurate for financial transactions: the UK CHAPS inter-bank network has a Rugby MSF receiver in each bank's gateway computer and uses that for all timestamps. -- martin@ | Martin Gregorie gregorie. | Essex, UK org | From jackie_python at yahoo.ca Sun Jun 24 15:24:20 2007 From: jackie_python at yahoo.ca (Jackie Wang) Date: Sun, 24 Jun 2007 15:24:20 -0400 (EDT) Subject: dealing with emf/wmf files Message-ID: <689380.74244.qm@web57504.mail.re1.yahoo.com> I'd like to put some emf/wmf pictures into a pdf file using 'reportlab', but the Python Imaging Library cannot recognize emf files. The wmf files are said to be 'identified only'. Therefore, the following code does not work: from reportlab.pdfgen import canvas from reportlab.lib.pagesizes import letter width, height = letter # (595.27,841.89) def hello(c): c.drawImage(r'D:\01.wmf',1,1,height,width) c = canvas.Canvas('hello.pdf', pagesize=(height,width)) hello(c) c.showPage() c.save() I do not want to convert the pictures into other formats, e.g. jpg which will lower the quality. Is there any way to get around with this problem? Thanks! Get news delivered with the All new Yahoo! Mail. Enjoy RSS feeds right on your Mail page. Start today at http://mrd.mail.yahoo.com/try_beta?.intl=ca From bj_666 at gmx.net Fri Jun 22 13:56:52 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Fri, 22 Jun 2007 19:56:52 +0200 Subject: comparing two lists and returning "position" References: <1182481876.028589.71710@x35g2000prf.googlegroups.com> <7xvedg4n2d.fsf@ruckus.brouhaha.com> <467b624e$0$16271$c30e37c6@lon-reader.news.telstra.net> <1182493019.795629.108860@w5g2000hsg.googlegroups.com> <1182534010.884992.119690@u2g2000hsc.googlegroups.com> Message-ID: In <1182534010.884992.119690 at u2g2000hsc.googlegroups.com>, hiro wrote: > Hi once again, Charles.. I have tried your approach in my data set l2 > and it keeps crashing on me, > bare in mind that I have a little over 10 million objects in my list > (l2) and l1 contains around 4 thousand > objects.. (i have enough ram in my computer so memory is not a > problem) > > python 2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit > (Intel)] on win32 > > error is : ValueError: list.index(x): x not in list So you are saying you get this error with the value of `x` actually in the list!? Somehow hard to believe. Ciao, Marc 'BlackJack' Rintsch From showell30 at yahoo.com Wed Jun 13 06:21:17 2007 From: showell30 at yahoo.com (Steve Howell) Date: Wed, 13 Jun 2007 03:21:17 -0700 (PDT) Subject: SimplePrograms challenge In-Reply-To: <466F9329.2020306@gmail.com> Message-ID: <760775.10923.qm@web33501.mail.mud.yahoo.com> --- Steven Bethard wrote: > Stefan Behnel wrote: > > Steven Bethard wrote: > >> If you want to parse invalid HTML, I strongly > encourage you to look into > >> BeautifulSoup. Here's the updated code: > >> > >> import ElementSoup # > http://effbot.org/zone/element-soup.htm > >> import cStringIO > >> > >> tree = > ElementSoup.parse(cStringIO.StringIO(page2)) > >> for a_node in tree.getiterator('a'): > >> url = a_node.get('href') > >> if url is not None: > >> print url > >> > [snip] > > > > Here's an lxml version: > > > > from lxml import etree as et # > http://codespeak.net/lxml > > html = et.HTML(page2) > > for href in html.xpath("//a/@href[string()]"): > > print href > > > > Doesn't count as a 15-liner, though, even if you > add the above HTML code to it. > > Definitely better than the HTMLParser code. =) > Personally, I still > prefer the xpath-less version, but that's only > because I can never > remember what all the line noise characters in xpath > mean. ;-) > I think there might be other people who will balk at the xpath syntax, simply due to their unfamiliarity with it. And, on the other hand, if you really like the xpath syntax, then the program really becomes more of an endorsement for xpath's clean syntax than for Python's. To the extent that Python enables you to implement an xpath solution cleanly, that's great, but then you have the problem that lxml is not batteries included. I do hope we can find something to put on the page, but I'm the wrong person to decide on it, since I don't really do any rigorous HTML screen scraping in my current coding. (I still think it's a common use case, even though I don't do it myself.) I suggested earlier that maybe we post multiple solutions. That makes me a little nervous, to the extent that it shows that the Python community has a hard time coming to consensus on tools sometimes. This is not a completely unfair knock on Python, although I think the reason multiple solutions tend to emerge for this type of thing is precisely due to the simplicity and power of the language itself. So I don't know. What about trying to agree on an XML parsing example instead? Thoughts? ____________________________________________________________________________________ Pinpoint customers who are looking for what you sell. http://searchmarketing.yahoo.com/ From avelldiroll at yahoo.fr Wed Jun 13 13:10:41 2007 From: avelldiroll at yahoo.fr (Avell Diroll) Date: Wed, 13 Jun 2007 19:10:41 +0200 Subject: Bytes/File Size Format Function In-Reply-To: <87r6oguru2.fsf@benfinney.id.au> References: <1181706472.008233.80050@a26g2000pre.googlegroups.com> <87r6oguru2.fsf@benfinney.id.au> Message-ID: <46702511.7010905@yahoo.fr> Ben Finney wrote: > The symbol for "bit" is 'b'. The symbol for "byte" is 'B'. 'kb' is > 'kilobit', i.e. 1000 bits. 'mb' is a "metre-bit", a combination of two > units. And so on. The SI units have definitions that are only muddied > by misusing them this way. I have to disagree: 'mb' should stand for "milli-bit" :) which could be considered as the probability of a bit ... this might be useful for quantum computing. From steve at REMOVE.THIS.cybersource.com.au Tue Jun 12 19:24:58 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Wed, 13 Jun 2007 09:24:58 +1000 Subject: Postpone creation of attributes until needed References: <1181553891.447344.109390@g4g2000hsf.googlegroups.com> <1181559496.911368.219210@p77g2000hsh.googlegroups.com> <1181564855.890242.116840@m36g2000hse.googlegroups.com> <1181626546.323759.80500@i13g2000prf.googlegroups.com> <1181663591.272374.156010@d30g2000prg.googlegroups.com> Message-ID: On Tue, 12 Jun 2007 08:53:11 -0700, Frank Millman wrote: >> Since, as far as I can tell, there is no minimum time between creating the >> instance at (1) and trying to access instance.y at (2), there is no >> minimum time between (1) and calling compute() at (4), except for the >> execution time of the steps between them. So why not just make compute() >> the very last thing that __init__ does? >> > > I wrote a long reply to this about an hour ago, but Google Groups > seems to have eaten it. I hope I can remember what I wrote. > > This is more like what I am doing - > > (t=table, c=column, p=pseudo column) > > (1) the caller initializes table t1 and columns c1-c10 > (2) the caller initializes table t2 and columns c11-c20 > (3) t2.__init__() creates a link to t1, and updates t1 with a link to > t2 > (4) t2.__init__() creates a link from c12 to c3, and updates c3 with a > link to c12 > (5) t2.__init__() creates pseudo column p1 on table t1, creates a link > from c14 to p1, updates p1 with a link to c14 > > This all works well, and has been working for some time. Ah, if I had ever read that there were two instances involved, I hadn't noticed. Sorry! > You can already see a difference between your scenario and mine. > Various attributes are set up *after* the original __init__() method > has completed. By "original" I guess you mean t1. I also assume that both t1 and t2 are instances of the same Table class. Here are some thoughts: - Don't ask the caller to initiate t1 and t2 (steps 1 and 2 above). Instead, write a function which does all the initiation (steps 1 through 5) and returns a tuple (t1, t2). That way, your initiate function ("make_tables" perhaps?) can do all the setup needed before the caller starts using either t1 or t2. - How does t2 know about t1? As a named global variable? If so, there is probably a better way, maybe something like this: class Table(object): def __init__(self, start_column, end_column, sibling=None): self.columns = [] for i in range(start_column, end_column): self.columns.append(get_a_column(i)) self.sibling = sibling if sibling is not None: # I am the sibling of my sibling sibling.sibling = self # make links between columns self.columns[12].make_link(sibling.columns[3]) sibling.columns[3].make_link(self.columns[12]) # create pseudo-columns (whatever they are!) sibling.p1 = contents_of_pseudo_column() self.columns[14].make_link(sibling.p1) sibling.p1.make_link(self.columns[14]) Now you call them like this: t1 = Table(1, 11) t2 = Table(11, 21, t1) # and now everything is initiated and ready to use... - If both tables t1 and t2 need to exist, it should be an error to use t1 without creating t2, or vice versa. An easy check for that will be: if self.sibling is None: raise TableError('no sibling') - Most importantly... I hope you are getting some benefit from all this extra work needed to support splitting the columns across two instances. > I have now added a complication. > > I want to create a t3 instance, with columns c21-c30, and I want to > create a pseudo column p2 on table t2, exactly as I did in steps 2 to > 5 above. I also want to change step 5 so that instead of linking p1 on > table 1 to c14 on table 2, I link it to p2 on table 2. However, at > that point, p2 does not exist. Perhaps each table needs two siblings, a left and a right. Should it be circular? As in t1 <-> t2 <-> t3 <-> t1. Or perhaps your requirement is that each table must have _at least_ one sibling, but not necessarily two. Either way, changing the magic constants 3, 12 and 14 above into either arguments or calculated values should allow you to make the code general enough to have any number of tables. Another suggestion: factor out the "make these two tables siblings" bits out of the __init__, so you can do this: def create_tables(): t1 = Table(1, 11) t2 = Table(11, 21) t3 = Table(21, 31) make_sibling(t1, t2) make_sibling(t2, t3) return (t1, t2, t3) t1, t2, t3 = create_Tables() As before, it is an error to access the data in a half-initiated table. But since the caller is not expected to create table instances themselves, but only call the create_table() function, that is never a problem. -- Steven. From frank at chagford.com Fri Jun 29 08:51:53 2007 From: frank at chagford.com (Frank Millman) Date: Fri, 29 Jun 2007 05:51:53 -0700 Subject: What happens to a thread with an unhandled exception? Message-ID: <1183121513.335933.101000@u2g2000hsc.googlegroups.com> Hi all I am doing something which works, but I have a gut feel that it cannot be relied upon. Can someone confirm this one way or the other. I have a multi-threaded server, which responds to client logins and sets up a thread for each active session. A thread can stay active for a long time. I use a subclass of threading.Thread to handle the session, to which I have added a number of attributes and methods, plus a reference back to the main thread. When a user logs in, I call a 'setup' method in the thread, which among other things updates a dictionary in the main thread to record the fact that they are logged in. When they log out, I call a 'cleanup' method in the thread, which among other things removes their id from the dictionary of active logins. It sometimes happens that an unhandled exception occurs in a thread. The main thread continues, other threads are unaffected, and users can continue to log in. However, the user that was active at the time cannot log back in as their cleanup method was never called. There are a number of ways to handle this, but I found one which seems quite effective. In the dictionary of active logins, I store a reference to the thread which is managing the session. If the user tries to log back in, I can detect that the thread is in a suspended state, and I use the reference to invoke the thread's cleanup method. This removes the entry from the dictionary of active logins and enables the user to log in again successfully. My worry is that the thread with the unhandled exception may eventually get garbage-collected, in which case the cleanup method will no longer be accessible. Could this happen, or does the thread stay in memory until termination of the main program? Thanks for any pointers. Frank Millman From gagsl-py2 at yahoo.com.ar Tue Jun 19 23:05:03 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 20 Jun 2007 00:05:03 -0300 Subject: Q: listsort and dictsort - official equivalents? References: <1182302544.4202.40.camel@delta.sgr-a.net> <740c3aec0706191757i43204155o89f4b37ed0bc68eb@mail.gmail.com> Message-ID: En Tue, 19 Jun 2007 21:57:30 -0300, BJ?rn Lindqvist escribi?: > It's not true that the sort must complete (or that the whole file must > be read for that matter), Python has cool generators which makes the > above possible. That's not possible, the input must be read completely before sorted() can output anything. Suppose the minimum element is at the end - until you read it, you can't output the very first sorted element. -- Gabriel Genellina From half.italian at gmail.com Mon Jun 4 22:03:04 2007 From: half.italian at gmail.com (half.italian at gmail.com) Date: Tue, 05 Jun 2007 02:03:04 -0000 Subject: get_traceback In-Reply-To: References: <1180977780.997361.133320@g37g2000prf.googlegroups.com> Message-ID: <1181008984.098975.152110@a26g2000pre.googlegroups.com> On Jun 4, 3:51 pm, "Gabriel Genellina" wrote: > En Mon, 04 Jun 2007 14:23:00 -0300, escribi?: > > > Is there a function or idoim for returning an exception/traceback > > rather than just printing it to stdout? I'm running a deamon where > > stdout is going to /dev/null, and I'm not even watching it..until > > now. All the functions I found in traceback and sys seemed only to > > print the error rather than just returning it, so I resorted to this: > > Read again the docs for the traceback module. > Maybe you are looking for traceback.format_exception(*sys.exc_info()) or > traceback.format_exc() > > > f = tempfile.TemporaryFile(mode='w+') > > sys.stdout = f > > traceback.print_tb(sys.exc_info()[2]) > > In this case you can use StringIO instead of a temporary file, and the > file argument to print_tb instead of swapping sys.stdout > > -- > Gabriel Genellina Thanks Gabriel. That was exactly what I was looking for. Also, I'm glad to make a connection to the StringIO class. I'm sure I will remember it the next time I need it. ~Sean From python-url at phaseit.net Mon Jun 11 09:23:31 2007 From: python-url at phaseit.net (Gabriel Genellina) Date: Mon, 11 Jun 2007 13:23:31 +0000 (UTC) Subject: Python-URL! - weekly Python news and links (Jun 11) Message-ID: QOTW: "That's the Martellibot for you. Never use a word where a paragraph with explanatory footnotes will do. Sigh. I miss him on c.l.py." - Simon Brunning "Conclusion: advice to 'try Python for yourself' is apt in a way the original questioner might not realize." - Cameron Laird A small survey revealing so many people using Python for so many different tasks... http://groups.google.com/group/comp.lang.python/browse_thread/thread/64b947bf0d77a9da/ "Bragging about Python": A call for good examples to impress non-Pythoneers generates a nice and compact solution to the 8 Queens problem by Paul McGuire. http://groups.google.com/group/comp.lang.python/browse_thread/thread/61c10896866425f6/ Naming conventions again: this time, how people construct meaningful names, and what they consider a "good" name: http://groups.google.com/group/comp.lang.python/browse_thread/thread/4f1610900da8f4bb/ Several attempts to speed up date conversions - and at the end, perhaps one doesn't even *need* the conversion at all! http://mail.python.org/pipermail/python-list/2007-June/444306.html If you thought that you could not use multiple Python interpreters inside the same process, you were wrong, and this is how to do it: http://groups.google.com/group/comp.lang.python/browse_thread/thread/4ac31cd3a389a4d8/ Did you know that you could skip a value using string interpolation? Here is the trick: http://groups.google.com/group/comp.lang.python/browse_thread/thread/79bb6c636f8710bb/ ======================================================================== 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. The Python Papers aims to publish "the efforts of Python enthusiats". http://pythonpapers.org/ 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 Steve Bethard continues the marvelous tradition early borne by Andrew Kuchling, Michael Hudson, Brett Cannon, Tony Meyer, and Tim Lesher of intelligently summarizing action on the python-dev mailing list once every other week. http://www.python.org/dev/summary/ The Python Package Index catalogues packages. http://www.python.org/pypi/ The somewhat older Vaults of Parnassus ambitiously collects references to all sorts of Python resources. http://www.vex.net/~x/parnassus/ Much of Python's real work takes place on Special-Interest Group mailing lists http://www.python.org/sigs/ 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 horpner at yahoo.com Tue Jun 19 14:04:58 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Tue, 19 Jun 2007 18:04:58 GMT Subject: Python's "only one way to do it" philosophy isn't good? References: <1181368143.874341.273140@r19g2000prf.googlegroups.com> Message-ID: On 2007-06-19, Douglas Alan wrote: > "Terry Reedy" writes: >> At the end, I added as a *side note* the irony that the >> purported author was the co-developer of Scheme, another >> 'minimalist algorithm language > > Sussman's statements are not ironic because Scheme is a > language that is designed to be extended by the end-user (even > syntactically), while keeping the core language minimal. This > is a rather different design philosophy from that of Python. Which version Scheme, though? Scheme has only formally had macros since R4RS, and then only as an extension. Macros are an extension to Scheme, rather than a founder. Python could conceivably end up in the same position 15 years from now, with macros a well-established late-comer, as generators have become. > I suggest that you haven't yet grokked the Weltanschauung of > Scheme. Scheme aficionados would not typically insist that a > proposed language feature is not good because it violates > anything like an "only one obvious way" rule. Rather they > would argue that if it can be implemented as fuctions and/or > macros, then it *should* be implemented that way, rather than > polluting the core language. The new facility should then be > included in a library. The SRFIs are cool. The last time I dipped my toe into the Scheme newsgroup, I was overwhelmed by the many impractical discussions of Scheme's dark corners. Python is either much more free of dark corners, or else simply doesn't attract that kind of aficionado. -- Neil Cerutti Let us join David and Lisa in the celebration of their wedding and bring their happiness to a conclusion. --Church Bulletin Blooper From ross at heth.eclipse.co.uk Sat Jun 30 10:32:22 2007 From: ross at heth.eclipse.co.uk (Ross Hetherington) Date: Sat, 30 Jun 2007 15:32:22 +0100 Subject: linecache and comparison with input In-Reply-To: References: Message-ID: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA512 Sebastian Wiesner wrote: > Then you will see, that getline returns the line *including the newline > character*, while raw_input does not. Use line.strip('\n') to remove > trailing newline characters from the return value of getline. Ah, thank you. I did notice that getline left a trailing newline, but I didn't realise raw_input didn't. Ooops. -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.7 (GNU/Linux) Comment: Using GnuPG with Fedora - http://enigmail.mozdev.org iD8DBQFGhml20HlvQApfM3gRCozzAJ0QAENDkQn8StlEr9Mh0yoCCkUhzQCcCmOC 5tPusqS4MwnisNLZmtKc3Y4= =hlHr -----END PGP SIGNATURE----- From kinch1967 at gmail.com Fri Jun 1 04:42:03 2007 From: kinch1967 at gmail.com (bullockbefriending bard) Date: Fri, 01 Jun 2007 08:42:03 -0000 Subject: speeding things up with C++ In-Reply-To: References: <1180171179.687276.77930@z28g2000prd.googlegroups.com> <1180608332.725330.306800@z28g2000prd.googlegroups.com> Message-ID: <1180687323.534258.323630@q19g2000prn.googlegroups.com> > Are you sure you want an STL container? Since the primary operator > here is Python, the extra benefits from the STL container over plain C > arrays isn't as evident. > > Pyrex is a good way to write the interface between your C++ code and > the Python code - it handles the refcounting and boilerplate for you - > and perhaps for writing the algorithms as well, depending on how > complicated and performance sensitive they are. good point. while i bow to the genius of the folks who invented template metaprogramming, the compiler error messages tend to be profoundly depressing :). one way or the other, pyrex is something i need to learn since i'm now completely enamoured with python and had better develop an arsenal of tricks for the rare times when it's just not fast enough. > Also, using numeric/Numarray can be a very big win. It can potentially > save you a fair amount of marshalling overhead. as i understand it, this is so for applying the likes of matrix operations, autocorrelations, FFTs, etc...where python essentially provides scripting glue to some highly optimised C functions. i'm assuming that the kind of algorithm i am looking at which involves some set operations on list elements + copying between lists isn't going to be helped so much by using numpy or similar. From mclaugb at nospm.yahoo.com Tue Jun 19 11:12:23 2007 From: mclaugb at nospm.yahoo.com (mclaugb) Date: Tue, 19 Jun 2007 16:12:23 +0100 Subject: ctypes pointer Message-ID: I have a simple function void adder(double a, double b, double *c){ *c = a+b; } i have created a shared dll -- "small_dll4.dll" of it using visual studio. now i wish to call it from python. to do so, i have done the following: libx = cdll("small_dll4.dll", RTLD_GLOBAL) libx.adder.argtypes = [c_double, c_double, POINTER(c_double)] libx.adder.restype = None size=c_double() zz=libd.adder(3.342, 4, byref(size)) and the result is an access violation! File "", line 0, in __main__ WindowsError: exception: access violation reading 0x7EF9DB23 I cant figure out what is causing this. thanks in advance, Bryan From bretthoerner at bretthoerner.com Mon Jun 18 17:57:37 2007 From: bretthoerner at bretthoerner.com (Brett Hoerner) Date: Mon, 18 Jun 2007 21:57:37 -0000 Subject: getting the size of an object In-Reply-To: References: <1182182932.947333.251020@o61g2000hsh.googlegroups.com> Message-ID: <1182203857.275327.235380@u2g2000hsc.googlegroups.com> On Jun 18, 2:48 pm, "filox" wrote: > is there a long answer? what i want is to find out the number of bytes the > object takes up in memory (during runtime). since python has a lot of > introspection mechanisms i thought that should be no problem... There isn't an automatic way through the language afaik. I think allocating memory in order to keep track of how much memory you have allocated can begin to be a problem. And most people just don't care down to each and every byte. :) Some helpful information here: http://groups.google.com/group/comp.lang.python/browse_thread/thread/a7b9f3c03fb49aa/0e793beec82884f0?lnk=gst&q=size+object&rnum=4#0e793beec82884f0 Brett From bbxx789_05ss at yahoo.com Tue Jun 26 02:09:53 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: Mon, 25 Jun 2007 23:09:53 -0700 Subject: can't start Apache on Mac OS X--no listening sockets available? In-Reply-To: <1182826067.067254.247940@j4g2000prf.googlegroups.com> References: <1182824632.015853.317970@g4g2000hsf.googlegroups.com> <1182826067.067254.247940@j4g2000prf.googlegroups.com> Message-ID: <1182838193.195172.206160@u2g2000hsc.googlegroups.com> > On Jun 25, 7:23 pm, 7stud wrote: > > > > > I'm trying to get Apache set up on my system so I can use mod_python. > > I installed Apache 2.2.4 according to the following instructions: > > >http://switch.richard5.net/isp-in-a-box-v2/installing-apache-on-mac-o... > > > and everything seemed to install correctly, but I can't start Apache. > > I typed in the following command: > > > $ sudo /Library/Apache2/bin/apachectl start > > Password: > > > and I got this error message: > > > httpd: Could not reliably determine the server's fully qualified > > domain name, using tms-computer.local for ServerName > > (48)Address already in use: make_sock: could not bind to address > > 0.0.0.0:80 > > no listening sockets available, shutting down > > Unable to open logs > > > Any ideas? > > Do you have "Web Sharing" in the prefs on as well? I checked and to my surprise Personal Web Sharing was turned on. I was messing around with it yesterday because I thought that might have something to do with my problems, but I couldn't get Personal Web Sharing to start--it just said "Web Sharing starting up...", and it never did. Anyway, I turned Personal Web Sharing off, and then the error message changed to this: $ sudo /Library/Apache2/bin/apachectl start Password: httpd: Could not reliably determine the server's fully qualified domain name, using tms-computer.local for ServerName However, I checked the All Processes page in the Activity Monitor, and it said httpd was running. So I tested my apache installation by typing http:/localhost in Safari's address bar, and a page displayed saying "It works!". But I wondered if that page was being served up by the pre-installed version of Apache or my new installation. So, I went into my new installation's directory and looked at the file: /Library/Apache2/htdocs/index.html and changed the text from "It works!" to "Apache 2.2.4", but when I retyped http:/localhost in Safari's address bar, I still got a page saying "It works!", so that page is not being served by my new installation. From CRhode at LacusVeris.com Tue Jun 5 14:48:30 2007 From: CRhode at LacusVeris.com (Chuck Rhode) Date: Tue, 05 Jun 2007 13:48:30 -0500 Subject: Python 3000: Standard API for archives? References: <%aT8i.12569$rO7.12072@newssvr25.news.prodigy.net> Message-ID: Tim Golden wrote this on Mon, 04 Jun 2007 15:55:30 +0100. My reply is below. > Chuck Rhode wrote: >> samwyse wrote this on Mon, 04 Jun 2007 12:02:03 +0000. My reply is >> below. >>> I think it would be a good thing if a standardized interface >>> existed, similar to PEP 247. This would make it easier for one >>> script to access multiple types of archives, such as RAR, 7-Zip, >>> ISO, etc. >> Gee, it would be great to be able to open an archive member for >> update I/O. This is kind of hard to do now. If it were possible, >> though, it would obscure the difference between file directories >> and archives, which would be kind of neat. Furthermore, you could >> navigate archives of archives (zips of tars and other >> abominations). > Just put something together a module called "archive" or whatever, > which exposes the kind of API you're thinking of, offering support > across zip, bz2 and whatever else you want. Put it up on the > Cheeseshop, announce it on c.l.py.ann and anywhere else which seems > apt. See if it gains traction. Take it from there. > NB This has the advantage that you can start small, say with zip and > bz2 support and maybe see if you get contributions for less common > formats, even via 3rd party libs. If you were to try to get it into > the stdlib it would need to be much more fully specified up front, I > suspect. Yeah, this is in the daydreaming stages. I'd like to maintain not-just-read-only libraries of geographic shapefiles, which are available free from governmental agencies and which are riddled with obvious errors. Typically these are published in compressed archives within which every subdirectory is likewise compressed (apparently for no other purpose than a rather vain attempt at flattening the directory structure, which must be reconstituted on the User's end anyway). Building a comprehensive index to what member name(s) the different map layers (roads, political boundaries, watercourses) have in various political districts of varying geographic resolutions is much more than merely frustrating. I've given it up. However, I believe that once I've located something usable, the thing to do is save a grand unified reference locator (GURL) for it. The GURL would specify a directory path to the highest level archive followed by a (potential cascade of) archive member name(s for enclosed archives) of the data file(s) to be operated on. Unpacking and repacking would be behind the scenes. Updates (via FTP) of non-local resources would be transparent, too. I think, though, that notes about the publication date, publisher, resolution, area covered, and format of the map or map layer ought to be kept out of the GURL. My whole appetite for this sort of thing would vanish if access to the shapefiles were more tractable to begin with. -- .. Chuck Rhode, Sheboygan, WI, USA .. 1979 Honda Goldwing GL1000 (Geraldine) .. Weather: http://LacusVeris.com/WX .. 52? ? Wind N 9 mph ? Sky overcast. From tjreedy at udel.edu Tue Jun 19 18:21:02 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 19 Jun 2007 18:21:02 -0400 Subject: Python's "only one way to do it" philosophy isn't good? References: <1181368143.874341.273140@r19g2000prf.googlegroups.com> Message-ID: "Douglas Alan" wrote in message news:lcr6o7g7zf.fsf at gaffa.mit.edu... || But it wasn't based on a "misquote of Tim Peters"; it was based on an | *exact* quotation of Tim Peters. My mistake. The misquotation is in the subject line and other's posts here and in other threads. | > and a mischaracterization of Python Nonetheless, picking on and characterizing Tim's statement as anti-flexibility and un-scientific is to me writing of a sort that I would not tolerate from my middle-school child. I checked the context of the quote, page 3 (and 4) of http://swiss.csail.mit.edu/classes/symbolic/spring07/readings/robust-systems.pdf "(3)Indeed, one often hears arguments against building flexibility into an engineered system. For example, in the philosophy of the computer language Python it is claimed: 'There should be one - and preferably only one - obvious way to do it.'[25] Science does| not usually proceed this way: In classical mechanics, for example, one can construct equations of motion using Newtonian vectoral mechanics, or using a Lagrangian or Hamiltonian variational formulation.[30] In the cases where all three approaches are applicable they are equivalent, but each has its advantages in particular contexts." This footnote is in the context of a section discussing redundancy in biological systems (and the usual lack thereof in engineered physical systems). Python is an algorithm language and a tool used to engineering information systems, which is something different. The next sections are about exploratory behavior. Languages do not 'behave', let alone 'explore'. Leaving that aside, if you consider vector mechanics and variational formulations as roughly analogous to functional versus procedural programming (or OOP), then Python has both (or all three). Or if you consider them to be different languages for expressing and solving problems, then Python is one just language, but one that intentionally works well with some others. So Python seems to have the sort of flexibility that he implicitly claims it does not. The general problems of software inflexibility that he mentioned in a previous section have nothing specific to do with Python. When he gets to solutions, one long section (page 13) somewhat specific to languages, versus applications thereof, is about extensible generic operations "where it is possible to define what is meant by addition, multiplication, etc., for new datatypes unimagined by the language designer." Well, golly gee. Guess what? Not only is Python code generic unless specialized (with isinstance tests, for instance), but it is highly extensible for new datatypes, just as Sussman advocates. There is a special method for just about every syntactic construct and builtin function. And 3.0 may add a new generic function module to dispatch on multiple arguments and possibly predicates. But what naive reader could possibly guess any of this from the single mention of Python quoted above? Terry Jan Reedy From aleax at mac.com Fri Jun 15 10:40:33 2007 From: aleax at mac.com (Alex Martelli) Date: Fri, 15 Jun 2007 07:40:33 -0700 Subject: huge dictionary -> bsddb/pickle question References: <1181895778.031710.58520@o11g2000prd.googlegroups.com> Message-ID: <1hzqne2.wv9m7y1um1vssN%aleax@mac.com> lazy wrote: ... > key1=>{key11=>[1,2] , key12=>[6,7] , .... } ... > Im processesing HUGE(~100M inserts into the dictionary) data. What will you need from the "saved" version later? If you need lookups by single keys or key pairs then a relational DB may be best; if you need to recover the whole huge dictionary into memory (assuming it will fit, e.g. you have a 64-bit machine with ample RAM) then it might be more efficient to "dump" things into a custom-designed format. If I was uncertain about future uses of the saved data, I'd go for the maximal flexibility afforded by a relational DB -- if you save to a relational DB you can later easily use the data in every which way, including ad-hoc ones (such flexibility is a key architectural feature of relational databases). E.g., a single table with 4 fields might be enough: key, subkey, leftint, rightint -- each field of the appropriate type (you do tell us that the two ints are smallish integers, but we don't know directly about the types of the keys -- besides a hint that the main keys are presumably strings of some kind since that's what bsddb likes as its own keys, but still, choosing the right kind of string may be important in order to save space and obtain good performance). The (key,subkey) pair would be the primary key on that table, and unless and until you need peculiar "navigation" in the future you may not require other indices, constraints, or whatever. At the scale you're talking about (multi-gigabyte, it appears) it's probably worth using a powerful DB (such as PostgreSQL, interfacing it to Python via psycopg2) rather than a lightweight one (such as sqlite, which comes with Python 2.5); however, depending on how critical performance is, such issues are often best resolved by benchmarking (similarly, you might benchmark the performance for inserting into the properly constrained table from the start, vs originally making the table constraints-less and using an ALTER TABLE later to add the primary key constraint/index that will be useful for later lookups; "bulk insertions" into DBs can often benefit from the latter idea). Alex From duncan.booth at invalid.invalid Wed Jun 20 04:07:30 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 20 Jun 2007 08:07:30 GMT Subject: Using a switch-like if/else construct versus a dictionary? References: <1182282008.522677.269730@g4g2000hsf.googlegroups.com> Message-ID: asincero wrote: > handle_case = {} > handle_case[1] = doCase1() > handle_case[2] = doCase2() > handle_case[3] = doCase3() > handle_case[4] = doCase4() > handle_case[5] = doCase5() > handle_case[c]() > If the switch values are simple integers then a list would be a more obvious choice: handle_case = [ doCase1, doCase2, doCase3, doCase4, doCase5 ] handle_case[c-1]() > Note that in this situation using OO polymorphism instead of a switch- > like construct wouldn't be applicable, or at least I can't see how it > could be. That is often the case when you reduce your question to a mickeymouse do nothing example. There are many ways to write code that could be written using a switch statement. If you took a few real use-cases then you would probably each one needs a different technique for best effect depending on the number of different cases, the values which must be accessed within each case, the side-effects (if any) expected from handling the case etc. The obvious options include: if/elif chain; a list or dictionary containing data values (not functions); a list or dict containing functions; command pattern (i.e. a class with a dispatch method); a class hierarchy and polymorphism; visitor pattern. For an example of the last of these see http://www.chris-lamb.co.uk/blog/2006/12/08/visitor-pattern-in-python/ which uses decorators to produce a very clean implementation using (I think) PyProtocols dispatch. From zachary.manning at gmail.com Sun Jun 24 15:52:25 2007 From: zachary.manning at gmail.com (Zachary Manning) Date: Sun, 24 Jun 2007 14:52:25 -0500 Subject: newbie tcp/ip question Message-ID: <467ECB79.7010001@gmail.com> Hello all, I'm having a hard time tracking down a way to open up a tcp/ip client connection and simply sending a string to the port I've opened up. For instance I want to send some hex characters as a string literal to port 7142 and to a specific ip address. How do I do that in python? thanks, zm From jerry.vb at gmail.com Sat Jun 9 02:14:16 2007 From: jerry.vb at gmail.com (Jerry VanBrimmer) Date: Fri, 8 Jun 2007 23:14:16 -0700 Subject: VIM editor question In-Reply-To: References: Message-ID: <901b226d0706082314m602933cbna0c0301e4fdd578b@mail.gmail.com> In your vim configuration file enter: colorscheme Example: colorscheme elflord Restart vim. On 6/8/07, David wrote: > Is anyone in the group familiar with the VIM editor? I rather like it but > any time I right click on a file and select "Edit with Vim" It opens the > file in a rather ugly default color scheme. > > I'd love to know how to make it automatically open files I select in my > favorite color scheme rather than having to go into the " EDIT "pull down > menu and select my preferred Color Scheme every time I open a file. > > thanks for any wisdom you can share > > David KG2LI > > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Jesus is coming!................................................Rev. 1:7 The Bottom Line................................................John 3:3-7 From XX.XmcX at XX.XmclaveauX.com Fri Jun 1 15:41:45 2007 From: XX.XmcX at XX.XmclaveauX.com (MC) Date: Fri, 01 Jun 2007 21:41:45 +0200 Subject: Comments appreciated on Erlang inspired Process class. References: Message-ID: Hi! Look Candygram : http://candygram.sourceforge.net/ -- @-salutations Michel Claveau From esj at harvee.org Wed Jun 6 09:17:57 2007 From: esj at harvee.org (Eric S. Johansson) Date: Wed, 06 Jun 2007 09:17:57 -0400 Subject: MoinMoin configuration In-Reply-To: <1180898555.111625.187150@h2g2000hsg.googlegroups.com> References: <1180898555.111625.187150@h2g2000hsg.googlegroups.com> Message-ID: <4666B405.6090602@harvee.org> kyosohma at gmail.com wrote: > I have read through the ACL instructions on MoinMoin's site, but I > don't understand how to make it work. See http://moinmoin.wikiwikiweb.de/HelpOnAccessControlLists > > To me it seems to be saying that you have to create a page before you > can set the ACL for it. I don't want a bunch of pages where some have > ACL's and some don't. > > If you can clear up my confusion, that would be great. Thanks! Yes, it is confusing and I went to this recently myself. in your site configuration file, wikiconfig.py, The only ACL that you should have (for this capability) are the two below. Before you put the acl's in place, you need to create the page AuthorizedGroup and put your wikiname in there. This will make you a member of the authorized group and able to edit that page after the ACLs are put in place. acl_rights_default = u"All:read" acl_rights_before = u"AuthorizedGroup:admin,read,write,delete,revert" if you wanted to make things a little more complicated and possibly secure, it should be possible to put in a page specific acl preventing anyone from reading "authorize groups" unless they are a member of the authorized group page and anyone from writing unless they are you. I would love to see if this kind of functionality would work but I don't have the time to play around with it (currently beating my head against flash memory and grub problems). So if you come up with a solution, feel free to e-mail me directly or if you have any other questions, also, feel free to send me mail. Might not know the answer but at least we can commiserate. :-) ---eric From inq1ltd at verizon.net Mon Jun 4 18:15:11 2007 From: inq1ltd at verizon.net (jim-on-linux) Date: Mon, 04 Jun 2007 18:15:11 -0400 Subject: Tkinter - resize tkMessageBox In-Reply-To: <1180988981.634298.38830@o11g2000prd.googlegroups.com> References: <1180988981.634298.38830@o11g2000prd.googlegroups.com> Message-ID: <200706041815.11508.inq1ltd@verizon.net> On Monday 04 June 2007 16:29, rahulnag22 at yahoo.com wrote: > Hi, > Is there a way to resize the width of the > "tkMessageBox.askyesno" dialog box, so that the > text does not wrap to the next line. Thanks > Rahul I don't know of any. It's a little more work but your better off using Toplevel and/or frame, you have more control over the window and its appearance. jim-on-linux http://www.inqvista.com From bj_666 at gmx.net Tue Jun 19 11:12:49 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Tue, 19 Jun 2007 17:12:49 +0200 Subject: HTMLParser.HTMLParseError: EOF in middle of construct References: <1182195498.16548.5.camel@localhost.localdomain> <4677e790$0$2840$a729d347@news.telepac.pt> Message-ID: In <4677e790$0$2840$a729d347 at news.telepac.pt>, none wrote: > Gabriel Genellina wrote: >> En Mon, 18 Jun 2007 16:38:18 -0300, Sergio Monteiro Basto >> escribi?: >> >>> Can someone explain me, what is wrong with this site ? >>> >>> python linkExtractor3.py http://www.noticiasdeaveiro.pt > test >>> >>> HTMLParser.HTMLParseError: EOF in middle of construct, at line 1173, >>> column 1 >>> >>> at line 1173 of test file is perfectly normal . >> >> That page is not valid HTML - http://validator.w3.org/ finds 726 errors >> in it. > > ok but my problem is not understand what is the specific problem at line > 1173 You can't just look at that line and ignore the rest. There are 604 (!) errors, some about table rows, before this line. So the parser may be confused at this point and be already in an internal state that sees that line in a completely different light than you do. Ciao, Marc 'BlackJack' Rintsch From eadmund42 at NOSPAMgmail.com Sat Jun 23 20:35:22 2007 From: eadmund42 at NOSPAMgmail.com (Robert Uhl) Date: Sat, 23 Jun 2007 18:35:22 -0600 Subject: The Modernization of Emacs: terminology buffer and keybinding References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182272495.990807.99110@a26g2000pre.googlegroups.com> <87tzt3ihev.fsf@kobe.laptop> <1182370216.961241.6960@n60g2000hse.googlegroups.com> <85zm2ufjpb.fsf@lola.goethe.zz> <1182372592.803332.288260@u2g2000hsc.googlegroups.com> <5dtk4tF34jrimU1@mid.dfncis.de> <1182375388.814275.227380@n2g2000hse.googlegroups.com> <87645h73ei.fsf@W0053328.mgh.harvard.edu> <1182548563.561252.82480@i13g2000prf.googlegroups.com> Message-ID: Twisted writes: > > For an example of the latter, consider opening a file. Can't remember > the exact spelling and capitalization of the file name? Sorry, bud, > you're SOL. Go find it in some other app and memorize the name, then > return to emacs. Once again I am forced to wonder if you have _ever_ actually used emacs. find-file has tab completion: hit tab without anything typed, and it displays _everything_ in the directory; type a few characters to narrow it down; hit tab to complete the filename and be done with it. Or of course you could use directory mode, which enables you to navigate around a directory tree, performing actions on files (including editing them). Then of course there's ido.el, which is even better: type a few characters from anywhere in the name, and it displays files matching those characters. You've never actually run emacs, have you? -- Robert Uhl The power of Satan is as nothing before the might of the Lord, so don't go getting any ideas. --I Abyssinians 20:20 From edudobay at gmail.com Tue Jun 26 17:50:21 2007 From: edudobay at gmail.com (Eduardo Dobay) Date: Tue, 26 Jun 2007 14:50:21 -0700 Subject: Using PSE under Win32 In-Reply-To: <1182730750.267265.74240@i38g2000prf.googlegroups.com> References: <1182611604.696515.143930@k79g2000hse.googlegroups.com> <1182730750.267265.74240@i38g2000prf.googlegroups.com> Message-ID: <1182894621.142691.52780@g4g2000hsf.googlegroups.com> On 24 jun, 21:19, Graham Dumpleton wrote: > What do you have PythonHandler set to and what does it identify? The > error above suggests that whatever you identify as the handler is not > a callable object like a function. Are you perhaps identifying some > sort of PSE template object as target when you shouldn't be? Post your > handler code so we can see it. > > Graham Hello, thanks for the answer. I just found the problem. I had written in my Apache conf PythonHandler pse_handler because I had seen it in PSE manual. But now I tried to google some more and found this wiki page that says that I should instead write PythonHandler pse_handler::mp_handler Apparently this behaviour changed in 4.0 beta (I found no mention to it in PSE's official site), but I'm almost sure the same error happened when I installed 3.0.6 and tried to run a test script. Anyway, I think that's it for now. Eduardo From grante at visi.com Sun Jun 24 13:03:23 2007 From: grante at visi.com (Grant Edwards) Date: Sun, 24 Jun 2007 17:03:23 -0000 Subject: automatical pdf generating References: <1182700820.325024.107040@g4g2000hsf.googlegroups.com> Message-ID: <137t8urlbb2tre4@corp.supernews.com> On 2007-06-24, Jackie wrote: > For each folder, I want to print the 4 pictures into a single-paged > pdf file (letter sized; print horizontally). All together, I want to > get 50 pdf files with names: 01.pdf,02.pdf,...,50.pdf. > > Is it possible to use Python to realized the above process? Yes. > I know there is a module named "reportlab". Is there any easy > command in the module to do my job? Yes. http://www.reportlab.org/rl_toolkit.html http://www.reportlab.com/docs/userguide.pdf -- Grant Edwards grante Yow! You mean you don't at want to watch WRESTLING visi.com from ATLANTA? From goofyheadedpunk at gmail.com Fri Jun 22 10:01:07 2007 From: goofyheadedpunk at gmail.com (Brian L. Troutwine) Date: Fri, 22 Jun 2007 07:01:07 -0700 Subject: Discovery of unpickleables in class heirarchies. Message-ID: <1182520867.708514.122710@a26g2000pre.googlegroups.com> I've a need to pickle arbitrary class hierarchies, which, luckily, can be made to conform to the pickle protocol. At the moment, however, I'm having a rather hard time discovering which classes in a heirarchy cannot be pickles. For instance, say class A has class B in it's __dict__ and let class B have a file handler in its __dict__. When I call cPickle.dumps(A) UnpickleableError will be raised when B's file handler is reached, but the error will only report being unable to pickle the file handler, saying nothing of B or A. I wouldn't expect cPickle to do that, but I do need to know somehow that class B has failed to pickle properly. To that end I've quickly hacked out a class that, ideally, will take an object that I'm attempting to pickle and, if the pickling does not succeed, recurse through the class heirarchy collecting information on which objects were not pickled. It is here: http://deadbeefbabe.org/paste/5218 The output, for the above example would be: However, it seems to be taking a rather long time. Perhaps my class heirarchies are too deep, or my recursion is flawed. Can anyone see a bug in my code, or have a better way of discovering this information altogether? From xavier_berard at hotmail.com Thu Jun 7 09:58:16 2007 From: xavier_berard at hotmail.com (=?iso-8859-1?q?Xavier_B=E9rard?=) Date: Thu, 07 Jun 2007 06:58:16 -0700 Subject: Tkinter custom drawing Message-ID: <1181224696.484887.29980@q66g2000hsg.googlegroups.com> Hello everyone, I am wondering if there is a way to use custom drawing in Tkinter. I've been using it for few months, and all I know about custom drawing is to draw directly on a Canvas with such methods as "create_line", "create_rectangle", etc. Now, the problem, is that I have already plenty of widgets on my screen. I just want to draw over them, which is a bit difficult in my comprehension of things. My perfect solution was to put temporary invisible Canvas when I want do use draw methods, but such thing doesn't exist (as far as I could search in this community's posts). Anyone have a clue ? Thanks, Xavier Berard From lists at asd-group.com Fri Jun 1 12:09:58 2007 From: lists at asd-group.com (NeBlackCat (lists)) Date: Sat, 02 Jun 2007 00:09:58 +0800 Subject: Detecting an active exception Message-ID: <466044D6.5040503@asd-group.com> Hello everybody - my first post! And it may be the most monumentally stupid question ever asked, but I just can't see an answer after several hours experimenting, searching and reading. It's simply this - how can a function determine whether or not it's being called in handling of an exception (ie. there is an "active" exception, and somewhere upstream on the stack there is an except: block statement)? Depending on what you read, sys.exc_info() is supposed to return (None,None,None) when there is no active exception, but it seems that it returns info about the last exception when there isn't one currently active. For example: try: a = a + 1 except: pass print sys.exc_info() produces: , , Where the traceback object identifies the offending a=a+1 line (of course). Is there another way of doing this? Note that I can't rely on using sys.exc_clear() in any solution, unfortunately. cheers - John From jakub.stolarski at gmail.com Mon Jun 25 12:37:18 2007 From: jakub.stolarski at gmail.com (Jakub Stolarski) Date: Mon, 25 Jun 2007 16:37:18 -0000 Subject: Capturing and sending keys {Esperanto} In-Reply-To: References: Message-ID: <1182789438.447893.145650@j4g2000prf.googlegroups.com> On Jun 25, 3:26 pm, AJK wrote: > Hello there! > > I've been googleing yet, and suppose it's hopeless to try, but better ask it... > > I want to write a program which turns Cx to , cx to et al WHILE > TYPING. (i.e. converting Esperanto x-system to real hats, for those > who know about this.) Therefore I though will need to capture the last > 2 typed characters (from any application), send a double backspace and > after that send the correct letters (back to the same application)... > > However, it seems inpossible to capture those letters, and maybe to > send them too... > > Or am I wrong? > > Greetings, > > LaPingvino > > (project:http://code.google.com/p/iksilo/- SVN Repository is free > viewable, project is GPL) > > -- > ar Dio tiel amis la mondon, ke Li donis Sian solenaskitan Filon, por > ke iu, kiu fidas al li, ne pereu, sed havu eternan vivon. > -Johano 3:16, La sankta Biblio- > > oju iam, pre u sen ese, pri io donu dankon. > -1 Tesalonikanoj 5:16-18a, La sankta Biblio- Under *nix it's easier to change xkb keymap. If you interested only in gtk applications then there is gtk-im-extra [1], which you can use to input "cxapeloj". You can also look at scim [2] sources. It supports gtk, qt and standard x applications. Bonsxancon! [1] http://gtk-im-extra.sourceforge.net/ [2] http://www.scim-im.org/ From fabiofz at gmail.com Sun Jun 10 08:17:21 2007 From: fabiofz at gmail.com (Fabio Zadrozny) Date: Sun, 10 Jun 2007 09:17:21 -0300 Subject: How to get existing frames in non-current thread? In-Reply-To: References: Message-ID: On 6/10/07, Gabriel Genellina wrote: > > En Sat, 09 Jun 2007 21:40:40 -0300, Fabio Zadrozny > escribi?: > > > Is there some way to get all the frames for any given thread? -- in a > way > > that does not require a compiled extension. > > For the current (calling) thread, you can use sys._getframe() > For other threads, you can use sys._current_frames() > Frames have a f_back attribute pointing to the previous one, that you can > use to navigate them. > Thanks a lot... I guess I'll have to find another way for versions before 2.5 ;-) -------------- next part -------------- An HTML attachment was scrubbed... URL: From cam.ac.uk at mh391.invalid Mon Jun 4 11:23:19 2007 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Mon, 04 Jun 2007 16:23:19 +0100 Subject: Pyrex: problem with blanks in string In-Reply-To: References: Message-ID: Hans Terlouw wrote: > When trying to wrap C code using Pyrex, I encountered a strange problem > with a piece of pure Python code. I tried to isolate the problem. The > following code causes Pyrex to generate C code which gcc cannot compile: It works for me. Try posting your error messages and versions of Pyrex/Python/GCC. Better yet, do this in the Pyrex mailing list rather than here. -- Michael Hoffman From david.golden at oceanfree.net Sun Jun 24 14:07:34 2007 From: david.golden at oceanfree.net (David Golden) Date: Sun, 24 Jun 2007 19:07:34 +0100 Subject: The Modernization of Emacs: terminology buffer and keybinding References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182272495.990807.99110@a26g2000pre.googlegroups.com> <87tzt3ihev.fsf@kobe.laptop> <1182370216.961241.6960@n60g2000hse.googlegroups.com> <85zm2ufjpb.fsf@lola.goethe.zz> <1182372592.803332.288260@u2g2000hsc.googlegroups.com> <1182373919.262388.100740@c77g2000hse.googlegroups.com> <85r6o6fhkb.fsf@lola.goethe.zz> <1182375045.626510.188170@m36g2000hse.googlegroups.com> <85myyufgwj.fsf@lola.goethe.zz> <1182375528.985142.293900@q69g2000hsb.googlegroups.com> <1182545268.055596.228700@i38g2000prf.googlegroups.com> <1182661040.286559.150880@q75g2000hsh.googlegroups.com> <467e27f1.6428764@news.readfreenews.net> <_Wqfi.20503$j7.378099@news.indigo.ie> Message-ID: <5qyfi.20510$j7.378061@news.indigo.ie> Thomas Bellman wrote: > I seem to recall that EMACS, the old TECO version on TOPS-20 and > ITS, only supported two windows ("panes" in Twisted's words). So > it's not *completely* false, just extremely outdated. > > Well, that's going back a bit. I somehow doubt he was using that, but I guess it's possible (he did claim emacs is a "unix" text editor though)... From NevilleD.python at sgr-a.net Tue Jun 19 21:22:24 2007 From: NevilleD.python at sgr-a.net (Neville D) Date: Wed, 20 Jun 2007 13:22:24 +1200 Subject: Q: listsort and dictsort - official equivalents? Message-ID: <1182302544.4202.40.camel@delta.sgr-a.net> I expressed my creativity & created two routines, listsort & dictsort. def listsort(l,cmp=None): l.sort(cmp); return l def dictsort(d,cmp=None):return [(k,d[k])for k in listsort(d.keys(),cmp=cmp)] Basically I am more familiar with sorting inside a for loop, eg in bourne shell one can do "for loop sorts": for group in $(sort /etc/group); do echo group; done In python I must kick off a sort on the line before I start the iteration. (This does make sense because at the end of the day the sort has complete BEFORE the for loop can proceed - that is... until the day when python lists have a secondary index ;-). group_list=group_dict.keys() group_list.sort() for group in group_list: # do print group,group_dict[group] # done I am sure python has a more concise way of doing this, any hints? Cheers NevilleD # examples: #!/usr/bin/env python ## -*- coding: utf-8 -*- ## purpose: demo sorting in python def aleph_cmp(a,b): # class only needs the "<" operator if a <1182843872.488493.153700@m36g2000hse.googlegroups.com> <87myync95b.fsf@mail.eng.it> <1182905443.074236.128290@w5g2000hsg.googlegroups.com> <5efqclF37fmubU1@mid.individual.net> Message-ID: <87myyi6fz1.fsf@W0053328.mgh.harvard.edu> blmblm at myrealbox.com writes: > I find Windows and its tools as frustrating as you seem to find > Unix, but I strongly suspect that being shown the ropes by someone > who understands and likes the system would help a lot. I feel the same way about Windows being frustrating, however I find that having a Windows "expert" around helps very little. Heck, *I* was a Windows expert for as long as I was using it. I always found it to be totally opaque. It always seemed like the only way to make things work was to BUY something --- something that really offended me. It became clear to me quickly that Windows is basically a billboard on a CRT --- the help files only told me to buy stuff, or how "fun and easy" it was to do something, without actually saying how to do it. When I got XP and wanted to change my desktop theme --- guess what? They decided to start charging for that too. With Windows I never got it; with Unix of any kind (linux, SunOS, etc), I have felt like I got it right away. Joel -- Joel J. Adamson Biostatistician Pediatric Psychopharmacology Research Unit Massachusetts General Hospital Boston, MA 02114 (617) 643-1432 (303) 880-3109 *Joel's guide to sending attachments: 1. put all the files you want to send in a folder and archive the folder using tar, then compress it with gzip or bzip2 2. please send me .pdf, .html, or text in place of Word documents: http://www.gnu.org/philosophy/sylvester-response.html *Did you know there's a FREE alternative to using word processors? http://www.edafe.org/latex/ http://en.wikipedia.org/wiki/LaTeX http://nitens.org/taraborelli/latex From debajit at debajit.com Thu Jun 28 21:56:53 2007 From: debajit at debajit.com (Debajit Adhikary) Date: Thu, 28 Jun 2007 21:56:53 -0400 Subject: Converting Diff Output to XML? In-Reply-To: <9c09a1210706271657w13c21100k551c66b4b307cb5a@mail.gmail.com> References: <110a172d0706260743m10a9aaebt81e072717dbd6582@mail.gmail.com> <9c09a1210706271657w13c21100k551c66b4b307cb5a@mail.gmail.com> Message-ID: <110a172d0706281856w6cf32e0ai362915325178c2dc@mail.gmail.com> That looks very good :)Thanks a ton! On 6/27/07, Yongjian Xu wrote: > > gnosis has a converter for ASCII file to xml file, its called txt2dw.py. > give it a try. > > -- > Jim > > On 6/26/07, Debajit Adhikary wrote: > > > > What would be the best way to convert the regular (unix) diff output > > into XML? > > Are there any libraries at all which might help? > > > > -- > > http://mail.python.org/mailman/listinfo/python-list > > > > > > -- > Yongjian (Jim) Xu > =========== > Sysops -------------- next part -------------- An HTML attachment was scrubbed... URL: From thomas at jollans.NOSPAM.com Tue Jun 5 05:47:06 2007 From: thomas at jollans.NOSPAM.com (Thomas Jollans) Date: Tue, 5 Jun 2007 10:47:06 +0100 Subject: html 2 image script or library References: <1181034367.911086.189870@k79g2000hse.googlegroups.com> Message-ID: <466532d8$0$2889$6e1ede2f@read.cnntp.org> "baur79" wrote in message news:1181034367.911086.189870 at k79g2000hse.googlegroups.com... > can you help me to find script or library for making website (from > url) 2 image (png, jpg no matter). complex business that is, you'll want to look at fully-fledged HTML redering engines like Gecko. You might also want to reveal your name (rather common on USENET and mailing lists, I gather) and use, to the best of your ability, proper English. Thomas Jollans From josiah.carlson at sbcglobal.net Mon Jun 11 02:36:25 2007 From: josiah.carlson at sbcglobal.net (Josiah Carlson) Date: Mon, 11 Jun 2007 06:36:25 GMT Subject: Python's "only one way to do it" philosophy isn't good? In-Reply-To: <7xy7irxjom.fsf@ruckus.brouhaha.com> References: <1181368143.874341.273140@r19g2000prf.googlegroups.com> <7xy7irxjom.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > Steven D'Aprano writes: >>> Not tail calls, in general, no. >> Sorry, how does that work? You're suggesting that there is an algorithm >> which the compiler could follow to optimize away tail-recursion, but human >> beings can't follow the same algorithm? >> >> Now I'm confused. > > The usual compiler method is to translate the code into > continuation-passing style and thereby gain tail-recursion > optimization automagically. Of course a human could do the same thing > in principle, but it would result in insanely difficult-to-write, > unreadable and unmaintainable code. At a higher level, there are no > Python features whatsoever, either existing or proposed, that couldn't > be eliminated and left to the human. Iterators? While loops? Who > needs 'em? We could all go back to programming in machine code. But > Python is supposed to make programming easier, not harder. Thanks to Richie Hindle, there exists a goto for Python implementation that makes such things quite trivial (assuming one doesn't like "abusing" break/continue/else). http://entrian.com/goto/ (which, by the way, is the best April-fools joke ever) - Josiah From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Thu Jun 21 09:55:48 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Thu, 21 Jun 2007 15:55:48 +0200 Subject: PEP 3107 and stronger typing (note: probably a newbie question) References: <1182369568.941307.316260@p77g2000hsh.googlegroups.com> Message-ID: <5dveb4F360un0U1@mid.individual.net> Stephen R Laniel wrote: > On Wed, Jun 20, 2007 at 12:59:28PM -0700, > bruno.desthuilliers at gmail.com wrote: >> Then you should use another language. > > This is what I meant about knowing how Internet discussions > go. I agree. I also notice that (rather newbie-) OPs with not-so-simple questions are easily offended by technical answers. I'd love to know why. Regards, Bj?rn -- BOFH excuse #39: terrorist activities From steve at laniels.org Thu Jun 14 17:45:08 2007 From: steve at laniels.org (Stephen R Laniel) Date: Thu, 14 Jun 2007 17:45:08 -0400 Subject: Failing on string exceptions in 2.4 Message-ID: <20070614214506.GA27937@slaniel-laptop.itasoftware.com> Reading the Python docs, it looks like string exceptions will be a DeprecationWarning in Python 2.5. Is there any way to make them so in 2.4? Now how about if I want to turn all DeprecationWarnings into compile-time errors? Is there some way to do this? End goal being that string exceptions would cause compilation to fail. A few times now, I've found myself doing class SomeClass: """docstring""" pass raise SomeClass, "Some description" and I've gotten a weird compiler error about the constructor for SomeClass. I'd prefer it just to fail there and not let me raise an exception that isn't subclassed beneath Exception. -- Stephen R. Laniel steve at laniels.org Cell: +(617) 308-5571 http://laniels.org/ PGP key: http://laniels.org/slaniel.key From mccredie at gmail.com Thu Jun 21 15:11:51 2007 From: mccredie at gmail.com (Matimus) Date: Thu, 21 Jun 2007 19:11:51 -0000 Subject: try/except with multiple files In-Reply-To: <1182452425.793305.193370@u2g2000hsc.googlegroups.com> References: <1182452425.793305.193370@u2g2000hsc.googlegroups.com> Message-ID: <1182453111.391374.279490@e9g2000prf.googlegroups.com> It depends, what are you going to do if there is an exception? If you are just going to exit the program, then that works fine. If you are going to just skip that file, then the above wont work. If you are going to return to some other state in your program, but abort the file opening, you might want to close any files that were opened. The closing can be taken care if in the except block, but you will have to know which ones opened successfully. In general I would do something like this for multiple files: [code] filenames = ["fname1","fname2","fname3"] for fn in filenames: try: f = open(fn) except IOError: # handle exception #do something with f [/code] But, that might not work for you if the files aren't homogeneous (each have similar contents). If the files have distinctly different purposes, I would just wrap them each in their own try/except block. I rambled a bit there, but I hope it helps. Matt From martin at see.sig.for.address Thu Jun 21 08:06:15 2007 From: martin at see.sig.for.address (Martin Gregorie) Date: Thu, 21 Jun 2007 13:06:15 +0100 Subject: The Modernization of Emacs In-Reply-To: <5dupbhF35nekiU2@mid.individual.net> References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182344981.372713.298580@w5g2000hsg.googlegroups.com> <1182370884.853838.321440@c77g2000hse.googlegroups.com> <2jpok4-ajt.ln1@zoogz.gregorie.org> <5dupbhF35nekiU2@mid.individual.net> Message-ID: Sascha Bohnenkamp wrote: >> Windows text editors are not normal: most are devoid of all but the most >> primitive functions and are further hampered by having an interface that >> required frequent time wasting hand transfers from keyboard to mouse >> because, if they provide keyboard equivalents at all, these are >> remarkably unmemorable and/or undocumented. > > well ultra-edit, textpad, source-insight etc. pp are better than that > (and run on windows) I said MOST, not all! To your list I'd add PFE and a Windows port of microEmacs, which has almost nothing in common with EMACS except some key bindings. But to return to your point: how many Windows users actually install the editors we've listed? I bet most never get past Wordpad. I've even found people using Word, of all things, to edit BAT files and program source. I'd give long odds that Windows users who use editors other than Wordpad are using the one that came with whatever IDE they've installed, simply because integrated editors are much more common in Windows-only IDEs that they are on *nixen. My guess is that this is because the standard editors (Wordpad, edlin) are so bad. -- martin@ | Martin Gregorie gregorie. | Essex, UK org | From steven.bethard at gmail.com Mon Jun 11 15:55:29 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Mon, 11 Jun 2007 13:55:29 -0600 Subject: Postpone creation of attributes until needed In-Reply-To: <1181569088.048872.254700@m36g2000hse.googlegroups.com> References: <1181553891.447344.109390@g4g2000hsf.googlegroups.com> <1181559496.911368.219210@p77g2000hsh.googlegroups.com> <1181564855.890242.116840@m36g2000hse.googlegroups.com> <1181569088.048872.254700@m36g2000hse.googlegroups.com> Message-ID: <466DA8B1.7080906@gmail.com> George Sakkis wrote: > On Jun 11, 8:27 am, Frank Millman wrote: >> On Jun 11, 1:56 pm, Steven D'Aprano >> >> wrote: >> >>> Unless you have thousands and thousands of instances, __slots__ is almost >>> certainly not the answer. __slots__ is an optimization to minimize the >>> size of each instance. The fact that it prevents the creation of new >>> attributes is a side-effect. >> Understood - I am getting there slowly. >> >> I now have the following - >> >>>>> class A(object): >> ... def __init__(self,x,y): >> ... self.x = x >> ... self.y = y >> ... def __getattr__(self,name): >> ... print 'getattr',name >> ... self.compute() >> ... return self.__dict__[name] >> ... def compute(self): # compute all missing attributes >> ... self.__dict__['z'] = self.x * self.y >> [there could be many of these] >> >>>>> a = A(3,4) >>>>> a.x >> 3 >>>>> a.y >> 4 >>>>> a.z >> getattr z >> 12>>> a.z >> 12 >>>>> a.q >> KeyError: 'q' >> >> The only problem with this is that it raises KeyError instead of the >> expected AttributeError. >> >> >> >>> You haven't told us what the 'compute' method is. >>> Or if you have, I missed it. >> Sorry - I made it more explicit above. It is the method that sets up >> all the missing attributes. No matter which attribute is referenced >> first, 'compute' sets up all of them, so they are all available for >> any future reference. >> >> To be honest, it feels neater than setting up a property for each >> attribute. > > I don't see why this all-or-nothing approach is neater; what if you > have a hundred expensive computed attributes but you just need one ? > Unless you know this never happens in your specific situation because > all missing attributes are tightly coupled, properties are a better > way to go. The boilerplate code can be minimal too with an appropriate > decorator, something like: > > class A(object): > > def __init__(self,x,y): > self.x = x > self.y = y > > @cachedproperty > def z(self): > return self.x * self.y > > > where cachedproperty is > > def cachedproperty(func): > name = '__' + func.__name__ > def wrapper(self): > try: return getattr(self, name) > except AttributeError: # raised only the first time > value = func(self) > setattr(self, name, value) > return value > return property(wrapper) And, if you don't want to go through the property machinery every time, you can use a descriptor that only calls the function the first time: >>> class Once(object): ... def __init__(self, func): ... self.func = func ... def __get__(self, obj, cls=None): ... if obj is None: ... return self ... else: ... value = self.func(obj) ... setattr(obj, self.func.__name__, value) ... return value ... >>> class A(object): ... def __init__(self, x, y): ... self.x = x ... self.y = y ... @Once ... def z(self): ... print 'calculating z' ... return self.x * self.y ... >>> a = A(2, 3) >>> a.z calculating z 6 >>> a.z 6 With this approach, the first time 'z' is accessed, there is no instance-level 'z', so the descriptor's __get__ method is invoked. That method creates an instance-level 'z' so that every other time, the instance-level attribute is used (and the __get__ method is no longer invoked). STeVe From laurent.pointal at limsi.fr Wed Jun 20 03:17:45 2007 From: laurent.pointal at limsi.fr (Laurent Pointal) Date: Wed, 20 Jun 2007 09:17:45 +0200 Subject: Execute script on remote computer In-Reply-To: References: <0B5158DBDB894441A80F5928175235330589F243@postoffice.cybage.com> Message-ID: Evan Klitzke a ?crit : > On 6/19/07, Vikas Saini wrote: >> I am trying to run the agent on one machine that will execute the >> script of >> a remote machine. > > It's not clear what OS you're using. But if you're running a > Unix/Linux system and it's a relatively simple script that you want to > run, you should just use the ssh command coupled with the name of the > command you want to run (you don't even need the agent to use python, > necessarily). For example, > > ssh user at foo bar > > Will ssh to machine 'foo' as user 'user' and execute command 'bar' on > that machine (rather than launching a shell, which is what ssh will do > if no command is specified). When the command exits, ssh will exit as > well. > > Note: You can use an ssh server on Windows too, see CopSSH for a free, relatively easy to install solution. So unix solution for running Python script can be used uder Xindows Xp too - at least if you dont want to have a GUI [*]. See http://www.itefix.no/phpws/index.php?module=pagemaster&PAGE_user_op=view_page&PAGE_id=12 [*] You can do remote display of Windows screen via an encrypted VNC using ssh port redirection - if you read french (or like screen capture), see http://www.limsi.fr/Individu/pointal/winremote/ From evan at yelp.com Sat Jun 16 15:04:06 2007 From: evan at yelp.com (Evan Klitzke) Date: Sat, 16 Jun 2007 12:04:06 -0700 Subject: How do I write to a CD? In-Reply-To: <51190.69.183.26.157.1182009013.squirrel@www.kearfott.com> References: <51190.69.183.26.157.1182009013.squirrel@www.kearfott.com> Message-ID: On 6/16/07, k47867 at kearfott.com wrote: > Can I just use open(), read(), write(), and close() for > these? And how do I make something bootable? I don't know enough about your query to answer all of your questions, but to make any device bootable, including a CD, you need to put a bootloader (and a kernel, of course) onto the device. If you are putting a Linux kernel onto the CD, the most common bootloader to use is ISOLINUX, although a recent release of GRUB will work as well. -- Evan Klitzke From arorap at gmail.com Tue Jun 12 22:58:14 2007 From: arorap at gmail.com (arorap) Date: Wed, 13 Jun 2007 02:58:14 -0000 Subject: cgi.FieldStorage() not working on Windows In-Reply-To: <1181692790.432649.273820@i13g2000prf.googlegroups.com> References: <1181661435.258140.17800@x35g2000prf.googlegroups.com> <1181692790.432649.273820@i13g2000prf.googlegroups.com> Message-ID: <1181703494.047837.26120@i38g2000prf.googlegroups.com> Thanks for your reply. The reason I want to run it as CGI (even though mod_php is available on my local computer) is that the target machine to which I will finally be uploading my scripts runs CGI. cgihandler should work just like CGI. Any clue why the cgi.FieldStorage()might not be working ? On Jun 12, 7:59 pm, Graham Dumpleton wrote: > On Jun 13, 1:17 am,arorap wrote: > > > > > I've mod_php installed with Apache 2.2. In one of my folders, I'm > > using the cgihandler as the PythonHandler as my target host runs > > python only as CGI. Here cgi.FieldStorage() doesn't seem to work. I > > can see the form data in sys.stdin but cgi.FieldStorage() returns an > > empty dictionary. Here's the code for the test script I am posting to > > - > > > -- > > #!/usr/bin/python > > > import os > > import cgi > > import sys > > > print "Content Type: text/plain\n\n" > > print "Hello CGI World !\n" > > > for key in os.environ: > > print key + "= " + os.environ[key] > > > print cgi.FieldStorage() > > > print sys.stdin.read() > > -- > > > And here's the output I see .. > > > -- > > Hello CGI World ! > > > HTTP_REFERER=http://learnpython/form.htm > > SERVER_SOFTWARE= Apache/2.2.4 (Win32)mod_python/3.3.1 Python/2.5.1 > > SCRIPT_NAME= /mptest.py > > SERVER_SIGNATURE= > > REQUEST_METHOD= POST > > SERVER_PROTOCOL= HTTP/1.1 > > QUERY_STRING= abc=ayz > > PATH= C:\Program Files\Internet Explorer;;C:\WINDOWS\system32;C: > > \WINDOWS;C:\WINDOWS\System32\Wbem;q:\bin;m:\cm\clearcase\bin;M:\PERL\NT > > \EXEC\BIN;m:\cm\clearcase\bin\nt;M:\Perl\NT\EXEC\BIN;m:\perl\nt\exec > > \bin;m:\cm\clearcase\utils;q:\bin;m:\opus;m:\tvcs;C:\highc331\bin;C: > > \Program Files\Rational\ClearCase\bin;C:\Program Files\Rational\common > > CONTENT_LENGTH= 86 > > HTTP_USER_AGENT= Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; > > SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727) > > HTTP_CONNECTION= Keep-Alive > > SERVER_NAME= learnpython > > REMOTE_ADDR= 127.0.0.1 > > PATHEXT= .COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH > > SERVER_PORT= 80 > > SERVER_ADDR= 127.0.0.1 > > DOCUMENT_ROOT= D:/Projects/LearnPython/www > > COMSPEC= C:\WINDOWS\system32\cmd.exe > > SCRIPT_FILENAME= D:/Projects/LearnPython/www/mptest.py > > SERVER_ADMIN= puneet.ar... at tekelec.com > > HTTP_HOST= learnpython > > SystemRoot= C:\WINDOWS > > HTTP_CACHE_CONTROL= no-cache > > REQUEST_URI= /mptest.py?abc=ayz > > HTTP_ACCEPT= */* > > WINDIR= C:\WINDOWS > > GATEWAY_INTERFACE= Python-CGI/1.1 > > REMOTE_PORT= 1081 > > HTTP_ACCEPT_LANGUAGE= en-us > > CONTENT_TYPE= application/x-www-form-urlencoded > > HTTP_ACCEPT_ENCODING= gzip, deflate > > > FieldStorage(None, None, []) > > > firstName=puneet&address=hawaii > > -- > > > I am posting to this script using a form with two text fields named > > firstName and address. > > > any clue where am I going wrong ? > > You don't need mod_python/cgihandler to run CGI scripts. Rather than > bring mod_python into the picture and confuse things, set up Apache to > run your script as a traditional CGI script instead. > > BTW, the fact that mod_python is loaded means that CGI scripts aren't > the only way of using Python available to you as you seem to think. > So, suggest you do some research as to what the differences are > between CGI and mod_python. > > Graham From horpner at yahoo.com Sat Jun 16 15:53:38 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Sat, 16 Jun 2007 19:53:38 GMT Subject: Python's "only one way to do it" philosophy isn't good? References: <1181368143.874341.273140@r19g2000prf.googlegroups.com> <1hzrsp4.7vjuav1aegg0tN%aleax@mac.com> <7SSci.35627$G23.1695@newsreading01.news.tds.net> <7xejkb23fe.fsf@ruckus.brouhaha.com> Message-ID: <6dXci.35643$G23.6531@newsreading01.news.tds.net> On 2007-06-16, Paul Rubin wrote: > Neil Cerutti writes: >> I vote for C++ as being astoundingly complex. But it provides >> complex features, e.g.,the machanisms it provides to deal with >> multiple inheritance, or generic, type-safe code. > > It gets off-topic but I'm not sure what advantage templates are > supposed to have over ML-like polymorphism. I don't know that much about ML. I know is does a really nice job of generic containers, as does C++. But can it 'foo' any type as easily as C++? template T foo(T); As an aside, templates are abusable for many sorts of valuable compile-time computations and type arithmetic, though I'd never write that code myself--it looks like death. C++ templates allow for fancy duck-typing in C++, which Python programmers love. The STL is a good example of the power of duck-typing (though it oughta been called quack-typing). -- Neil Cerutti From michael at jedimindworks.com Tue Jun 5 16:46:39 2007 From: michael at jedimindworks.com (Michael Bentley) Date: Tue, 5 Jun 2007 15:46:39 -0500 Subject: subprocess leaves child living In-Reply-To: <874plmgogn.fsf@merkury.smsnet.pl> References: <1181052375.551083.117390@p47g2000hsd.googlegroups.com> <874plmgogn.fsf@merkury.smsnet.pl> Message-ID: On Jun 5, 2007, at 3:01 PM, Rob Wolfe wrote: > Thomas Dybdahl Ahle writes: > >> But you can't ever catch sigkill. > > There is no protection against sigkill. > >> Isn't there a way to make sure the os kills the childprocess when the >> parrent dies? > > If the parent dies suddenly without any notification childprocesses > become zombies and there is no way to avoid that. Apologies for picking nits... But actually *that* is an orphan process. When a parent process dies and the child continues to run, the child becomes an orphan and is adopted by init. Orphan processes can be cleaned up on most Unices with 'init q' (or something very similar). Zombies on the other hand, are those processes that have completed execution but still have an entry in the process table. The cause of zombies AFAIK, is a parent that has failed to call wait(2). To clean up zombies, you can send a SIGCHLD signal to the parent process -- probably with 'kill -17' (but use 'kill -l' to find out what it is on your system). hth, Michael --- "I would rather use Java than Perl. And I'd rather be eaten by a crocodile than use Java." ? Trouser From cam.ac.uk at mh391.invalid Wed Jun 20 05:28:36 2007 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Wed, 20 Jun 2007 10:28:36 +0100 Subject: DFW Pythoneers Meeting THIS Saturday In-Reply-To: <1182325553.232470.205970@q75g2000hsh.googlegroups.com> References: <1182325553.232470.205970@q75g2000hsh.googlegroups.com> Message-ID: peter wrote: > Just a tad arrogant, don't you think, to put a notice of some local > event on an international forum without saying where it is? It says right in the subject line! DFW. If you don't know what DFW means, then it's probably not your local area. -- Michael Hoffman From pjb at informatimago.com Fri Jun 22 15:21:40 2007 From: pjb at informatimago.com (Pascal Bourguignon) Date: Fri, 22 Jun 2007 21:21:40 +0200 Subject: I need some cleanings tips and advice. References: <1182528064.446459.49420@n2g2000hse.googlegroups.com> <467bf4c9@news.nucleus.com> Message-ID: <87aburkd6j.fsf@thalassa.lan.informatimago.com> Neil Cerutti writes: > ["Followup-To:" header set to comp.lang.python.] > On 2007-06-22, Colin B. wrote: >> In comp.lang.perl.misc CleaningTips at gmail.com wrote: >>> Me and my buddy made a website called www.stupidpinheads.com, its >>> basically a free forum and free blog driven web site dedicated as a >>> source people can goto to find out how to clean and remove stains from >>> pretty much anything. Problem is, as of yet, you couldn't find out how >>> to clean anything right now cause the site is new and no one has found >>> it yet. >> >> Let's see if I get this right. >> >> You create a website for a subject that you know nothing about. Then you >> try to solicit content in a bunch of programming language newsgroups. >> >> Wow, that's pretty pathetic, even for a google-groups poster! > > Maybe they lost the business plan. It's not surprising, since it > was probably written on a napkin. No problem with that, we can help: +-----------------+ | BUSINESS PLAN | +-----------------+ *%* 1- Make a web site about stains 2- ??? 3- Profit! -- __Pascal Bourguignon__ http://www.informatimago.com/ NOTE: The most fundamental particles in this product are held together by a "gluing" force about which little is currently known and whose adhesive power can therefore not be permanently guaranteed. From robert.rawlins at thinkbluemedia.co.uk Wed Jun 27 10:29:28 2007 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins - Think Blue) Date: Wed, 27 Jun 2007 15:29:28 +0100 Subject: Zip File Woes In-Reply-To: <03ca01c7b8c4$ebd69d40$c383d7c0$@rawlins@thinkbluemedia.co.uk> References: <03ca01c7b8c4$ebd69d40$c383d7c0$@rawlins@thinkbluemedia.co.uk> Message-ID: <03dd01c7b8c7$91e62410$b5b26c30$@rawlins@thinkbluemedia.co.uk> Just as an update guys: Before my zip code featured below I have another piece of code that creates the zip file from a binary string, like this: #f3 = open("Media/Media.zip", "wb") #f3.write(base64.decodestring(MediaBinary)) #f3.close Now, with that code commented out like that so the unzip code is running on the file generated last time the code was run it works fine, but if I try and unzip after the file has been freshly created I get that error, I've even tried placing a 2 second sleep command in between them and still get the problems. Thanks guys, Rob From: python-list-bounces+robert.rawlins=thinkbluemedia.co.uk at python.org [mailto:python-list-bounces+robert.rawlins=thinkbluemedia.co.uk at python.org] On Behalf Of Robert Rawlins - Think Blue Sent: 27 June 2007 15:10 To: python-list at python.org Subject: Zip File Woes Hello Guys, I'm having a MASSIVE headache today with zip files, I had it working a while ago but it all seems to have stopped in the past 30 minutes and I can't figure out why. I'm simply trying to write a function that will unzip a file, simple as that. I've currently got this code: Import zipfile zip = zipfile.ZipFile('Media/Media.zip', 'r') unzip(zip) zip.close() def unzip(zip): for name in zip.namelist(): newname = 'Media/%s' % (name) file(newname, 'wb').write(zip.read(name)) Now when I try and run this i get the following error message: 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 However, if I copy the zip file off the unit client onto my windows box and unzip it and it works absolutely perfectly, all the files are extracted as I would expect, which leads me to think the zip file is fine, and i must just be missing something in my code. Any ideas guys? I'm tearing my hair out here. Rob -------------- next part -------------- An HTML attachment was scrubbed... URL: From nogradi at gmail.com Wed Jun 13 06:03:39 2007 From: nogradi at gmail.com (Daniel Nogradi) Date: Wed, 13 Jun 2007 12:03:39 +0200 Subject: Dive into Python 5.5 In-Reply-To: <1181724020.770062.286220@o11g2000prd.googlegroups.com> References: <1181724020.770062.286220@o11g2000prd.googlegroups.com> Message-ID: <5f56302b0706130303j7376b35dge2d507b38841e254@mail.gmail.com> > class UserDict: > def __init__(self, dict=None): > self.data = {} > if dict is not None: self.update(dict) > > I just don't understant this code, as it is not also mention in the > book. the update is a method of a dict right? in my understanding the > last statement should be self.data.update(dict). > > someone please explain to me what happen where? You are right, this code will not work, and your suggestion is a reasonable one. HTH, Daniel From doug at alum.mit.edu Sat Jun 30 17:19:04 2007 From: doug at alum.mit.edu (Douglas Alan) Date: Sat, 30 Jun 2007 17:19:04 -0400 Subject: Python's "only one way to do it" philosophy isn't good? References: <1182750077.570603.160240@q69g2000hsb.googlegroups.com> <7xir9cbm0g.fsf@ruckus.brouhaha.com> <7xejjzmk7u.fsf@ruckus.brouhaha.com> <7xy7i7xjl5.fsf@ruckus.brouhaha.com> <1182872972.417776.78650@o11g2000prd.googlegroups.com> <1182873568.454491.302860@e9g2000prf.googlegroups.com> <7xps3iy73h.fsf@ruckus.brouhaha.com> <7x1wfudtw9.fsf@ruckus.brouhaha.com> <7x8xa1pbg8.fsf@ruckus.brouhaha.com> <7xhcopnvcg.fsf@ruckus.brouhaha.com> Message-ID: I wrote: > P.S. The last time I took a language class (about five or six years > ago), the most interesting languages I thought were descended from > Self, not any functional language. (And Self, of course is descended > from Smalltalk, which is descended from Lisp.) I think that Cecil is the particular language that I was most thinking of: http://en.wikipedia.org/wiki/Cecil_programming_language |>oug From jstroud at mbi.ucla.edu Mon Jun 11 20:30:00 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Mon, 11 Jun 2007 17:30:00 -0700 Subject: Python Help!!! In-Reply-To: References: Message-ID: Elfine Peterson Tjio wrote: > I'm trying to make a program that reads Fasta file and print it out. I used the SeqIO module and the results is: > > 'ATGGTCAT....SingleAlphabet()' > > For this purpose, should I use SeqIO or Fasta? > > for example: > > from Bio import SeqIO > > or > > from Bio import Fasta > > I want it to print every letter. Can anyone point me to the right direction. The newest biopython tutorial or book recommendation will be appreciated, too. This question is better for the biopython list. Also, your subject line should be more specific with respect to your actual question. James From bcannon at gmail.com Wed Jun 20 21:52:52 2007 From: bcannon at gmail.com (Brett C.) Date: Thu, 21 Jun 2007 01:52:52 -0000 Subject: Secured CPython interpreter in embedded situations Message-ID: <1182390772.805912.294400@d30g2000prg.googlegroups.com> I have been working on making Python a secure interpreter to run when embedded in terms of resources with an object representation (e.g., files but not memory or CPU). To save myself from repeating myself and missing some details of exactly what I have done I am going to point to a post to my Python blog (and I have replied to people in the comments so if you have a question it may have been answered there): http://sayspy.blogspot.com/2007/05/i-have-finished-securing-python.html . With no one having told me they have found a hole in the design I am ready to make a wider announcement here. If you have a use for a secured CPython interpreter then please have a look (although the work generalizes to the language, I implemented it in CPython since that is what I know best). This work is not about replacing rexec, though! It secures the entire interpreter and is not about running some Python code at a higher privilege level than some other code. If you manage to check out the code and get it run, let me know (I have one report of someone getting it to compile but erroring out immediately but I can't reproduce it as it still works for me after a ``make distclean``). And if you do manage to break the security model (manage to open a file, import a module that is not whitelisted, etc.), then PLEASE let me know! If the work holds up I will make an announcement in c.l.py.a and then start the process to get my changes into the trunk so that you don't need to use a branch. Thanks in advance to anyone who gives the code a whirl. -Brett From ping.nsr.yeh at gmail.com Mon Jun 18 13:21:28 2007 From: ping.nsr.yeh at gmail.com (Ping) Date: Mon, 18 Jun 2007 17:21:28 -0000 Subject: A patch to support L.count(value, cmp=None, key=None) In-Reply-To: <1182098963.177045.15110@j4g2000prf.googlegroups.com> References: <1181850818.567840.251090@x35g2000prf.googlegroups.com> <1181853479.914070.217270@i13g2000prf.googlegroups.com> <1181855184.511137.100870@z28g2000prd.googlegroups.com> <1181916937.648267.163070@z28g2000prd.googlegroups.com> <1181981527.960296.135820@i13g2000prf.googlegroups.com> <1182026221.039617.56320@n2g2000hse.googlegroups.com> <1182094967.099444.91410@n15g2000prd.googlegroups.com> <1182098963.177045.15110@j4g2000prf.googlegroups.com> Message-ID: <1182187288.141498.45010@n15g2000prd.googlegroups.com> Hi, I patched Objects/listobject.c to support L.count(value, cmp=None, key=None). I tested it with the same script above by replacing slist with built-in list. It worked correctly with this small test. The patch is below (126 lines, I hope that's not too big to be pasted here). This is the first time that I modified CPython source, and I may very well make mistakes in (lack of) reference counting or other things. Comments and corrections are much appreciated! Regards, Ping --- Objects/listobject.c.orig Sun Oct 29 05:39:10 2006 +++ Objects/listobject.c Tue Jun 19 01:04:30 2007 @@ -919,12 +919,12 @@ /* Comparison function. Takes care of calling a user-supplied * comparison function (any callable Python object), which must not be - * NULL (use the ISLT macro if you don't know, or call PyObject_RichCompareBool - * with Py_LT if you know it's NULL). - * Returns -1 on error, 1 if x < y, 0 if x >= y. + * NULL. + * Returns -9 on error, otherwise return the result of the user- supplied + * comparison. */ static int -islt(PyObject *x, PyObject *y, PyObject *compare) +custom_compare(PyObject *x, PyObject *y, PyObject *compare) { PyObject *res; PyObject *args; @@ -936,7 +936,7 @@ */ args = PyTuple_New(2); if (args == NULL) - return -1; + return -9; Py_INCREF(x); Py_INCREF(y); PyTuple_SET_ITEM(args, 0, x); @@ -944,16 +944,28 @@ res = PyObject_Call(compare, args, NULL); Py_DECREF(args); if (res == NULL) - return -1; + return -9; if (!PyInt_Check(res)) { Py_DECREF(res); PyErr_SetString(PyExc_TypeError, "comparison function must return int"); - return -1; + return -9; } i = PyInt_AsLong(res); Py_DECREF(res); - return i < 0; + return i; +} + +/* "less-than" Comparison function. Calls custom_compare to do the + * actual comparison. + * Returns -1 on error, 1 if x < y, 0 if x >= y. + */ +static int +islt(PyObject *x, PyObject *y, PyObject *compare) +{ + int res = custom_compare(x, y, compare); + if (res == -9) return -1; + return res < 0; } /* If COMPARE is NULL, calls PyObject_RichCompareBool with Py_LT, else calls @@ -2232,16 +2244,44 @@ } static PyObject * -listcount(PyListObject *self, PyObject *v) +listcount(PyListObject *self, PyObject * args, PyObject *kwds) { + PyObject *v = NULL; /* value for counting */ + PyObject *compare = NULL; + PyObject *keyfunc = NULL; + static char *kwlist[] = {"value", "cmp", "key", 0}; + PyObject *item; Py_ssize_t count = 0; Py_ssize_t i; + int cmp; + + assert(self != NULL); + assert (PyList_Check(self)); + if (args != NULL) { + if (!PyArg_ParseTupleAndKeywords(args, kwds, "O| OO:count", + kwlist, &v, &compare, &keyfunc)) + return NULL; + } + if (compare == Py_None) + compare = NULL; + if (keyfunc == Py_None) + keyfunc = NULL; for (i = 0; i < self->ob_size; i++) { - int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ); + item = self->ob_item[i]; + if (keyfunc != NULL) { + item = PyObject_CallFunctionObjArgs(keyfunc, item, + NULL); + } + + if (compare != NULL) { + cmp = custom_compare(item, v, compare); + } else { + cmp = PyObject_RichCompareBool(item, v, Py_EQ); + } if (cmp > 0) count++; - else if (cmp < 0) + else if (cmp == -9) return NULL; } return PyInt_FromSsize_t(count); @@ -2404,7 +2444,7 @@ PyDoc_STRVAR(index_doc, "L.index(value, [start, [stop]]) -> integer -- return first index of value"); PyDoc_STRVAR(count_doc, -"L.count(value) -> integer -- return number of occurrences of value"); +"L.count(value, cmp=None, key=None) -> integer -- return number of occurrences of value [in the key] [with the cmp function]."); PyDoc_STRVAR(reverse_doc, "L.reverse() -- reverse *IN PLACE*"); PyDoc_STRVAR(sort_doc, @@ -2422,7 +2462,7 @@ {"pop", (PyCFunction)listpop, METH_VARARGS, pop_doc}, {"remove", (PyCFunction)listremove, METH_O, remove_doc}, {"index", (PyCFunction)listindex, METH_VARARGS, index_doc}, - {"count", (PyCFunction)listcount, METH_O, count_doc}, + {"count", (PyCFunction)listcount, METH_VARARGS | METH_KEYWORDS, count_doc}, {"reverse", (PyCFunction)listreverse, METH_NOARGS, reverse_doc}, {"sort", (PyCFunction)listsort, METH_VARARGS | METH_KEYWORDS, sort_doc}, {NULL, NULL} /* sentinel */ From showell30 at yahoo.com Tue Jun 12 19:13:10 2007 From: showell30 at yahoo.com (Steve Howell) Date: Tue, 12 Jun 2007 16:13:10 -0700 (PDT) Subject: SimplePrograms challenge In-Reply-To: <466F27A3.8000106@gmail.com> Message-ID: <401059.55617.qm@web33506.mail.mud.yahoo.com> --- Steven Bethard wrote: > Steve Howell wrote: > > --- George Sakkis wrote: > >> from itertools import count, ifilter > >> def sieve(): > >> seq = count(2) > >> while True: > >> p = seq.next() > >> seq = ifilter(p.__rmod__, seq) > >> yield p > [snip] > > Is there a way to broaden the problem somehow, so > that > > it can be a longer solution and further down on > the > > page, and so that I can continue to enforce my > > somewhat arbitrary rule of ordering examples by > how > > long they are? > > How about we just comment it better? > > import itertools > > def iter_primes(): > # an iterator of all numbers between 2 and > +infinity > numbers = itertools.count(2) > > # generate primes forever > while True > > # generate the first number from the > iterator, > # which should always be a prime > prime = numbers.next() > yield prime > > # lazily remove all numbers from the > iterator that > # are divisible by prime we just selected > numbers = itertools.ifilter(prime.__rmod__, > numbers) > > I think that's 17-ish, though you could shrink it > down by removing some > of the spaces. > Actually, just one small caveat--I'd still want the program to print out the results. I think I've followed that convention for all the other programs. ____________________________________________________________________________________ Be a better Heartthrob. Get better relationship answers from someone who knows. Yahoo! Answers - Check it out. http://answers.yahoo.com/dir/?link=list&sid=396545433 From borud-news at borud.no Sat Jun 23 11:56:16 2007 From: borud-news at borud.no (Bjorn Borud) Date: 23 Jun 2007 17:56:16 +0200 Subject: The Modernization of Emacs: terminology buffer and keybinding References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182272495.990807.99110@a26g2000pre.googlegroups.com> <87tzt3ihev.fsf@kobe.laptop> <1182370216.961241.6960@n60g2000hse.googlegroups.com> <1182549831.068658.123870@i13g2000prf.googlegroups.com> Message-ID: [Twisted ] | | That sort of negative-sum thinking is alien to me. Software being easy | for beginners to get started using does not in and of itself detract | from its value to expert users. the fact that you imply that this is my argument tells me that either you have not paid attention, or you have a raging inferiority complex. given the sum of your postings so far I'd say that you neither are, nor consider yourself, a cerebral sort of person, so this narrows it down somewhat (although not to the exclusion of you not having paid attention). -Bj?rn From grahn+nntp at snipabacken.dyndns.org Tue Jun 19 10:35:12 2007 From: grahn+nntp at snipabacken.dyndns.org (Jorgen Grahn) Date: 19 Jun 2007 14:35:12 GMT Subject: Convert to C/C++? References: <1181852202.897976.312280@j4g2000prf.googlegroups.com> Message-ID: On Thu, 14 Jun 2007 13:16:42 -0700, SpreadTooThin wrote: > I am wondering if someone who knows the implemention of python's time > could help converting this to c/c++.... > > nanoseconds = int(time.time() * 1e9) [straightforward non-time arithmetic snipped] > > vs unix gettimeofday.... > > int gettimeofday(struct timeval *tp, struct timezone *tzp); > > struct timeval { > long tv_sec; /* seconds since Jan. 1, 1970 */ > long tv_usec; /* and microseconds */ > }; Quite simply, time.time() corresponds to tv_sec + tv_usec/1e6, modulo any rounding and numerical errors introduced by the floating-point format used. > struct timezone { > int tz_minuteswest; /* of Greenwich */ > int tz_dsttime; /* type of dst correction to apply */ > }; The struct timezone is not set by Linux/glibc gettimeofday(), so you can happily ignore it. You only want UTC time anyway. /Jorgen -- // Jorgen Grahn R'lyeh wgah'nagl fhtagn! From facundo at taniquetil.com.ar Fri Jun 29 19:32:09 2007 From: facundo at taniquetil.com.ar (Facundo Batista) Date: Fri, 29 Jun 2007 23:32:09 +0000 (UTC) Subject: Rappresenting infinite References: <1182940919.351011.267020@n2g2000hse.googlegroups.com> <1182945569.081290.40870@c77g2000hse.googlegroups.com> <20070628234618.2907b52d@localhost> <20070629004542.31bbc7ac@localhost> Message-ID: mmanns at gmx.net wrote: >> No. You can make one that fits your requirements, though. > > I am struggling to oversee the implications of design choices for inf > behaviour - especially if it comes to comparison with float type inf. > The type in my application contains a gmpy.mpq and a float that is > always kept between -1 and 1 by adding to the mpq on each operation. > I am looking for a robust inf design for this type. (Note: mpq and > float inf do not compare). Infinity, and all its behaviours are well defined in the General Decimal Arithmetic Specification, here at http://www2.hursley.ibm.com/decimal/. You can always pass your float to Decimal through string, and then do there *all* the operations: >>> from decimal import * >>> a = 3.4 >>> b = 1.0e1000 >>> Decimal(str(a)) Decimal("3.4") >>> Decimal(str(b)) Decimal("Infinity") >>> Decimal(str(b)) / 0 Decimal("Infinity") >>> Decimal(str(b)) * 0 Traceback (most recent call last): File "", line 1, in File "/usr/lib/python2.5/decimal.py", line 1140, in __mul__ return context._raise_error(InvalidOperation, '(+-)INF * 0') File "/usr/lib/python2.5/decimal.py", line 2325, in _raise_error raise error, explanation decimal.InvalidOperation: (+-)INF * 0 >>> setcontext(ExtendedContext) >>> Decimal(str(b)) * 0 Decimal("NaN") >>> Regards, -- . Facundo . Blog: http://www.taniquetil.com.ar/plog/ PyAr: http://www.python.org/ar/ From S.Mientki-nospam at mailbox.kun.nl Sat Jun 23 03:41:05 2007 From: S.Mientki-nospam at mailbox.kun.nl (Stef Mientki) Date: Sat, 23 Jun 2007 09:41:05 +0200 Subject: is this a valid import sequence ? In-Reply-To: References: <4f97$467c254d$d443bb3a$9522@news.speedlinq.nl> Message-ID: <9a7d5$467ccd70$d443bb3a$5322@news.speedlinq.nl> thanks Steven, Steven D'Aprano wrote: > On Fri, 22 Jun 2007 21:43:40 +0200, Stef Mientki wrote: > >> This might be a very weird construction, >> but it's the most easy way in translating another language into Python (for simulation). >> >> Although it works, I like to know if this a valid construction: > > Since it works, how can it NOT be a valid construction? ok that seems a plausible reasoning > > However, using global variables is almost always a bad idea. Passing > parameters around is really cheap in Python, that's almost always a better > solution. Yes I know, but that's a fact of the "real thing" I'm simulating ;-) cheers, Stef > > From borud-news at borud.no Fri Jun 22 10:38:37 2007 From: borud-news at borud.no (Bjorn Borud) Date: 22 Jun 2007 16:38:37 +0200 Subject: The Modernization of Emacs: terminology buffer and keybinding References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182272495.990807.99110@a26g2000pre.googlegroups.com> <87tzt3ihev.fsf@kobe.laptop> <1182370216.961241.6960@n60g2000hse.googlegroups.com> <85zm2ufjpb.fsf@lola.goethe.zz> <1182372592.803332.288260@u2g2000hsc.googlegroups.com> <1182373919.262388.100740@c77g2000hse.googlegroups.com> <85r6o6fhkb.fsf@lola.goethe.zz> <1182375045.626510.188170@m36g2000hse.googlegroups.com> Message-ID: [Twisted ] | | I think it is quite relevant. Clunky computer interfaces may not be so | dramatically dangerous, but they certainly can hamper productivity. | Between Windows bugs and gratuitous misfeatures (e.g. DRM) and Unix | clunkiness, billions of dollars of potential productivity is lost | worldwide every *month*. bah, UNIX is not user hostile; it is just selective about its friends. -Bj?rn From smitty1e at gmail.com Sun Jun 10 19:52:04 2007 From: smitty1e at gmail.com (smitty1e) Date: Sun, 10 Jun 2007 23:52:04 -0000 Subject: codecs / subprocess interaction: utf help requested In-Reply-To: <1181513440.723767.40650@a26g2000pre.googlegroups.com> References: <1181510260.821468.151320@h2g2000hsg.googlegroups.com> <1181513440.723767.40650@a26g2000pre.googlegroups.com> Message-ID: <1181519524.125258.40410@q75g2000hsh.googlegroups.com> On Jun 10, 6:10 pm, John Machin wrote: > On Jun 11, 7:17 am, smitty1e wrote: > > > The first print statement does what you'd expect. > > The second print statement has rather a lot of rat in it. > > The goal here is to write a function that will return the man page for > > some command (mktemp used as a short example here) as text to client > > code, where the groff markup will be chopped to extract all of the > > command options. Those options will eventually be used within an > > emacs mode, all things going swimmingly. > > I don't know what's going on with the piping in the second version. > > It looks like the output of p0 gets converted to unicode at some > > point, > > Whatever gave you that idea? > > > but I might be misunderstanding what's going on. The 4.8 > > codecs module documentation doesn't really offer much enlightment, > > nor google. About the only other place I can think to look would be > > the unit test cases shipped with python. > > Get your head out of the red herring factory; unicode, "utf" (which > one?) and codecs have nothing to do with your problem. Think about > looking at your own code and at the bzip2 documentation. > > > > > Sort of hoping one of the guru-level pythonistas can point to > > illumination, or write something to help out the next chap. This > > might be one of those catalytic questions, the answer to which tackles > > five other questions you didn't really know you had. > > Thanks, > > Chris > > --------------------------- > > #!/usr/bin/python > > import subprocess > > > p = subprocess.Popen(["bzip2", "-c", "-d", "/usr/share/man/man1/mktemp. > > 1.bz2"] > > , stdout=subprocess.PIPE) > > stdout, stderr = p.communicate() > > print stdout > > > p0 = subprocess.Popen(["cat","/usr/share/man/man1/mktemp.1.bz2"], > > stdout=subprocess.PIPE) > > p1 = subprocess.Popen(["bzip2"], stdin=p0.stdout , > > stdout=subprocess.PIPE) > > stdout, stderr = p1.communicate() > > print stdout > > --------------------------- > > You left out the command-line options for bzip2. The "rat" that you > saw was the result of compressing the already-compressed man page. > Read this:http://www.bzip.org/docs.html > which is a bit obscure. The --help output from my copy of an antique > (2001, v1.02) bzip2 Windows port explains it plainly: > """ > If invoked as `bzip2', default action is to compress. > as `bunzip2', default action is to decompress. > as `bzcat', default action is to decompress to stdout. > > If no file names are given, bzip2 compresses or decompresses > from standard input to standard output. > """ > > HTH, > John Don't I feel like the biggest dork on the planet. I had started with >cat /usr/share/man/man1/paludis.1.bz2 | bunzip2 then proceeded right to a self-foot-shoot when I went to python. *sigh* Thanks for the calibration, sir. Rm C From bugmagnet at gmail.com Thu Jun 21 05:23:43 2007 From: bugmagnet at gmail.com (bugmagnet at gmail.com) Date: Thu, 21 Jun 2007 09:23:43 -0000 Subject: Internationalised email subjects In-Reply-To: <1182417604.446766.47660@e9g2000prf.googlegroups.com> References: <1182337500.638044.63470@e9g2000prf.googlegroups.com> <46791592$0$5719$edfadb0f@dread14.news.tele.dk> <1182346499.123234.279880@e9g2000prf.googlegroups.com> <1182417604.446766.47660@e9g2000prf.googlegroups.com> Message-ID: <1182417823.793678.323530@a26g2000pre.googlegroups.com> That's really strange. The chinese characters I am inputing into the post are not being displayed. Basically, what I am doing is this: h = Header('(Some Chinese characters inserted here', 'GB2312') And when I run this code, I receive the following error message: UnicodeDecodeError: 'gb2312' codec can't decode bytes in position 2-3: illegal multibyte sequence Any idea what I may be doing wrong? How do I convert Chinese characters into something like p\xf6stal in the original code posted by Martin? Can someone point me in the right direction? I'm not even sure what class/method to look into for this. From vsaini at cybage.com Wed Jun 20 01:19:54 2007 From: vsaini at cybage.com (Vikas Saini) Date: Wed, 20 Jun 2007 10:49:54 +0530 Subject: Execute script on remote computer In-Reply-To: Message-ID: <0B5158DBDB894441A80F592817523533058C3ECF@postoffice.cybage.com> The os I am using is window Xp. Thanks&Regards, Vikas Saini **** Do or do not. There is no try. **** -----Original Message----- From: Evan Klitzke [mailto:evan at yelp.com] Sent: Wednesday, June 20, 2007 10:21 AM To: Vikas Saini Cc: python-list at python.org Subject: Re: Execute script on remote computer On 6/19/07, Vikas Saini wrote: > I am trying to run the agent on one machine that will execute the script of > a remote machine. It's not clear what OS you're using. But if you're running a Unix/Linux system and it's a relatively simple script that you want to run, you should just use the ssh command coupled with the name of the command you want to run (you don't even need the agent to use python, necessarily). For example, ssh user at foo bar Will ssh to machine 'foo' as user 'user' and execute command 'bar' on that machine (rather than launching a shell, which is what ssh will do if no command is specified). When the command exits, ssh will exit as well. -- Evan Klitzke "Legal Disclaimer: This electronic message and all contents contain information from Cybage Software Private Limited which may be privileged, confidential, or otherwise protected from disclosure. The information is intended to be for the addressee(s) only. If you are not an addressee, any disclosure, copy, distribution, or use of the contents of this message is strictly prohibited. If you have received this electronic message in error please notify the sender by reply e-mail to and destroy the original message and all copies. Cybage has taken every reasonable precaution to minimize the risk of malicious content in the mail, but is not liable for any damage you may sustain as a result of any malicious content in this e-mail. You should carry out your own malicious content checks before opening the e-mail or attachment." www.cybage.com From python at jayloden.com Mon Jun 18 13:45:25 2007 From: python at jayloden.com (Jay Loden) Date: Mon, 18 Jun 2007 13:45:25 -0400 Subject: copy locked files In-Reply-To: <893A44FF792E904A97B7515CE34191460102D650@volimxs01.thqinc.com> References: <1182178224.486883.203330@q75g2000hsh.googlegroups.com> <893A44FF792E904A97B7515CE34191460102D650@volimxs01.thqinc.com> Message-ID: <4676C4B5.8080102@jayloden.com> Adam Pletcher wrote: > Do you mean files marked in-use by the OS, like DLLs used by an open > application? > > There shouldn't be anything preventing you from copying in-use files, or > even read-only files if that's what you meant: > > import shutil > shutil.copy('C:\\my_application\\test.dll', > 'C:\\new_folder\\test.dll') > > Although you can't move or delete an in-use file, AFAIK. I had to deal with a similar problem using the Win32 API in C recently. You can't move or delete an in-use file, as Adam noted. However, you *can* rename a file (see http://www.nntp.perl.org/group/perl.makemaker/2006/01/msg2437.html as a nice summation of the problem), and MoveFileEx() in the Win32 API has a flag that will delete a file on the next reboot. As far as copying an in-use file, there are two possibilities I can think of. One would be to try disconnecting the lock using the openfiles command (this may not exist on all versions of Windows, but it is there on my WinXP box). The other would be to use Locked Files Wizard (used to be called CopyLock) http://noeld.com/programs.asp?cat=misc It comes with a command line version of the tool that you can call from your Python script as necessary. Neither is an ideal solution but I can't find any other suggestions out there on dealing with this from Python. HTH, -Jay From steve at REMOVE.THIS.cybersource.com.au Mon Jun 25 07:46:02 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Mon, 25 Jun 2007 21:46:02 +1000 Subject: is this a valid import sequence ? References: <4f97$467c254d$d443bb3a$9522@news.speedlinq.nl> <137qo1egg4v1k04@corp.supernews.com> <1i0694u.1n6evsntoei0wN%aleax@mac.com> <1i06hm3.1ii0h87p707f2N%aleax@mac.com> <1182748080.330171.324800@g4g2000hsf.googlegroups.com> Message-ID: On Mon, 25 Jun 2007 05:08:00 +0000, Michele Simionato wrote: > On Jun 24, 1:29 pm, Steven D'Aprano >> I would like to hear your opinion of whether the >> following two functions are equally as wrong: >> >> def f1(gizmo): >> global spam # holds the frommet needed for the gizmo >> gizmo.get_frommet(spam) >> >> def f2(gizmo): >> # global spam holds the frommet needed for the gizmo >> gizmo.get_frommet(spam) >> >> I'm sure they're both wrong, but I'd like to know if there are degrees of >> wrongness. > > I am not Alex Martelli, but I will tell you my opinion anyway. > To me f2 is not wrong: at worse you can say that the comment > is redundant since it is already clear from the code that > spam is a global, but it is not a big deal. As a code > reviewer I would not have had issues with f2. OTOH I would > have had serious issues with f1. Since the global > statement in correct Python code is solely used to declare > that a global variable is being set in an inner scope, I > would have to guess that: > > 1. function f1 wrong; maybe the author cut and pasted it > from someplace, forgetting the line where the global > variable spam was set; > > 2. maybe f1 is right, but then the author forgot to remove > the global declaration after the cut & paste; > > 3. the author does not know Python, and he believes that he > has to use global to denote the fact that the method > gizmo.get_frommet(spam) is setting a global variable. > > So I would have had to look at get_frommet to see that actually > 'spam' is not set there, Why do you do that? I'm not arguing that you shouldn't, but I'm trying to understand your reasoning. Are you assuming (for the sake of the argument) that there's a bug somewhere in the code? If you're trying to track down a bug, you'll likely need to look at get_frommet regardless of the presence or absence of the global statement. Or are you trying to analyze the entire module? If so, you also have to dig into get_frommet. (I repeat, I'm not saying you shouldn't, but I'm trying to understand why you think the way you do.) > and finally I would have reached the > conclusion that > > 4. the author was completely wrong and used global without > knowing its meaning. So you're with Alex that "redundant" == "wrong"? I still can't my head around that. To me, redundant and wrong are orthogonal, not synonyms. This code is wrong but not redundant (assuming you have a need for such a function): def sin_deg(x): """Return the sine of x degrees.""" return math.sin(x/math.pi*180) # oops! should be x*math.pi/180 To me, this code is redundant but not wrong: def sin(x): return math.sin(x) It's not wrong, because it does everything that it is supposed to do, and nothing that it isn't supposed to do. Am I wrong? -- Steven. From aisaac at american.edu Sat Jun 23 10:57:46 2007 From: aisaac at american.edu (Alan Isaac) Date: Sat, 23 Jun 2007 14:57:46 GMT Subject: relative import question: packaging scripts Message-ID: What is the recommended packaging of demo scripts or test scripts for a package that has modules that use relative imports? Example: Suppose I have the package structure: package/ __init__.py subpackage1/ __init__.py moduleY.py subpackage2/ __init__.py moduleZ.py Important detail: moduleZ uses a relative import to access moduleY. The problem: I have a script test.py that I want to distribute with the package. It will import moduleZ to illustrate or test the module's use. Is it the case that this script cannot reasonably be bundled with `package`? (I.e., within its directory structure.) I cannot put it in the `subpackage2` directory and just import moduleZ, because then I will get ValueError: Attempted relative import in non-package I cannot put it in the `package` directory and import subpackage2.moduleZ, because then I will get ValueError: Attempted relative import beyond toplevel package The script could use path manipulation to find `package`, as suggested by Alex Martelli http://mail.python.org/pipermail/python-list/2007-May/438250.html and others. However it has also been claimed that this approach is an insane for any shared code. Is it? I do not want to assume the package will be installed: a user should be able to play with it without installing it. In this case, does the only "sane" thing to become to require any user to take the step of inserting the package location into sys.path and have test.py rely on the user having done this? Thank you, Alan Isaac From sbellon at sbellon.de Fri Jun 29 05:57:13 2007 From: sbellon at sbellon.de (Stefan Bellon) Date: Fri, 29 Jun 2007 11:57:13 +0200 Subject: Hooking __import__ when embedding the interpreter Message-ID: <20070629115713.5d0d8dd8@cube.tz.axivion.com> Hi all, I am embedding the Python interpreter using the C API and extending it using modules generated by SWIG. In order to guarantee consistency about importing those modules, I would like to "hook" into the Python's import statement and __import__ function and do some checks there. I have experimented a bit already, but still have a few questions and would be happy if anybody from the group could shed some light on those. At present, I have the following test code: #include #include static PyObject * __import__(PyObject *self, PyObject *args) { char *name; PyObject *globals = NULL; PyObject *locals = NULL; PyObject *fromlist = NULL; if (!PyArg_ParseTuple (args, "s|OOO:__import__", &name, &globals, &locals, &fromlist)) { return NULL; } PyObject *m = PyDict_GetItemString(PyImport_GetModuleDict(), name); if (m) { Py_INCREF(m); return m; } if (!strcmp(name, "foobar")) // to be replaced by the consistency check! { PyErr_SetString (PyExc_ImportError, "cannot import module right now"); return NULL; } return PyImport_ImportModuleEx(name, globals, locals, fromlist); } static PyMethodDef import_hook[] = { { "__import__", __import__ }, { NULL, NULL } }; int main() { Py_Initialize(); Py_InitModule("import_hook", import_hook); PyObject_SetAttrString (PyImport_ImportModule("__builtin__"), "__import__", PyObject_GetAttrString (PyImport_ImportModule("import_hook"), "__import__")); PyRun_InteractiveLoop(stdin, ""); Py_Finalize(); } The code of __import__ above was inspired by the code of builtin__import__ in Python/bltinmodule.c with the addition of the early exit if the module is already loaded and the "consistency" check which I reduced to some "cannot load module foobar" for ease of the test case. Now to my open questions. 1) The above code seems to work ok when using the "import" statement, but it does not when using the dynamic __import__ function. If using it that way, I get: >>> sys=__import__("sys") Traceback (most recent call last): File "", line 1, in ? SystemError: new style getargs format but argument is not a tuple What am I missing in order to get the __import__ function covered as well? 2) Another point is, that I need to check _from where_ the module is imported. In fact, this is going to become part of the consistency check condition. How can I find out from which module the import was initiated? 3) My final point is related to 2) ... if I get to the module object, then how do I get at the source file name of that? I noticed that when a .pyc is available, then this is preferred. I'd like to get at the .py file itself. Is this available or do I just have to strip off the trailing 'c' (or 'o'?) if present (seems hacky to me). I am very much looking forward to your suggestions! Greetings, Stefan -- Stefan Bellon From lobais at gmail.com Thu Jun 7 09:48:51 2007 From: lobais at gmail.com (Thomas Dybdahl Ahle) Date: Thu, 07 Jun 2007 15:48:51 +0200 Subject: subprocess leaves child living References: <1181199653.183854.245560@g4g2000hsf.googlegroups.com> Message-ID: Den Thu, 07 Jun 2007 07:00:53 +0000 skrev reed: > On Jun 5, 7:58 am, Thomas Dybdahl Ahle wrote: >> Hi, When I do a small program like >> >> from subprocess import Popen >> popen = Popen(["ping", "google.com"]) from time import sleep >> sleep(100) >> >> start it and kill it, the ping process lives on. Is there a way to >> ensure that the ping process is always killed when the python process >> is? >> I can't use atexit, as ping then isn't killed when python is killed "in >> the hard way" > > > > pid = popen.pid > pidfile = open('/usr/local/var/somefile.pid', 'w') pidfile.write('pid') > pidfile.close() > then you can check if it is still running when your ?program? restarts > and can kill it. If it restarts yeah. > maybe not the perfect answer, but it answers an imperfect question. Any details you need? From benedict.verheyen at gmail.com Mon Jun 11 08:42:33 2007 From: benedict.verheyen at gmail.com (Benedict Verheyen) Date: Mon, 11 Jun 2007 14:42:33 +0200 Subject: python-ldap for Python 2.5 on Windows? In-Reply-To: References: <1181323389.805143.236480@i38g2000prf.googlegroups.com> Message-ID: Thorsten Kampe schreef: >> I'm on Vista (boohoo :(), what's your platform? > > XP SP2 Hmmm it thought so. So in my case it would be interesting to know how to build it so i can make a build that works on Vista too. Regards, Benedict From nagle at animats.com Sun Jun 10 12:43:47 2007 From: nagle at animats.com (John Nagle) Date: Sun, 10 Jun 2007 09:43:47 -0700 Subject: Python optimization (was Python's "only one way to do it" philosophy isn't good?) In-Reply-To: References: <1181368143.874341.273140@r19g2000prf.googlegroups.com> Message-ID: <9OVai.7525$u56.7287@newssvr22.news.prodigy.net> Josiah Carlson wrote: > Steven D'Aprano wrote: > >> On Sat, 09 Jun 2007 22:52:32 +0000, Josiah Carlson wrote: >> >>> the only thing that optimization currently does in Python at present >>> is to discard docstrings >> >> >> Python, or at least CPython, does more optimizations than that. Aside >> from >> run-time optimizations like interned strings etc., there are a small >> number of compiler-time optimizations done. >> >> Running Python with the -O (optimize) flag tells Python to ignore >> assert statements. Using -OO additionally removes docstrings. ... > > I would guess it is because some other data types may have side-effects. > On the other hand, a peephole optimizer could be written to trim out > unnecessary LOAD_CONST/POP_TOP pairs. > >> Some dead code is also optimized away: > > Obviously dead code removal happens regardless of optimization level in > current Pythons. > >> Lastly, in recent versions (starting with 2.5 I believe) Python >> includes a >> peephole optimizer that implements simple constant folding: > > Constant folding happens regardless of optimization level in current > Pythons. > So really, assert and docstring removals. Eh. It's hard to optimize Python code well without global analysis. The problem is that you have to make sure that a long list of "wierd things", like modifying code or variables via getattr/setattr, aren't happening before doing significant optimizations. Without that, you're doomed to a slow implementation like CPython. ShedSkin, which imposes some restrictions, is on the right track here. The __slots__ feature is useful but doesn't go far enough. I'd suggest defining "simpleobject" as the base class, instead of "object", which would become a derived class of "simpleobject". Objects descended directly from "simpleobject" would have the following restrictions: - "getattr" and "setattr" are not available (as with __slots__) - All class member variables must be initialized in __init__, or in functions called by __init__. The effect is like __slots__, but you don't have to explictly write declarations. - Class members are implicitly typed with the type of the first thing assigned to them. This is the ShedSkin rule. It might be useful to allow assignments like self.str = None(string) to indicate that a slot holds strings, but currently has the null string. - Function members cannot be modified after declaration. Subclassing is fine, but replacing a function member via assignment is not. This allows inlining of function calls to small functions, which is a big win. - Private function members (self._foo and self.__foo) really are private and are not callable outside the class definition. You get the idea. This basically means that "simpleobject" objects have roughly the same restrictions as C++ objects, for which heavy compile time optimization is possible. Most Python classes already qualify for "simpleobject". And this approach doesn't require un-Pythonic stuff like declarations or extra "decorators". With this, the heavy optimizations are possible. Strength reduction. Hoisting common subexpressious out of loops. Hoisting reference count updates out of loops. Keeping frequently used variables in registers. And elimination of many unnecessary dictionary lookups. Python could get much, much faster. Right now CPython is said to be 60X slower than C. It should be possible to get at least an order of magnitude over CPython. John Nagle From sjmachin at lexicon.net Mon Jun 11 15:16:12 2007 From: sjmachin at lexicon.net (John Machin) Date: Mon, 11 Jun 2007 12:16:12 -0700 Subject: Repository - file scanner In-Reply-To: <87zm36uy5g.fsf@rudin.co.uk> References: <1181331239.609059.320740@g4g2000hsf.googlegroups.com> <1181515276.379978.136400@z28g2000prd.googlegroups.com> <1181581520.733087.253380@q66g2000hsg.googlegroups.com> <87zm36uy5g.fsf@rudin.co.uk> Message-ID: <1181589372.177090.211860@i38g2000prf.googlegroups.com> On Jun 12, 4:46 am, Paul Rudin wrote: > HMS Surprise writes: > > >> Why not use grep? > > > With Windows XP? > > www.cygwin.com Using cygwin for this problem is like using a sledgehammer to crack a nut. See http://gnuwin32.sourceforge.net/summary.html *Lots* of goodies there. HTH, John From blmblm at myrealbox.com Wed Jun 27 14:59:33 2007 From: blmblm at myrealbox.com (blmblm at myrealbox.com) Date: 27 Jun 2007 18:59:33 GMT Subject: The Modernization of Emacs: terminology buffer and keybinding References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182843872.488493.153700@m36g2000hse.googlegroups.com> <87myync95b.fsf@mail.eng.it> <1182905443.074236.128290@w5g2000hsg.googlegroups.com> Message-ID: <5efqclF37fmubU1@mid.individual.net> In article <1182905443.074236.128290 at w5g2000hsg.googlegroups.com>, Twisted wrote: [ snip ] > I'm wondering if getting your head around unix arcana is also > dependent on an iffy "knack" where you "get it" and somehow know where > to look for documentation and problem fixes, despite everything having > its own idiosyncratic way, and "get" some sort of workflow trick > going, or you don't. Well .... For me I think the crucial thing was having Unix experts on tap when I was learning -- someone to answer my questions patiently, and also to show me things I might not have found on my own. Some combination of Usenet groups and books might have served the same purpose. I find Windows and its tools as frustrating as you seem to find Unix, but I strongly suspect that being shown the ropes by someone who understands and likes the system would help a lot. > Personally, the thing I always found most > irritating was the necessary frequent trips to the help. Even when the > help was easy to use (itself rare) that's a load of additional task > switching and crap. Of course, lots of the time the help was not easy > to use. Man pages and anything else viewed on a console, for example > -- generally you could not view it side by side with your work, but > instead interrupt the work, view it, try to memorize the one next > step, go back to your work, perform that next step, back to the help > to memorize another step ... that has all the workflow of a backed-up > sewer, yet until and unless the commands become second nature it's > what you're typically forced to do without a proper GUI. [ I'm trying to imagine circumstances in which I would say "proper GUI" and .... not succeeding. "Proper command line", now that I say sometimes .... :-)? ] About not being able to view help side by side with one's work, though .... You probably haven't heard the joke about how a window manager is a mechanism for having multiple xterms (terminal windows) on the screen at the same time, and a mouse is a device for selecting which one should have the focus? Well, I like it. [ snip ] > Maybe the thing I really, REALLY deplore is simply having 99% of my > attention forced to deal with the mechanics of the job and the > mechanics of the help viewer and only 1% with the actual content of > the job, instead of the other way around. Exactly my experience of trying to use MS Office tools to do quick edits under time pressure. -- B. L. Massingill ObDisclaimer: I don't speak for my employers; they return the favor. From twisted0n3 at gmail.com Mon Jun 25 18:38:29 2007 From: twisted0n3 at gmail.com (Twisted) Date: Mon, 25 Jun 2007 22:38:29 -0000 Subject: The Modernization of Emacs: terminology buffer and keybinding In-Reply-To: <5eaptcF378d21U3@mid.individual.net> References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182547318.325617.16370@o11g2000prd.googlegroups.com> <1182657564.912472.55570@g4g2000hsf.googlegroups.com> <5eaptcF378d21U3@mid.individual.net> Message-ID: <1182811109.258156.306150@k79g2000hse.googlegroups.com> On Jun 25, 5:20 pm, blm... at myrealbox.com wrote: > In article <1182657564.912472.55... at g4g2000hsf.googlegroups.com>, > > Twisted wrote: > > On Jun 23, 10:36 am, Martin Gregorie > > wrote: > > [ snip ] > > > * The operating system where you can do powerful stuff with a command > > line and a script or two, but can also get by without either. (Windows > > fails the former. Linux fails the latter.) > > About the latter -- it's hard for me to be sure, since for many > things something with a GUI is not my first choice of tool, but > my impression is that on "user-friendly" Linux distributions, > pretty much everything, including sysadmin stuff, can be done by > pointing and clicking, starting with the menus displayed on the > default desktop. With the latest stuff like Ubuntu, you're pretty much right ... until something goes wrong. Windows has safe mode and System Restore and, if push comes to shove, a recovery disk or partition. Linux has ... the command line, or worse a GRUB or fsck prompt at startup. No access to accessible, easy to browse help right when you need it most. Blow away the partition with everything on it and reinstall? y/n _ Sometimes it's not that bad. Sometimes it's just some X thing needing tweaking, or a particular thing elsewhere that's broken, but it requires at minimum hand-hacking a .rc file and running some stuff in a terminal window (aka command line, but with maybe more easily available and navigable help, since at minimum you can open two side by side and leave one open to the output of man or less). From deets at nospam.web.de Mon Jun 4 10:58:25 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 04 Jun 2007 16:58:25 +0200 Subject: python for EE CAD program References: <1180964104.685598.21330@n4g2000hsb.googlegroups.com> <5cik0mF30e4avU1@mid.uni-berlin.de> <1180967112.693545.64270@p77g2000hsh.googlegroups.com> Message-ID: <5cinkhF30nk9aU1@mid.uni-berlin.de> > Hello Diez, > > I did look at PythonCad but the distribution and install methods for > Windows is not user freindly. Since the public domain software, I > don't think they protect the source code either. The subject of code obfuscation in python has been beaten to death quite a few times on this list, do a search to find anything you want to know. In a nutshell: forget about it. it's not worth it, difficult to accomplish due to the dynamic nature of python and to be brutally honest: more or less nothing you can come up with in your own code is really worth looking at anyway. That's not saying that you can't code, just that more or less everything one programs is trivial and only of value in the actual context it was written in. So nobody is really interested in ripping stuff out. diez From __peter__ at web.de Mon Jun 4 03:44:16 2007 From: __peter__ at web.de (Peter Otten) Date: Mon, 04 Jun 2007 09:44:16 +0200 Subject: int vs long References: <1180839659.196587.194200@p77g2000hsh.googlegroups.com> <7xr6otiv4l.fsf@ruckus.brouhaha.com> <1180895701.813483.326780@k79g2000hse.googlegroups.com> <7xabvgj33p.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > Dan Bishop writes: >> If you ever do, it's trivial to write your own enumerate(): >> def enumerate(seq): >> index = 0 >> for item in seq: >> yield (index, item) >> index += 1 > > That's a heck of a lot slower than the builtin, and if you're running it > often enough for sys.maxint to be an issue, you may care about the speed. Yes, but the overall slowdown is probably still negligable when you are doing anything useful inside the for loop. Peter From deets at nospam.web.de Mon Jun 18 09:57:28 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 18 Jun 2007 15:57:28 +0200 Subject: Having lots of fun passing parameters ... help! References: <1182174634.676242.222140@n60g2000hse.googlegroups.com> Message-ID: <5dnha8F35ca42U1@mid.uni-berlin.de> DAC wrote: > I've defined a single method in Python using: > > def funcAdjacents(inputWord, outputFile): > ... > lots of boring stuff > ... > > > and then called it using: > > funcAdjacents("SampleWord","outputFile.file") > > Which works OK in Python - I get the results I want. But what I'm > trying to do is get inputWord and outputFile to be parameters are > passed on the command line, e.g. > > C:\Python\> myScript.py "SampleWord" "outputFile.file" > > And just to add to the fun, once I've reached this stage I would like > to either a) be able to execute this .py file from a HTML environment > or b) execute this file as a .exe and embed into HTML (which I can > do). You get the parameters to a script executed at the shell using import sys print sys.argv or in your case funcAdjacents(*sys.argv[1:]) Executing this from HTML requires the usage of CGI. But without further details what you really are after here and what your webenvironment is, we won't be able to help you. Diez From DustanGroups at gmail.com Sat Jun 16 16:37:01 2007 From: DustanGroups at gmail.com (Dustan) Date: Sat, 16 Jun 2007 20:37:01 -0000 Subject: a_list.count(a_callable) ? In-Reply-To: References: <1181850818.567840.251090@x35g2000prf.googlegroups.com> <1181853479.914070.217270@i13g2000prf.googlegroups.com> <1181855184.511137.100870@z28g2000prd.googlegroups.com> <1181916937.648267.163070@z28g2000prd.googlegroups.com> <1181981527.960296.135820@i13g2000prf.googlegroups.com> Message-ID: <1182026221.039617.56320@n2g2000hse.googlegroups.com> On Jun 16, 12:04 pm, Wildemar Wildenburger wrote: > class SmartCountingList(list): > def count(self, item, func=lambda x: x): > return len([item for item in self if func(item) is True]) A less bug-prone and (I would think) speedier example, although still untested: class SmartCountingList(list): def count(self, item, func=lambda x: x): return sum(1 for i in self if func(item)==item) Then, you would call it as follows: a_list.count(True, a_function) From danmcleran at yahoo.com Mon Jun 11 11:28:20 2007 From: danmcleran at yahoo.com (danmcleran at yahoo.com) Date: Mon, 11 Jun 2007 08:28:20 -0700 Subject: skip next item in list In-Reply-To: <1181573389.186279.108590@g37g2000prf.googlegroups.com> References: <1181573389.186279.108590@g37g2000prf.googlegroups.com> Message-ID: <1181575700.609801.259670@w5g2000hsg.googlegroups.com> On Jun 11, 8:49 am, ahlongxp wrote: > list=('a','d','c','d') > for a in list: > if a=='a' : > #skip the letter affer 'a' > > what am I supposed to do? You could do this with itertools.ifilter and an predicate (pred) for a more OO solution. I've created 2 lists, the source list (l) and the expected answer (ans). Make sure this is what you meant in your problem statement: import itertools l = ['a', 'b', 'c', 'a', 'd', 'e', 'f', 'a', 'g', 'h'] ans = ['a', 'c', 'a', 'e', 'f', 'a', 'h'] class pred(object): def __init__(self): self.last = None def __call__(self, arg): result = None if self.last == 'a': result = False else: result = True self.last = arg return result i = itertools.ifilter(pred(), l) result = list(i) print result print ans assert result == ans print 'done' From mitko at qlogic.com Tue Jun 5 12:56:57 2007 From: mitko at qlogic.com (Mitko Haralanov) Date: Tue, 5 Jun 2007 09:56:57 -0700 Subject: Getting mount stats for filesystems In-Reply-To: <46650e6c$0$25817$9b622d9e@news.freenet.de> References: <46650e6c$0$25817$9b622d9e@news.freenet.de> Message-ID: <20070605095657.60e23831@opal.pathscale.com> On Tue, 05 Jun 2007 09:19:08 +0200 "Martin v. L?wis" wrote: > I'm not quite sure what you want to achieve. You are on machine B, > and you want to find out whether a remote file system (on machine A) > is mounted remotely (say, from machine C)? Ok, let me try to explain: I am on machine A, which has a NFS mounted filesystem hosted on machine B. All I need to find out is whether the NFS filesystem is mounted using tcp or udp. -- Mitko Haralanov mitko at qlogic.com Senior Software Engineer 650.934.8064 System Interconnect Group http://www.qlogic.com ========================================== Paul: If rubbin' frozen dirt in your crotch is wrong, hey, I don't wanna be right. From jeffrey.rollin at gmail.com Tue Jun 12 06:04:52 2007 From: jeffrey.rollin at gmail.com (Jeff Rollin) Date: Tue, 12 Jun 2007 11:04:52 +0100 Subject: Accessing attributes? Message-ID: Hi there. I'm working with the Python Tutorial "Byte of Python" at swaroopch.info. I have created the following file: ------------------------------------------------------------------------ #!/usr/bin/env python # Filename: objvar.py class Person: """Represents a person.""" population = 0 # class variable def __init__(self,name): """Initializes the person's data.""" self.name = name # object variable print '(Initializing %s)' % self.name # When this person is created, he/she adds to the population Person.population += 1 def __del__(self): """I am dying.""" print '%s says bye.' % self.name Person.population -= 1 if Person.population == 0: print 'I am the last one.' else: print 'There are still %d people left.' % Person.population def say_hi(self): """Greeting by the person. Really, that's all it does.""" print 'Hi, my name is %s.' % self.name def how_many(cls): """Prints the current population.""" if Person.population == 0: print 'Nobody is alive as of now.' elif Person.population == 1: print 'There is just one person here.' else: print 'We have %d persons here.' % Person.population how_many = classmethod(how_many) #jeff = Person('Jeff') #jeff.say_hi() cj = Person('Calamity Jane') #cj.say_hi() Person.how_many() #jeff.say_hi() Person.how_many() --------------------------------------------------------------------------------- but when I execute: % objvar.py I get the error message: (Initializing Calamity Jane) Traceback (most recent call last): ? File "/home/jef/bin/objvar.py", line 49, in ? ? Person.how_many() AttributeError: class Person has no attribute 'how_many' Where am I going wrong? Many TIA for any help. From smitty1e at gmail.com Sun Jun 10 17:17:40 2007 From: smitty1e at gmail.com (smitty1e) Date: Sun, 10 Jun 2007 21:17:40 -0000 Subject: codecs / subprocess interaction: utf help requested Message-ID: <1181510260.821468.151320@h2g2000hsg.googlegroups.com> The first print statement does what you'd expect. The second print statement has rather a lot of rat in it. The goal here is to write a function that will return the man page for some command (mktemp used as a short example here) as text to client code, where the groff markup will be chopped to extract all of the command options. Those options will eventually be used within an emacs mode, all things going swimmingly. I don't know what's going on with the piping in the second version. It looks like the output of p0 gets converted to unicode at some point, but I might be misunderstanding what's going on. The 4.8 codecs module documentation doesn't really offer much enlightment, nor google. About the only other place I can think to look would be the unit test cases shipped with python. Sort of hoping one of the guru-level pythonistas can point to illumination, or write something to help out the next chap. This might be one of those catalytic questions, the answer to which tackles five other questions you didn't really know you had. Thanks, Chris --------------------------- #!/usr/bin/python import subprocess p = subprocess.Popen(["bzip2", "-c", "-d", "/usr/share/man/man1/mktemp. 1.bz2"] , stdout=subprocess.PIPE) stdout, stderr = p.communicate() print stdout p0 = subprocess.Popen(["cat","/usr/share/man/man1/mktemp.1.bz2"], stdout=subprocess.PIPE) p1 = subprocess.Popen(["bzip2"], stdin=p0.stdout , stdout=subprocess.PIPE) stdout, stderr = p1.communicate() print stdout --------------------------- From bj_666 at gmx.net Tue Jun 5 04:03:13 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Tue, 05 Jun 2007 10:03:13 +0200 Subject: magic names in python References: <1180939436.862957.127810@p77g2000hsh.googlegroups.com> <1180943167.241208.37080@q75g2000hsh.googlegroups.com> <1181027654.070887.10910@q66g2000hsg.googlegroups.com> Message-ID: In <1181027654.070887.10910 at q66g2000hsg.googlegroups.com>, per9000 wrote: > Still, I have problems with "magic" functions, similar to magic > numbers: http://en.wikipedia.org/wiki/Magic_number_%28programming%29 > f.x. calling all member-functions of a class to close files as > illustrated in a previous post, or PyUnits magic "test*"-names: > http://pyunit.sourceforge.net/pyunit.html#RUNNING_CMD (there are > options here but I fell into the bear-trap of course) I don't see much similarity here. While magic numbers are quite meaningless on their own, the name prefix carries at least *some* explanation and therefore is much less magic. Maybe not even magic at all in the sense of the Wikipedia article. > Guessing from your replies this is a general problem/issue/feature and > as I understand it there is no special pythonic recommendations in > this area, right? Except documenting what's going on and not over(ab)using the reflective and dynamic nature of Python to the point where the source starts to get unreadable and too magic, AFAIK there's no special "pythonic" recommendation. :-) Ciao, Marc 'BlackJack' Rintsch From mirko-usenet-200706 at dziadzka.de Tue Jun 19 13:07:16 2007 From: mirko-usenet-200706 at dziadzka.de (Mirko Dziadzka) Date: Tue, 19 Jun 2007 19:07:16 +0200 Subject: metaclasses and performance Message-ID: Hi all I'm playing around with metaclasses and noticed, that there is small but mesurable a performance difference in the code shown below. With a more complex example I get a 5 percent performance penalty for using a metaclass. Until today I assumed, that a metaclass has no performance impact at all after class creation. Can someone explain me the performance difference between the two classes test1 and test2 Thank's in advance Mirko ---- cut here ----- class meta(type): pass class test1(object): __metaclass__ = meta # using type via meta here def __init__(self): self.foo = 42 def get_foo(self): return self.foo class test2(object): __metaclass__ = type # using type directly def __init__(self): self.foo = 42 def get_foo(self): return self.foo # and here the performance test code ... it's only 2% on my machine import time for c in [test1, test2] * 10: t = c() start = time.time() for i in xrange(10 * 1000 * 1000): t.get_foo() print c.__name__, time.time() - start ---- cut here ----- From senwin30 at gmail.com Thu Jun 28 12:28:56 2007 From: senwin30 at gmail.com (senthil arasu) Date: Thu, 28 Jun 2007 11:28:56 -0500 Subject: Help needed for Pmw and WxPython Interface Message-ID: <1ef9860e0706280928l2d000ba8g555d568228ee1b7b@mail.gmail.com> Hi, Iam creating tab pages using pmw nb = Pmw.NoteBook(master) p1 = nb.add('Page 1') p2 = nb.add('Page 2') p3 = nb.add('Page 3') created button control for every tabe page to open HTML Button(p1, fg='blue',command=f.call,command=call1).pack(pady=40) Button(p2, fg='blue',command=f.call,command=call2).pack(pady=40) Button(p3, fg='blue',command=f.call,command=call2).pack since HTML rendering supported in WxPython library .I have defined call backs with WxPython HTML routines eg. def call1:() { html.LoadPage("http://wxwidgets.org/manuals/2.5.4/wx_wxbutton.html") } Iam facing problem in integration of both the libraries. Is it possible to integrate the functionalities of libraries WxPython and pmw.? please help me. thanks iS IT -------------- next part -------------- An HTML attachment was scrubbed... URL: From adecchi at gmail.com Sat Jun 30 20:30:46 2007 From: adecchi at gmail.com (Alejandro Decchi) Date: Sat, 30 Jun 2007 21:30:46 -0300 Subject: help search file Message-ID: Hello Python user. I am a newbie with python and i am interesting to do a web apliation to search file on the hard disk and give a link to download the file found. Someone can give a help ??? Thz Ale -------------- next part -------------- An HTML attachment was scrubbed... URL: From shao.tu at gmail.com Sat Jun 23 04:57:56 2007 From: shao.tu at gmail.com (stalex) Date: Sat, 23 Jun 2007 01:57:56 -0700 Subject: ctypes help for "array of character pointers" as an output parameter Message-ID: <1182589076.262791.49960@e9g2000prf.googlegroups.com> I'm wrapping a C function exists in a shared library. Its prototype looks like as follows int getFileNames(int aSize, char **names); The documentation says that the asSize is the number of entries to be returned and names is output array of character pointers of at least aSize elements. So, I defined a function prototype in python, follow ctypes tutorial, and try to run it. The following code section shows what I did. _getNames = TheLib.getNames _getNames.restype = c_int _getNames.argtypes = [ c_int, POINTER(c_char_p) ] def getNames(): aSize = 1024 names = (c_char_p * arraySize)() rc = _getNames(aSize, names) After that, I make a call to getNames() in my python program and, unfortunately, either TypeError or Segmentation fault. Sigh... I wonder that whether the _getNames prototype definition in my code section is correct?? If it isn't, I guess so, how do I do a right one? Another, whether the usage in getNames() is correct?? Appreciate for any reply or recommendation. From wolf_tracks at invalid.com Wed Jun 6 10:29:17 2007 From: wolf_tracks at invalid.com (W. Watson) Date: Wed, 06 Jun 2007 07:29:17 -0700 Subject: Need a Little Help on Tkinter and Python In-Reply-To: <4666b2f8$0$23408$5402220f@news.sunrise.ch> References: <4666b2f8$0$23408$5402220f@news.sunrise.ch> Message-ID: Thanks for your responses. I've located the URL from the post above and will check out the two books mentioned here. I used to do a lot of scientific programming, but now just concentrate on science. Martin Blume wrote: > "W. Watson" schrieb >> I have about a 1600 line Pythron program I'd like to >> make some simple mods to, but have really just a nodding >> acquaintance with Python and Tkinter. >> [...] >> Let's change that. >> > > The book "Learning Python" from O'Reilly is excellent. > > If you are into scientific programming, the book > "Python Scripting for Computational Science" > by Hans Petter Langtangen from Springer is useful. > > HTH > Martin > > > -- Wayne Watson (Nevada City, CA) Web Page: From dak at gnu.org Tue Jun 19 09:53:21 2007 From: dak at gnu.org (David Kastrup) Date: Tue, 19 Jun 2007 15:53:21 +0200 Subject: The Modernization of Emacs References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <873b0p9vpm.fsf@W0053328.mgh.harvard.edu> Message-ID: <861wg8rqy6.fsf@lola.quinscape.zz> Harry George writes: > I don't mind folks using any editor they want, as long as they are > proficient. In those cases, I have no problem doing Extreme > Programming with them -- code a bit, save, the other guy codes a > bit. But when someone uses vi and then forgets how to do block > moves, or uses eclipse and bogs down the session, or uses MS Notepad > and can't enforce language-specific indents, I get frustrated. My favorite killing offence is /* vi:set ts=4: */. -- David Kastrup From http Fri Jun 15 12:02:34 2007 From: http (Paul Rubin) Date: 15 Jun 2007 09:02:34 -0700 Subject: Serialization across languages? References: <46719c90$0$10851$88260bb3@free.teranews.com> <46727407$0$20038$426a74cc@news.free.fr> Message-ID: <7xir9pjjdx.fsf@ruckus.brouhaha.com> Bruno Desthuilliers writes: > Then I'd second Simon's suggestion to use JSON. Any idea if a C implementation is available? I mean Python-callable. From showell30 at yahoo.com Fri Jun 1 07:15:55 2007 From: showell30 at yahoo.com (Steve Howell) Date: Fri, 1 Jun 2007 04:15:55 -0700 (PDT) Subject: execute a function after each source code line ? In-Reply-To: <41c66$465ffa9d$83aef404$5115@news1.tudelft.nl> Message-ID: <245671.61267.qm@web33504.mail.mud.yahoo.com> --- stef wrote: > Steve, > that's exactly what I've in mind. > The screen shots, looks really good, > and I'll definitely will take a deeper look into > your code. Cool, good luck. Feel free to contact me privately if you have questions about the implementation. There's also a mailing list for GvR, although it's not that active at the moment. It's not that the project is dead, we just don't have much to add to it at this point. :) > I've one advantage over you, > the language I want to simulate (JAL), > is very Pascal like, > and therefor can be easily converted into equivalent > Python code. > FWIW the language I was interpeting is also Pascal-like, and as I mentioned, we initially translated it into Python code as well. Even when we abandoned the idea of using Python to run the program (er, this is like describing PyPy, we were still using Python at the outer level, just not the inner level), we still kept the code around to translate from GvR to Python. The translations from GvR to Python made it easy for us to write unit tests like this: ''' if front_is_blocked: turnleft if front_is_blocked: turnleft if front_is_blocked: turnleft move ''', ''' if self.FRONT_IS_BLOCKED(0): self.TURNLEFT(1) if self.FRONT_IS_BLOCKED(2): self.TURNLEFT(3) if self.FRONT_IS_BLOCKED(4): self.TURNLEFT(5) self.MOVE(6) ''' More here: http://gvr.cvs.sourceforge.net/*checkout*/gvr/GvR/TESTgvrparser.py?revision=1.23&content-type=text%2Fplain ____________________________________________________________________________________ Luggage? GPS? Comic books? Check out fitting gifts for grads at Yahoo! Search http://search.yahoo.com/search?fr=oni_on_mail&p=graduation+gifts&cs=bz From flyzone at technologist.com Wed Jun 13 11:48:51 2007 From: flyzone at technologist.com (Flyzone) Date: Wed, 13 Jun 2007 08:48:51 -0700 Subject: problem on waiting exit thread and write on file Message-ID: <1181749731.260357.192390@q19g2000prn.googlegroups.com> I have a list of parameters. I need to run in thread a command, one thread for one parameter. So i made a for loop, creating 5 threads and waiting their stop with: for parameter in parameters Thread{ .... write on BW2 .... } Main { open file BW2 for write ..... (creating list of thread with a counter).... Stopped=False while (Stopped == False): if not thread5.isAlive(): if not thread4.isAlive(): if not thread3.isAlive(): if not thread2.isAlive(): if not thread1.isAlive(): Stopped=True if (Stopped == False): time.sleep(0.3) ...... close file BW2 } Somethimes i get however the error that i can't write on a file already closed There is a way more easy to wait that all children exit and to run a queue of threads? I tried also this: a=0 while (a == 0): try: os.waitpid(-2, 0) except OSError, exc: # all CHILD finished a=1 but the same problem persist. The only way to don't have error is to had a time.sleep(4) before closing the file from the main program. From doug at alum.mit.edu Thu Jun 28 23:36:56 2007 From: doug at alum.mit.edu (Douglas Alan) Date: Thu, 28 Jun 2007 23:36:56 -0400 Subject: Python's "only one way to do it" philosophy isn't good? References: <1182750077.570603.160240@q69g2000hsb.googlegroups.com> <7xir9cbm0g.fsf@ruckus.brouhaha.com> <7xejjzmk7u.fsf@ruckus.brouhaha.com> <7xy7i7xjl5.fsf@ruckus.brouhaha.com> <5N0C7KBirhgGFwUp@woodrowhorsfall.plus.com> Message-ID: Steve Holden writes: >> Actually, it's "chacun". And the "?" may precede the "chacun". >> |>oug > "chacun" is an elision of the two words "Chaque" (each) and "un" > (one), and use of those two words is at least equally correct, though > where it stands in modern usage I must confess I have no idea. Google can answer that: 158,000 hits for "chaqu'un", 57 million for "chacun". |>oug From tcrane at REMOVETHISuiuc.edu Fri Jun 8 11:29:04 2007 From: tcrane at REMOVETHISuiuc.edu (T. Crane) Date: Fri, 08 Jun 2007 15:29:04 GMT Subject: interating over single element array Message-ID: <4Beai.13210$5j1.6184@newssvr21.news.prodigy.net> Hi all, Can someone please explain to me why I can't do something like this: a = 1 for value in a: print str(value) If I run this I get the error: 'int' object is not iterable Obivously this is an absurd example that I would never do, but in my application the length of 'a' can be anything greater than 0, and I want to be able to handle cases when 'a' has only one element without coding a special case just in the event that len(a) = 1. any suggestions are appreciated, trevis From reedobrien at gmail.com Sat Jun 2 18:30:45 2007 From: reedobrien at gmail.com (reed) Date: Sat, 02 Jun 2007 22:30:45 -0000 Subject: Trouble killing a process on windows In-Reply-To: <1180801625.231797.158370@p77g2000hsh.googlegroups.com> References: <1180801625.231797.158370@p77g2000hsh.googlegroups.com> Message-ID: <1180823445.551017.45700@h2g2000hsg.googlegroups.com> On Jun 2, 12:27 pm, Thomas Nelson wrote: > Hi, I'd like to start a program, run it for a while, then terminate > it. I can do this on linux, but I'm new to working with windows. > Here's my script: > > from subprocess import Popen > from time import sleep > import win32api > war3game = Popen(["C:\Program Files\Warcraft III\Frozen Throne.exe"]) > sleep(30) > print "slept for 30" > print win32api.TerminateProcess(int(war3game._handle),-1) > #print > ctypes.windll.kernel32.TerminateProcess(int(war3game._handle),-1) > print "terminated process" > > Here's the output: > slept for 30 > Traceback (most recent call last): > File "C:\Python24\warcraft\runwar3.py", line 7, in ? > print win32api.TerminateProcess(int(war3game._handle),-1) > error: (5, 'TerminateProcess', 'Access is denied.') > > I'm logged in as adminstrator. Does anyone know how to fix this > problem? > Thanks for your time, > Tom kill = Popen(['taskkill', war3game.pid]) *shrugs* maybe it is just taskill, or maybe you need the full path. don't recall as I quit using windows. Takskill on XP and newer maybe From toby at tobiah.org Tue Jun 19 15:22:05 2007 From: toby at tobiah.org (Tobiah) Date: Tue, 19 Jun 2007 12:22:05 -0700 Subject: Reference current module? Message-ID: <4678201b$0$16340$88260bb3@free.teranews.com> Can I do: getattr(current_module, 'foo') where 'current_module' is a handle the the one that the code is in? Just like getattr(self, 'foo') in a class, but for the current module instead? Thanks, Toby -- Posted via a free Usenet account from http://www.teranews.com From thomas at jollans.com Thu Jun 28 08:53:13 2007 From: thomas at jollans.com (Thomas Jollans) Date: Thu, 28 Jun 2007 14:53:13 +0200 Subject: 16bit hash In-Reply-To: References: <46833DC0.3050503@v.loewis.de> Message-ID: Robin Becker wrote: > Martin v. L?wis wrote: > > 0 the ideal hash > > :) > > can't be argued with > >> ....... >> So: what are your input data, and what is the >> distribution among them? >> >> Regards, >> Martin >> > I'm trying to create UniqueID's for dynamic postscript fonts. According > to my resources we don't actually need to use these, but if they are > required by a particular postscript program (perhaps to make a print run > efficient) then the private range of these ID's is 4000000<=UID<=4999999 > ie a range of one million. > > So I probably really need an 18 bit hash > > The data going into the font consists of > > fontBBox '[-415 -431 2014 2033]' > charmaps ['dup (\000) 0 get /C0 put',......] > metrics ['/C0 1251 def',.....] > bboxes ['/C29 [0 0 512 0] def',.......] > chardefs ['/C0 {newpath 224 418 m 234 336 ......def}',......] > > ie a bunch of lists of strings which are eventually joined together and > written out with a template to make the postscript definition. > > The UniqueID is used by PS interpreters to avoid recreating particular > glyphs so ideally I would number these fonts sequentially using a global > count, but in practice several processes separated by application and > time can produce postscript which eventually gets merged back together. > > If the UID's clash then the printer produces very strange output. > > I'm fairly sure there's no obvious python way to ensure the separated > processes can communicate except via the printer. So either I use a > python based scheme which reduces the risk of clashes ie random or some > data based hash scheme or I attempt to produce a postscript solution > like looking for a private global sequence number. > > I'm not sure my postscript is really good enough to do the latter so I > hoped to pursue a python based approach which has a low probability of > busting. Originally I thought the range was a 16bit number which is why > I started with 16bit hashes. For identifying something, I suggest you use a hash function like sha1 truncating it to as much as you can use, similarly to what Jon Ribbens suggested. From C.delete_this.Sanders at BoM.GOv.AU Tue Jun 5 00:15:59 2007 From: C.delete_this.Sanders at BoM.GOv.AU (Charles Sanders) Date: Tue, 05 Jun 2007 14:15:59 +1000 Subject: ctypes: error passing a list of str to a fortran dll In-Reply-To: <1180952246.415068.237400@h2g2000hsg.googlegroups.com> References: <1180952246.415068.237400@h2g2000hsg.googlegroups.com> Message-ID: <4664e37f$0$59818$c30e37c6@lon-reader.news.telstra.net> luis wrote: > I'm using ctypes to call a fortran dll from python. I have no problems > passing integer and double arryas, but I have an error with str arrys. > For example: [snip] I do not know about Microsoft Fortran compilers (your mention of dll indicates you are probably using MS), nor much about Python, but the C equivalent of a given Fortran call is operating system and compiler dependent. You should consult the Fortran compiler manual for the compiler used to create the DLL. Despite this, many (but not all) C to Fortran interfaces have the following characteristics + C name is Fortran name in lower case + Fortran REAL, DOUBLE PRECISION, INTEGER etc parameters are pointers to the parameter in C, ie float*, etc + Fortran REAL etc arrays are pointers in C (same as C arrays decay to pointers). + Fortran CHARACTER and CHARACTER arrays are passed as TWO parameters, one a pointer to the start of the variable or array, and the other the length as an integer, not a pointer. The length parameters follow all other parameters, in order of the character variables/arrays. Variations I have seen (all on Unix) include using upper case instead of lower, prepending (or postpending) an underscore (or other character(s)) to the subroutine or function name, and using special "character descriptors" (packing address and length into one "word") for character variables. There are almost certainly more variations that I have not seen. For example, given a FORTRAN declaration SUBROUTINE X( CV, RV, CA, N ) CHARACTER*(*) CV REAL RV CHARACTER*(*) CA(*) INTEGER N The C equivalent is likely to be void x( char *pcv, float *prv, char *pca, int *pn, int lv, int la) Where lv will hold the length of cv and la the length of each element of ca (required to be the same for all elements of the array). Fortran uses fixed length character strings, padded with blanks. Given the error message > ValueError: Procedure probably called with not enough > arguments (4 bytes missing) I suspect that your Fortran compiler is one of the many which do this, and the missing 4 bytes are the integer length of each element of the character array. Also, I noticed you seem to be passing an array of character pointers rather than an array of characters. It is doubtful that Fortran can handle this. You will probably have to pad the strings to a maximal length with spaces, concatanate then into one big string, and pass this by reference together with their padded length. Your Fortran may (but probably won't) have extensions that allow you to pass an array of character pointers. Charles From mcl.office at googlemail.com Fri Jun 8 11:29:35 2007 From: mcl.office at googlemail.com (mosscliffe) Date: Fri, 08 Jun 2007 08:29:35 -0700 Subject: Case-Insensitive Sorting of Multi-Dimensional Lists In-Reply-To: References: <020e01c7a94c$a7970750$0f01a8c0@desktop9> Message-ID: <1181316575.800182.167640@m36g2000hse.googlegroups.com> On 8 Jun, 14:18, "Simon Brunning" wrote: > On 6/7/07, Joe wrote: > > > > > I have a list of lists that I would like to sort utilizing a certain index > > of the nested list. I am able to successfully use: > > > Import operator > > list = [["Apple", 1], ["airplane", 2]] > > list.sort(key=operator.itemgetter(0)) > > > But, unfortunately, this will be case sensitive (Apple will come before > > airplane because the A is capital) and I need it to be insensitive. > > Try: > > list.sort(key=lambda el: el[0].lower()) > > BUT - it's not a good idea to use list as a name, 'cos list is a > built-in, and you're obscuring it. > > -- > Cheers, > Simon B. > s... at brunningonline.nethttp://www.brunningonline.net/simon/blog/ > GTalk: simon.brunning | MSN: small_values | Yahoo: smallvalues I have tried the following, for a one dimensional list and it works, but I can not get my head around this lambda. How would this be written, without the lamda ? mylist = ['Fred','bill','PAUL','albert'] mylist.sort(key=lambda el: el.lower()) Any pointer to an idiot's guide appreciated. Richard From rjagodic at gmail.com Tue Jun 26 15:58:01 2007 From: rjagodic at gmail.com (Ratko) Date: Tue, 26 Jun 2007 12:58:01 -0700 Subject: popen and a long running process in a wx.python application In-Reply-To: <1182870983.001851.156960@q75g2000hsh.googlegroups.com> References: <1182870983.001851.156960@q75g2000hsh.googlegroups.com> Message-ID: <1182887881.632751.127470@p77g2000hsh.googlegroups.com> On Jun 26, 10:16 am, Doru Moisa wrote: > Hello, > > How can I capture the output of a long runnning process which I open > with popen() ? > I tried reading line by line, char by char, but the result always > comes when the process finishes. > (I am trying to make a wx.python program that opens some "make ..." > with popen). How can I receive the output of the program immediatly, > so that I can show a progressbar in my application ? > I always get the program's output after it finished executing. > Is this the right place, or should I post this to wx.python ? > > Thank you in advance. I think this is the right list to post this in since it's independent of wxPython. I just recently went through this and got it working properly. Your problem is that the output is buffered and is only flushed upon exit (and that's when you read() it) Here's a piece of code: doRead = True p = subprocess.Popen(["ls"], stdout=sp.PIPE, stderr=sp.STDOUT, bufsize=1) while doRead: txt = os.read(p.stdout.fileno(), 2048) time.sleep(0.5) # read at most x times / sec A few things to note: (1) you must use os.read and not the builtin read() for unbuffered read. (2) you probably want to run this while loop in a thread because read will block until there's some text available (3) this is a polling method where I read at most 2 a second in the above example (4) this works on Mac, Windows and Linux the same (besides the "ls" command of course) (5) after you read this text you can send it to a TextCtrl or something Hope that helps. Ratko From borud-news at borud.no Sat Jun 23 11:08:19 2007 From: borud-news at borud.no (Bjorn Borud) Date: 23 Jun 2007 17:08:19 +0200 Subject: The Modernization of Emacs: terminology buffer and keybinding References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182272495.990807.99110@a26g2000pre.googlegroups.com> <87tzt3ihev.fsf@kobe.laptop> <1182370216.961241.6960@n60g2000hse.googlegroups.com> <85zm2ufjpb.fsf@lola.goethe.zz> <1182372592.803332.288260@u2g2000hsc.googlegroups.com> <1182373919.262388.100740@c77g2000hse.googlegroups.com> <85r6o6fhkb.fsf@lola.goethe.zz> <1182375045.626510.188170@m36g2000hse.googlegroups.com> <1182546050.465987.115740@q19g2000prn.googlegroups.com> <871wg3k8c8.fsf@thalassa.lan.informatimago.com> <1182546979.295368.146110@q19g2000prn.googlegroups.com> <87wsxviqol.fsf@thalassa.lan.informatimago.com> <1182552172.406571.116390@i38g2000prf.googlegroups.com> Message-ID: [Falcolas ] | | I guess ultimately I'm trying to argue the point that just because a | tool was written with a GUI or on Windows does not automatically make | it any less a productive tool than a text based terminal tool. Even in | windows, you can use the keyboard to do all of your work, if you learn | how (thanks to the magic of the alt key). as I see it, the debate isn't whether GUI tools are inferior per se, but whether Emacs is inferior since it has its own interaction concepts that do not map 1:1 to GUI conventions of Windows and OSX. the point I am trying to get across is that Emacs (and vi) is its own niche, and that if you want to improve them, there are more important things than fiddling around with superficial details (like keybindings -- which you can customize to your own liking anyway). for Emacs it would be far more helpful if the Lisp-implementation was replaced with one that is more efficient and Common Lisp-like. (indeed several friends of mine would like to see Emacs done in Common Lisp, and I seem to have some memory of such a project existing somewhere). -Bj?rn From steve at REMOVE.THIS.cybersource.com.au Tue Jun 5 19:20:40 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Wed, 06 Jun 2007 09:20:40 +1000 Subject: magic names in python References: <1180939436.862957.127810@p77g2000hsh.googlegroups.com> Message-ID: On Tue, 05 Jun 2007 18:08:31 +0000, Lenard Lindstrom wrote: > Steven D'Aprano wrote: >> On Mon, 04 Jun 2007 22:19:35 +0000, Lenard Lindstrom wrote: >> >>> What is "magic" about __init__ and __repr__? They are identifiers just >>> like "foo" or "JustAnotherClass". They have no special meaning to the >>> Python compiler. The leading and trailing double underscores represent >>> no special incantation. It is just a naming convention. >> >> That's not quite true, as you point out: > > Disassemble the code object of a class statement. "__init__" is just an > identifier, a Python name. So there is no "magic" here. It is not JUST an identifier, it is an identifier with a special, dare I say *magic*, meaning. I suspect we have different ideas of what a "magic name" is. You seem to be under the impression that magic names are a bad thing, and that therefore one has to minimize their number. Hence you are glossing over the differences and emphasizing the similarities between methods (say) foo and __init__. I don't consider "magic name" in this content to be anything to be ashamed of, so I'm not concerned about downplaying the differences. Yes, there are significant similarities between __init__ and random methods you write yourself, but the differences are equally, if not more, significant. >>> So a number of method names like __init__ and __repr__ have a >>> pre-defined usage. >> >> That makes them magic, in the best possible way. > > I was careful to use the word "usage". Maybe I should have used > "protocol" or "specification" here. A method named "write" is understood > to have a particular definition and purpose. Is it "magic"? It could be, depending on the context. If we're discussing file objects compared to str objects, then file objects have a method "write" and str objects don't, and the method is just another method. But in the context of some third function, which takes a file-like object with a "write" method, then yes it is magic, because any type of object will work so long as it has a method "write" with the right semantics. Not very much magic, but a little. > These > methods are simply callbacks. And yes, these callbacks make Python flexible. > >> >> >>> In every other respect they are just normal methods. >> >> That is *almost* true. Or, to put it another way, that is wrong. Some of >> the double-underscore magic methods are automatically called on the class >> instead of the instance, bypassing normal inheritance. >> > > They exist as Python functions in the class dictionary. They have no > hidden flags that distinguish them from other class level function > attributes. They don't need special flags, because the Python compiler itself already knows about the existence of them and takes special actions with them. [snip] > I do admit that the special methods are given special treatment by the > type and ClassType types to ensure they are called by their > corresponding operations. But this special treatment is restricted to > the types themselves. In CPython an extension type can be written from > scratch that treats special methods exactly as a new-style class does. > Or an extension type can implement a completely novel approach. The > point is, at some level, the machinery which defines special method > "magic" is accessible to the programmer. So is it really "magic" or > advanced technology? Does it matter? As Clarke said, any sufficiently advanced technology is indistinguishable from magic... or to put it another way, as Larry Niven did, any sufficiently advanced magic is indistinguishable from technology. Since I don't actually believe in magic, as in "wishing makes it so", of course it is technology. But most Python programmers aren't capable of, or have any interest in, writing extension types in C or hacking the compiler. > This comes down to the original posting not defining a "magic name". It > does not mention what is so objectionable about __init__ and __repr__. I > am claiming they are not as "magical" as they may first appear. I don't believe the Original Poster considers there is anything objectionable about magic names like __init__ and __repr__, and even if he does, I certainly don't. Magic names in this context are those methods which have pre-defined meanings to the compiler. That is mostly double-underscore methods like __init__, but also methods like iterator.next(). If you ask yourself "What methods do I have to over-ride to make a customized sub-class of a built-in type?", the answer will include mostly magic names. If you ask "What methods do I have to write for my class to work with Python operators?", the answer will also include magic names like __add__, __mul__, and __xor__. -- Steven. From bignose+hates-spam at benfinney.id.au Fri Jun 1 08:05:42 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 01 Jun 2007 22:05:42 +1000 Subject: Is PEP-8 a Code or More of a Guideline? References: <1180236987.850208.271410@u30g2000hsc.googlegroups.com> <5c1jpkF2tl0ilU1@mid.individual.net> <1180539790.654176.26900@q75g2000hsh.googlegroups.com> Message-ID: <87fy5bzxpl.fsf@benfinney.id.au> "Joe Riopel" writes: > Using camel case instead of the under_score means less typing. I am lazy. Using camelCase instead of lower_case means harder reading. I am lazy. Remember: a program is read by humans much more often than it is written. -- \ "If you saw two guys named Hambone and Flippy, which one would | `\ you think liked dolphins the most? I'd say Flippy, wouldn't | _o__) you? You'd be wrong, though. It's Hambone." -- Jack Handey | Ben Finney From ibm at svpal.org Sat Jun 2 02:13:36 2007 From: ibm at svpal.org (Ian MacLure) Date: Sat, 02 Jun 2007 01:13:36 -0500 Subject: Ancient projectiles (was: Muzzle Velocity (was: High resolution sleep (Linux)) References: <1178274122.142071.91740@y5g2000hsa.googlegroups.com> <3f0mi4-mj8.ln1@lairds.us> Message-ID: Roy Smith wrote in news:roy-2F6BE5.16193326052007 at 032-325- 625.area1.spcsdns.net: > In article <3f0mi4-mj8.ln1 at lairds.us>, claird at lairds.us (Cameron Laird) > wrote: > >> Hmmm; now you've got me curious. What *were* the first >> composite projectiles? > > Fetchez la Vache! Non, non, non, non, NON! La vache, she is the COMPOSTING projectile. Zere is a difference you ignorant Rosbif! IBM From uymqlp502 at sneakemail.com Fri Jun 8 00:19:08 2007 From: uymqlp502 at sneakemail.com (Russ) Date: Thu, 07 Jun 2007 21:19:08 -0700 Subject: compiling python and calling it from C/C++ Message-ID: <1181276348.740945.312970@x35g2000prf.googlegroups.com> Is it possible to compile python code into a library (on unix), then link to it and call it from C/C++? If so, where can I learn how. Thanks. From andreas_eder at gmx.net Thu Jun 28 05:26:42 2007 From: andreas_eder at gmx.net (Andreas Eder) Date: Thu, 28 Jun 2007 11:26:42 +0200 Subject: The Modernization of Emacs: terminology buffer and keybinding References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182272495.990807.99110@a26g2000pre.googlegroups.com> <87tzt3ihev.fsf@kobe.laptop> <1182370216.961241.6960@n60g2000hse.googlegroups.com> <85zm2ufjpb.fsf@lola.goethe.zz> <1182372592.803332.288260@u2g2000hsc.googlegroups.com> <1182549094.366282.286740@m37g2000prh.googlegroups.com> <87bqf7fwmg.fsf@telesippa.clsnet.nl> <1182553682.197778.138500@g37g2000prf.googlegroups.com> <87r6nzc9nu.fsf@mail.eng.it> <1182904631.083783.170640@o61g2000hsh.googlegroups.com> Message-ID: <86zm2ka0q5.fsf@eder.homelinux.net> Hi Twisted, >>>>> "Twisted" == Twisted writes: Twisted> Let me get this straight. Twisted> In this corner, we have just about every Windows application ever Twisted> developed. When a user needs help, a click on the "help" menu or tap Twisted> of the F1 key is all it takes to obtain some. Sometimes the help is Twisted> not of the greatest quality, but that is another issue we won't Twisted> concern ourselves with here. Almost always when I really needed help in Windows, all it said was: go ask your system administrator. Really helpful :-( Twisted> In the other corner, we have just about every Unix application ever Twisted> developed. When a user needs help, they may do such things as manually Twisted> explore the directories where the application was installed Twisted> (equivalent to rooting around in C:\Program Files\Appname for .hlp Twisted> files, because F1 didn't work and there was no "help" menu, if such a Twisted> thing ever happened on Windoze). Ever heard of man pages? and info? 'Andreas -- Wherever I lay my .emacs, there's my $HOME. From frederic.pica at gmail.com Mon Jun 4 03:55:19 2007 From: frederic.pica at gmail.com (=?iso-8859-1?B?RnLpZOlyaWMgUElDQQ==?=) Date: Mon, 04 Jun 2007 07:55:19 -0000 Subject: Python memory handling In-Reply-To: References: <1180611604.247696.149060@h2g2000hsg.googlegroups.com> <1180627331.756615.132650@k79g2000hse.googlegroups.com> Message-ID: <1180943719.212184.242450@o5g2000hsb.googlegroups.com> Greets, Sorry for my late answer, google groups lost my post... First, thanks you for your explanations about memory handling in the os and python. I've tried with python 2.5 under linux : For the parsing of a 66 Mb xml file with cElementTree : When starting python : 2.1 Mb private memory used import xml.etree.cElementTree as ElementTree #3.4 Mb used et=ElementTree.parse('otherdata.xml') #218.6 Mb used del et #43.3 Mb used et=ElementTree.parse('otherdata.xml') #218.6 Mb used del et #60.6 Mb used et=ElementTree.parse('otherdata.xml') #218.6 Mb used del et #54.1 Mb used et=ElementTree.parse('otherdata.xml') #218.6 Mb used del et #54.1 Mb used et=ElementTree.parse('otherdata.xml') #218.6 Mb used del et #54.1 Mb used Why does I have a such erratic memory freeing ? I've tried the same test many time with a new interpreter and I've got 43.3 Mb after the first free and 54.1 Mb after the others. If there is a memory pool limit in list ans dict, why can't I goes back to 43.3 or 54.1 Mb all the times ? I've tried using readlines(): When starting python : 2.1 Mb private memory used f=open('otherdata.xml') #2.2 Mb used data=f.readlines() #113 Mb used del data #2.7 Mb used f.seek(0) #2.7 Mb used data=f.readlines() #113 Mb used del data #2.7 Mb used That time I have a good memory handling (for my definition of memory handling) So is there a problem with cElementTree ? I've done a last test with ElementTree : When starting python : 2.1 Mb private memory used import xml.etree.ElementTree as ElementTree #3.2 Mb used et=ElementTree.parse('otherdata.xml') #211.4 Mb used (but very slow :p) del et #21.4 Mb used et=ElementTree.parse('otherdata.xml') #211.4 Mb used del et #29.8 Mb used So why does I have such differences in memory freeing ? Only due to fragmentation ? Anyway, python 2.5 has a better memory handling than 2.4, but still not perfect for me. I think I've not really understood the problem with the use of malloc (fragmentation,...) Thanks for your help Regards, FP From paul_lautman at yahoo.com Wed Jun 13 05:19:08 2007 From: paul_lautman at yahoo.com (Captain Paralytic) Date: Wed, 13 Jun 2007 02:19:08 -0700 Subject: updating db with csv In-Reply-To: References: <1181234515.502945.43770@q66g2000hsg.googlegroups.com> <1181551597.685686.129100@k79g2000hse.googlegroups.com> Message-ID: <1181726348.133523.258870@d30g2000prg.googlegroups.com> On 13 Jun, 06:35, Tim Roberts wrote: > Captain Paralytic wrote: > >On 11 Jun, 07:37, Tim Roberts wrote: > >| Not in standard SQL. MySQL supports a REPLACE extension that does > >| an UPDATE if the key already exists, and an INSERT if it does not. > >| There is also an extension clause to the INSERT statement called > >| "ON DUPLICATE KEY UPDATE xxx" that might do what you want. > > >No Tim, that is not correct. the REPLACE extension does not do an > >update, it does a replace. It delets the old record and inserts a new > >one. The INSERT...ON DUPLICATE KEY UPDATE... does an update. So a > >REPLACE will remove all existing field values not referenced in the > >statement, whilst an INSERT...ON DUPLICATE KEY UPDATE... will preserve > >them. Also REPLACE will make a TIMESTAMP column which has a DEFAULT > >CURRENT_TIMESTAMP setting work like one which has ON UPDATE > >CURRENT_TIMESTAMP DEFAULT CURRENT_TIMESTAMP setting. > > Thanks for the correction; that's an important difference. I'm a Postgres > guy; if I had noticed this was cross-posted to c.d.mysql as well as > comp.lang.python, I probably would have kept quiet. > -- > Tim Roberts, t... at probo.com > Providenza & Boekelheide, Inc. But then you wouldn't have learned about this important difference. I too learn a lot when I give what I think is a correct answer and then have someone else explain what really happens. The wonder of usenet. From bignose+hates-spam at benfinney.id.au Wed Jun 13 05:53:59 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 13 Jun 2007 19:53:59 +1000 Subject: Dive into Python 5.5 References: <1181724020.770062.286220@o11g2000prd.googlegroups.com> Message-ID: <87ir9suqmg.fsf@benfinney.id.au> james_027 writes: > class UserDict: > def __init__(self, dict=None): > self.data = {} > if dict is not None: self.update(dict) The code confusingly shadows the builtin 'dict' type with a poorly-chosen parameter name. See if this makes things less confusing:: class UserDict: def __init__(self, from=None): self.data = {} if from is not None: self.update(from) > I just don't understant this code, as it is not also mention in the > book. the update is a method of a dict right? in my understanding > the last statement should be self.data.update(dict). As you point out, the 'update' method isn't defined, and the class inherits from no base classes, so this class as written will fail in the __init__ method when the 'self.update' attribute cannot be found. What should be happening is that the class should inherit from the Python dict type: class UserDict(dict): # ... That way, the 'update' method will be inherited from the 'dict.update' method, and likewise for all the other behaviour expected from a dict type. -- \ "Madness is rare in individuals, but in groups, parties, | `\ nations and ages it is the rule." -- Friedrich Nietzsche | _o__) | Ben Finney From arkanes at gmail.com Wed Jun 6 11:16:18 2007 From: arkanes at gmail.com (Chris Mellon) Date: Wed, 6 Jun 2007 10:16:18 -0500 Subject: which "GUI module" you suggest me to use? In-Reply-To: References: <136bvigp2ps99bc@corp.supernews.com> <136di0nsamvcgd0@corp.supernews.com> Message-ID: <4866bea60706060816l67f8090ct8c0c663fc992a16d@mail.gmail.com> On 6/6/07, Samuel wrote: > On Wed, 06 Jun 2007 14:43:35 +0000, Grant Edwards wrote: > > > On 2007-06-06, Samuel wrote: > >> On Wed, 06 Jun 2007 00:22:40 +0000, Grant Edwards wrote: > >>> wxPython works fine under Windows, Linux and OSX. > >> > >> wxPython emulates Gtk > > > > What? On some platforms (Linux), wxPython _uses_ Gtk. I don't see how > > you could say it emulates it. > > That may be true in some cases, but in fact, most widgets show some sort > of difference. Take for example the HPaned - it looks totally different > (the slider is a lot slimmer, plus moving it makes a line appear. The > behavior is different as well). > I'm not familiar with any wxPython control called HPaned. There's a couple different types of splitter, the Gtk native one is wxSplitterWindow. The others are owner drawn with better or worse native appearance. Splitters are one of those things where everyone writes their own, like web frameworks. > Even simple widgets show differences. Try triple-clicking into entry > boxes, it's different from Gtk. > Text boxes are absolutely native controls under gtk. > >> (though using some native widgets, it also uses some of its own) and in > >> many cases it looks non-native compared to Gtk. > > > > How can that be the case when wxPython is using Gtk? > > Obviously, it does *not* always use Gtk. It *always* uses Gtk. Some people write or use custom controls, which may or may not have gtk native analogs. This isn't any different than using pygtk and writing custom widgets. > > >> If your target platform includes Unix systems, you'll have to decide > >> whether inconsistencies with the look and feel of the desktop are an > >> issue for you. > > > > wxPython looks completely native on Unix, because it's using a native > > widget set (Gtk). > > Same as above. > > -Samuel > -- > http://mail.python.org/mailman/listinfo/python-list > From jitudon at hotmail.com Fri Jun 15 07:48:54 2007 From: jitudon at hotmail.com (jitudon at hotmail.com) Date: Fri, 15 Jun 2007 04:48:54 -0700 Subject: Want to learn Python In-Reply-To: <1181907696.878873.214760@i13g2000prf.googlegroups.com> References: <1181907696.878873.214760@i13g2000prf.googlegroups.com> Message-ID: <1181908134.153109.71690@i38g2000prf.googlegroups.com> On Jun 15, 4:41 pm, Amol wrote: > Hi, I want to learn Python in less than a month which resources should > I use. I prefer to read books . Please give me a list of *recognized* > resources. Thank You all http://python.org/doc/ JItendra Nair From Stebanoid at gmail.com Sun Jun 3 13:03:34 2007 From: Stebanoid at gmail.com (Stebanoid at gmail.com) Date: Sun, 03 Jun 2007 10:03:34 -0700 Subject: subexpressions (OT: math) In-Reply-To: References: <4662675b$1_5@news.bluewin.ch> Message-ID: <1180890214.317409.85100@w5g2000hsg.googlegroups.com> On 3 , 14:05, Steven D'Aprano wrote: > On Sun, 03 Jun 2007 09:02:11 +0200, Leonhard Vogt wrote: > >> bla-bla > > Hmmm... perhaps that's why the author of the "units" program doesn't > treat angles as dimensionless when taking square roots. > > Given that, I withdraw my claim that the sqrt of an angle is just an > angle. I can't quite see why it shouldn't be, but the evidence is fairly > solid that it isn't. > > -- > Steven angle is dimensionless unit. To understand it: sin() can't have dimensioned argument. It is can't to be - sin(meters) it is difficult to invent what is a "sqrt from a angle" but it can be. From bbxx789_05ss at yahoo.com Tue Jun 26 17:58:47 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: Tue, 26 Jun 2007 14:58:47 -0700 Subject: subprocess.Popen() problem In-Reply-To: References: <1182890310.087603.273390@n60g2000hse.googlegroups.com> Message-ID: <1182895127.103227.43810@u2g2000hsc.googlegroups.com> On Jun 26, 3:00 pm, "Jerry Hill" wrote: > On 6/26/07, 7stud wrote: > > > p.stdin.write("hello") > > You need to add the linefeed, otherwise your mytest.py process is > still waiting for you to finish typing. So, use this instead: > > p.stdin.write("hello\n") > Arggh. Of course! Thanks >Never tried this, but I think you need to use the communicate method >detailed here: Yes, communicate() will work too, but communicate reads stdout into a string(i.e. into memory), and I don't want to do that. Thanks. From anamax at earthlink.net Tue Jun 26 11:59:28 2007 From: anamax at earthlink.net (Andy Freeman) Date: Tue, 26 Jun 2007 08:59:28 -0700 Subject: Python's "only one way to do it" philosophy isn't good? In-Reply-To: <1182872972.417776.78650@o11g2000prd.googlegroups.com> References: <7x3b0nmkk6.fsf@ruckus.brouhaha.com> <1182750077.570603.160240@q69g2000hsb.googlegroups.com> <7xir9cbm0g.fsf@ruckus.brouhaha.com> <7xejjzmk7u.fsf@ruckus.brouhaha.com> <7xy7i7xjl5.fsf@ruckus.brouhaha.com> <1182872972.417776.78650@o11g2000prd.googlegroups.com> Message-ID: <1182873568.454491.302860@e9g2000prf.googlegroups.com> On Jun 26, 8:49 am, Andy Freeman wrote: > Map doesn't work on generators or iterators because they're not part > of the common lisp spec, but if someone implemented them as a library, > said library could easily include a map that handled them as well. Note that this is is a consequence of something that Python does better than lisp. Far more parts of python are defined in terms of named operations which are data-type independent. As a result, they work on things that the implementor (or spec) never considered. That said, it's no big deal for a lisp program that needed an enhanced map that also understands iterators and generators to use it. Compare that with what a programmer using Python 2.4 has to do if she'd like the functionality provided by 2.5's with statement. Yes, with is "just syntax", but it's extremely useful syntax, syntax that can be easily implemented with lisp-style macros. From erikwickstrom at gmail.com Mon Jun 25 15:13:33 2007 From: erikwickstrom at gmail.com (erikcw) Date: Mon, 25 Jun 2007 19:13:33 -0000 Subject: Why isn't this query working in python? In-Reply-To: References: <1180103946.552760.239200@p47g2000hsd.googlegroups.com> <6e42ec490705250751i89d3cf3v3a3062690d0284aa@mail.gmail.com> <1180207521.072958.322770@p47g2000hsd.googlegroups.com> <1180225290.235515.274000@q19g2000prn.googlegroups.com> <1180279833.131269.136770@w5g2000hsg.googlegroups.com> Message-ID: <1182798813.356626.63870@w5g2000hsg.googlegroups.com> On May 27, 11:06 pm, Steve Holden wrote: > davel... at mac.com wrote: > > > On May 27, 2007, at 4:01 PM, Steve Holden wrote: > > >>erikcwwrote: > >>> On May 26, 8:21 pm, John Machin wrote: > >>>> On May 27, 5:25 am,erikcw wrote: > > >>>>> On May 25, 11:28 am, Carsten Haese wrote: > >>>>>> On Fri, 2007-05-25 at 09:51 -0500, Dave Borne wrote: > >>>>>>>> I'm trying to run the following query: > >>>>>>> ... > >>>>>>>> member_id=%s AND expire_date > NOW() AND completed=1 AND > >>>>>>>> (product_id > >>>>>>> Shouldn't you be using the bind variable '?' instead of '%s' ? > >>>>>> The parameter placeholder for MySQLdb is, indeed and > >>>>>> unfortunately, %s. > >>>>>> The OP is using parameter substitution correctly, though in an > >>>>>> obfuscated fashion. 'sql' is a misnamed tuple containing both the > >>>>>> query > >>>>>> string *and* the parameters, which is being unpacked with '*' into > >>>>>> two > >>>>>> arguments to the execute call. > >>>>>> The only problem I see is that the parameters should be a > >>>>>> sequence, i.e. > >>>>>> (self.uid,) instead of just (self.uid). > >>>>>> HTH, > >>>>>> -- > >>>>>> Carsten Haesehttp://informixdb.sourceforge.net > >>>>> I tried adding the comma to make it a sequence - but now change. > >>>>> ('SELECT payment_id FROM amember_payments WHERE member_id=%s AND > >>>>> expire_date > NOW() AND completed=1 AND (product_id >11 AND product_id > >>>>> <21)', (1608L,)) > >>>>> () > >>>>> What else could it be? > >>>> Possibly a type mismatch. How is member_id declared in the CREATE > >>>> TABLE? For diagnostic purposes, try passing in (1608,) and ('1608',). > > >>> Here is a copy of the table schema and the first 2 rows. > > >>> -- phpMyAdmin SQL Dump > >>> -- version 2.9.0.2 > >>> --http://www.phpmyadmin.net > >>> -- > >>> -- Host: localhost > >>> -- Generation Time: May 27, 2007 at 11:29 AM > >>> -- Server version: 5.0.27 > >>> -- PHP Version: 4.4.2 > >>> -- > >>> -- Database: `lybp_lybp` > >>> -- > > >>> -- -------------------------------------------------------- > > >>> -- > >>> -- Table structure for table `amember_payments` > >>> -- > > >>> CREATE TABLE `amember_payments` ( > >>> `payment_id` int(11) NOT NULL auto_increment, > >>> `member_id` int(11) NOT NULL default '0', > >>> `product_id` int(11) NOT NULL default '0', > >>> `begin_date` date NOT NULL default '0000-00-00', > >>> `expire_date` date NOT NULL default '0000-00-00', > >>> `paysys_id` varchar(32) NOT NULL default '', > >>> `receipt_id` varchar(32) NOT NULL default '', > >>> `amount` decimal(12,2) NOT NULL default '0.00', > >>> `completed` smallint(6) default '0', > >>> `remote_addr` varchar(15) NOT NULL default '', > >>> `data` text, > >>> `time` timestamp NOT NULL default CURRENT_TIMESTAMP on update > >>> CURRENT_TIMESTAMP, > >>> `aff_id` int(11) NOT NULL default '0', > >>> `payer_id` varchar(255) NOT NULL default '', > >>> `coupon_id` int(11) NOT NULL default '0', > >>> `tm_added` datetime NOT NULL default '0000-00-00 00:00:00', > >>> `tm_completed` datetime default NULL, > >>> `tax_amount` decimal(12,2) NOT NULL default '0.00', > >>> PRIMARY KEY (`payment_id`), > >>> KEY `member_id` (`member_id`), > >>> KEY `payer_id` (`payer_id`), > >>> KEY `coupon_id` (`coupon_id`), > >>> KEY `tm_added` (`tm_added`,`product_id`), > >>> KEY `tm_completed` (`tm_completed`,`product_id`) > >>> ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=11020 ; > > >>> -- > >>> -- Dumping data for table `amember_payments` > >>> -- > > >>> INSERT INTO `amember_payments` VALUES (423, 107, 1, '2004-10-01', > >>> '2004-10-21', 'authorize_aim', '5687944', 3.95, 1, '', NULL, > >>> '2004-11-30 19:21:43', 0, '', 0, '2004-11-30 19:21:43', '2004-11-30 > >>> 19:21:43', 0.00); > >>> INSERT INTO `amember_payments` VALUES (422, 107, 1, '2004-10-22', > >>> '2004-11-21', 'authorize_aim', '5873225', 9.95, 1, '', NULL, > >>> '2004-11-30 19:22:18', 0, '', 0, '2004-11-30 19:20:13', '2004-11-30 > >>> 19:20:13', 0.00); > > >>> Thanks for your help! > >>> Erik > > >> I feel obliged to point out that there ARE no rows meeting the criteria > >> you query specified! > > >> mysql> SELECT expire_date, NOW() FROM amember_payments; > >> +-------------+---------------------+ > >> | expire_date | NOW() | > >> +-------------+---------------------+ > >> | 2004-10-21 | 2007-05-27 15:59:21 | > >> | 2004-11-21 | 2007-05-27 15:59:21 | > >> +-------------+---------------------+ > >> 2 rows in set (0.02 sec) > > >> mysql> > > >> So I am not sure how you managed to get a manual query to work, but do > >> be sure that the Python query you mentioned at the start of the thread > > >> sql = """SELECT payment_id FROM amember_payments WHERE > >> member_id=%s AND expire_date > NOW() AND completed=1 AND (product_id > >>>> 11 AND product_id <21)""", (self.uid) > > > And doesn't the above comma, need to be a percent symbol? > > Nope. > > > Dave > > >> doesn't stand a chance of returning any results unless you use a time > >> machine to go back almost three years! > > >> regards > >> Steve > > -- > Steve Holden +1 571 484 6266 +1 800 494 3119 > Holden Web LLC/Ltd http://www.holdenweb.com > Skype: holdenweb http://del.icio.us/steve.holden > ------------------ Asciimercial --------------------- > Get on the web: Blog, lens and tag your way to fame!! > holdenweb.blogspot.com squidoo.com/pythonology > tagged items: del.icio.us/steve.holden/python > All these services currently offer free registration! > -------------- Thank You for Reading ---------------- The SQL my script is generating is still returning an empty recordset. However, when I run SELECT * FROM amember_payments WHERE member_id=2124 AND expire_date > NOW() AND completed=1 AND (product_id >11 AND product_id <21) directly in phpMyAdmin - it works. Here is an updated subset of the database that should work better for testing: CREATE TABLE `amember_payments` ( `payment_id` int(11) NOT NULL auto_increment, `member_id` int(11) NOT NULL default '0', `product_id` int(11) NOT NULL default '0', `begin_date` date NOT NULL default '0000-00-00', `expire_date` date NOT NULL default '0000-00-00', `paysys_id` varchar(32) NOT NULL default '', `receipt_id` varchar(32) NOT NULL default '', `amount` decimal(12,2) NOT NULL default '0.00', `completed` smallint(6) default '0', `remote_addr` varchar(15) NOT NULL default '', `data` text, `time` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP, `aff_id` int(11) NOT NULL default '0', `payer_id` varchar(255) NOT NULL default '', `coupon_id` int(11) NOT NULL default '0', `tm_added` datetime NOT NULL default '0000-00-00 00:00:00', `tm_completed` datetime default NULL, `tax_amount` decimal(12,2) NOT NULL default '0.00', PRIMARY KEY (`payment_id`), KEY `member_id` (`member_id`), KEY `payer_id` (`payer_id`), KEY `coupon_id` (`coupon_id`), KEY `tm_added` (`tm_added`,`product_id`), KEY `tm_completed` (`tm_completed`,`product_id`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=11508 ; INSERT INTO `amember_payments` VALUES (10710, 970, 8, '2007-05-05', '2007-06-05', 'authorize_aim', '1424138558', '19.95', 1, '71.229.108.131', 'a:6:{s:15:"COUPON_DISCOUNT";N;s:10:"TAX_AMOUNT";N;s: 5:"TAXES";N;i:0;a:1:{s:12:"RENEWAL_ORIG";s:19:"RENEWAL_ORIG: 10325";}i: 1;a:25:{s:7:"x_Login";s:12:"478459b79866";s:9:"x_Version";s:3:"3.1";s: 12:"x_Delim_Data";s:4:"True";s:10:"x_Tran_Key";s: 16:"eeRay89XQNAic8KJ";s:12:"x_Delim_Char";s:1:"|";s: 13:"x_Invoice_Num";s:9:"10710-329";s:8:"x_Amount";s:5:"19.95";s: 15:"x_Currency_Code";s:3:"USD";s:10:"x_Card_Num";s:19:"**** **** **** 4020";s:10:"x_Exp_Date";s:4:"1007";s:6:"x_Type";s:12:"AUTH_CAPTURE";s: 16:"x_Relay_Response";s:5:"FALSE";s:7:"x_Email";s: 20:"larry at israeltour.com";s:13:"x_Description";s:11:"The AdTool-";s: 9:"x_Cust_ID";s:3:"970";s:12:"x_First_Name";s:5:"Larry";s: 11:"x_Last_Name";s:6:"Ritter";s:9:"x_Address";s:21:"107 E Mt Pleasant Ave";s:6:"x_City";s:10:"Livingston";s:7:"x_State";s:2:"NJ";s: 5:"x_Zip";s:5:"07039";s:9:"x_Country";s:2:"US";s:9:"x_Company";s: 27:"Israel Tour Connection, LLC";s:13:"x_Customer_IP";s: 13:"64.139.74.236";s:7:"x_Phone";s:10:"9735352575";}i:2;a:7:{s: 6:"RESULT";s:1:"1";s:10:"RESULT_SUB";s:1:"1";s:11:"REASON_CODE";s: 1:"1";s:7:"RESPMSG";s:35:"This transaction has been approved.";s: 3:"AVS";s:1:"Y";s:5:"PNREF";s:10:"1424138558";s:9:"CVV_VALID";s: 0:"";}}', '2007-05-06 10:52:25', 0, 'cc:d41d8cd98f00b204e9800998ecf8427e', 0, '2007-05-06 10:52:22', '2007-05-06 10:52:25', '0.00'); INSERT INTO `amember_payments` VALUES (10711, 2124, 18, '2007-05-05', '2007-06-26', 'authorize_aim', '1424138585', '97.00', 1, '71.229.108.131', 'a:8:{s:15:"COUPON_DISCOUNT";N;s:10:"TAX_AMOUNT";N;s: 5:"TAXES";N;i:0;a:1:{s:12:"RENEWAL_ORIG";s:19:"RENEWAL_ORIG: 10326";}i: 1;a:25:{s:7:"x_Login";s:12:"478459b79866";s:9:"x_Version";s:3:"3.1";s: 12:"x_Delim_Data";s:4:"True";s:10:"x_Tran_Key";s: 16:"eeRay89XQNAic8KJ";s:12:"x_Delim_Char";s:1:"|";s: 13:"x_Invoice_Num";s:9:"10711-845";s:8:"x_Amount";s:5:"97.00";s: 15:"x_Currency_Code";s:3:"USD";s:10:"x_Card_Num";s:19:"**** **** **** 6006";s:10:"x_Exp_Date";s:4:"0709";s:6:"x_Type";s:12:"AUTH_CAPTURE";s: 16:"x_Relay_Response";s:5:"FALSE";s:7:"x_Email";s: 25:"kirtchristensen at gmail.com";s:13:"x_Description";s:21:"Winner Alert Pro User";s:9:"x_Cust_ID";s:4:"2124";s:12:"x_First_Name";s:4:"Kirt";s: 11:"x_Last_Name";s:11:"Christensen";s:9:"x_Address";s:19:"3402 S. Melissa Dr.";s:6:"x_City";s:14:"Spokane Valley";s:7:"x_State";s: 2:"WA";s:5:"x_Zip";s:5:"99206";s:9:"x_Country";s:2:"US";s: 9:"x_Company";s:0:"";s:13:"x_Customer_IP";s:14:"67.185.167.174";s: 7:"x_Phone";s:12:"509-242-7867";}i:2;a:7:{s:6:"RESULT";s:1:"1";s: 10:"RESULT_SUB";s:1:"1";s:11:"REASON_CODE";s:1:"1";s:7:"RESPMSG";s: 35:"This transaction has been approved.";s:3:"AVS";s:1:"Y";s: 5:"PNREF";s:10:"1424138585";s:9:"CVV_VALID";s:0:"";}s: 16:"orig_expire_date";s:10:"2007-06-05";s:8:"prorated";s:7:"3, 8, 8";}', '2007-06-25 09:28:38', 0, 'cc:d41d8cd98f00b204e9800998ecf8427e', 0, '2007-05-06 10:52:26', '2007-05-06 10:52:28', '0.00'); INSERT INTO `amember_payments` VALUES (10712, 2006, 10, '2007-05-05', '2008-05-05', 'authorize_aim', '', '147.00', 0, '71.229.108.131', 'a:6: {s:15:"COUPON_DISCOUNT";N;s:10:"TAX_AMOUNT";N;s:5:"TAXES";N;i:0;a:1:{s: 12:"RENEWAL_ORIG";s:18:"RENEWAL_ORIG: 5711";}i:1;a:25:{s:7:"x_Login";s: 12:"478459b79866";s:9:"x_Version";s:3:"3.1";s:12:"x_Delim_Data";s: 4:"True";s:10:"x_Tran_Key";s:16:"eeRay89XQNAic8KJ";s: 12:"x_Delim_Char";s:1:"|";s:13:"x_Invoice_Num";s:9:"10712-465";s: 8:"x_Amount";s:6:"147.00";s:15:"x_Currency_Code";s:3:"USD";s: 10:"x_Card_Num";s:19:"**** **** **** 2785";s:10:"x_Exp_Date";s: 4:"0908";s:6:"x_Type";s:12:"AUTH_CAPTURE";s:16:"x_Relay_Response";s: 5:"FALSE";s:7:"x_Email";s:23:"superbusiness at gmail.com";s: 13:"x_Description";s:14:"AdTool Annual-";s:9:"x_Cust_ID";s:4:"2006";s: 12:"x_First_Name";s:9:"Dimitrios";s:11:"x_Last_Name";s:9:"Katsoulis";s: 9:"x_Address";s:18:"430 Briarvista Way";s:6:"x_City";s:7:"Atlanta";s: 7:"x_State";s:2:"GA";s:5:"x_Zip";s:5:"30329";s:9:"x_Country";s: 2:"US";s:9:"x_Company";s:0:"";s:13:"x_Customer_IP";s: 13:"24.98.190.106";s:7:"x_Phone";s:12:"404-634-0031";}i:2;a:7:{s: 6:"RESULT";s:1:"2";s:10:"RESULT_SUB";s:1:"1";s:11:"REASON_CODE";s: 1:"2";s:7:"RESPMSG";s:35:"This transaction has been declined.";s: 3:"AVS";s:1:"Y";s:5:"PNREF";s:10:"1424138607";s:9:"CVV_VALID";s: 0:"";}}', '2007-05-06 10:52:30', 0, '', 0, '2007-05-06 10:52:28', NULL, '0.00'); INSERT INTO `amember_payments` VALUES (10713, 1574, 8, '2007-05-06', '2007-06-06', 'authorize_aim', '', '19.95', 0, '71.229.108.131', 'a:6: {s:15:"COUPON_DISCOUNT";N;s:10:"TAX_AMOUNT";N;s:5:"TAXES";N;i:0;a:1:{s: 12:"RENEWAL_ORIG";s:19:"RENEWAL_ORIG: 10192";}i:1;a:25:{s: 7:"x_Login";s:12:"478459b79866";s:9:"x_Version";s:3:"3.1";s: 12:"x_Delim_Data";s:4:"True";s:10:"x_Tran_Key";s: 16:"eeRay89XQNAic8KJ";s:12:"x_Delim_Char";s:1:"|";s: 13:"x_Invoice_Num";s:9:"10713-206";s:8:"x_Amount";s:5:"19.95";s: 15:"x_Currency_Code";s:3:"USD";s:10:"x_Card_Num";s:19:"**** **** **** 9006";s:10:"x_Exp_Date";s:4:"0407";s:6:"x_Type";s:12:"AUTH_CAPTURE";s: 16:"x_Relay_Response";s:5:"FALSE";s:7:"x_Email";s: 25:"sales at unusualonline.co.uk";s:13:"x_Description";s:11:"The AdTool-";s:9:"x_Cust_ID";s:4:"1574";s:12:"x_First_Name";s:4:"John";s: 11:"x_Last_Name";s:9:"Flowerdew";s:9:"x_Address";s:14:"8A Oxted Green";s:6:"x_City";s:18:"Milford, Godalming";s:7:"x_State";s:2:"XX";s: 5:"x_Zip";s:7:"GU8 5DA";s:9:"x_Country";s:2:"GB";s:9:"x_Company";s: 0:"";s:13:"x_Customer_IP";s:14:"80.176.190.185";s:7:"x_Phone";s: 15:"0044 1483861858";}i:2;a:7:{s:6:"RESULT";s:1:"3";s: 10:"RESULT_SUB";s:1:"1";s:11:"REASON_CODE";s:1:"8";s:7:"RESPMSG";s: 28:"The credit card has expired.";s:3:"AVS";s:1:"P";s:5:"PNREF";s: 1:"0";s:9:"CVV_VALID";s:0:"";}}', '2007-05-06 10:52:31', 0, '', 0, '2007-05-06 10:52:30', NULL, '0.00'); Thanks for your help! Erik From montyphyton at gmail.com Wed Jun 6 04:53:56 2007 From: montyphyton at gmail.com (montyphyton at gmail.com) Date: Wed, 06 Jun 2007 01:53:56 -0700 Subject: which "GUI module" you suggest me to use? In-Reply-To: References: <1181082196.630888.161620@w5g2000hsg.googlegroups.com> Message-ID: <1181120036.080160.156450@o5g2000hsb.googlegroups.com> > This completely loses me; what do you mean by "draw its own icon", > and what does that have to do with rendering Web pages? maybe "draw its own icons" wasn't the best (or the most accurate way) of putting it. what i meant by that is this (from wikipedia): "Qt uses its own paint engine and controls. This makes the work of porting to other platforms easier because very few classes in Qt depended on the target platform. Qt used to emulate the native look of its intended platforms, which occasionally led to slight discrepancies where that emulation wasn't perfect. This, however, no longer applies because the latest versions of Qt use the native styles API of the different platforms to draw the Qt controls." what does that have to do with rendering web pages? have no idea. i just wanted to point out the main difference between qt and wx that he should be aware of. From gagsl-py2 at yahoo.com.ar Wed Jun 27 00:19:46 2007 From: gagsl-py2 at yahoo.com.ar (gagsl-py2 at yahoo.com.ar) Date: Wed, 27 Jun 2007 01:19:46 -0300 (ART) Subject: Can Readlines() go to next line after a Tab In-Reply-To: <907447.255451182911425439.JavaMail.servlet@perfora> Message-ID: <536600.91507.qm@web32806.mail.mud.yahoo.com> (Please keep posting on this list) --- tim at preservedwords.com escribi?: > Thanks, but this method still reads the whole line > into memory. I would like to find a way for it to > stop reading when it encounters a \t and then go to > the next. This would be much faster. You can't avoid reading the whole line - how can you detect the end-of-line, unless you use fixed-length records? > According to my tests, readlines with a regular > expression is actually faster than the index method > you mentioned. Here is the code testing a 25meg file > with thousands of lines, Hard to believe, altough that depends on a lot of factors. Is the posted code all your testing code? If so, it doesn't look right. Write two separate functions, without side effects each (in this case, that means using a local variable for kwords). Let's call them f1 and f2, inside kw.py. Use the timeit module to measure performance instead of time.time(). Execute both functions *separately* on two *separate* Python invocations, like this: python -m timeit -s "from kw import f1,f2" "f1()" python -m timeit -s "from kw import f1,f2" "f2()" and see what happens. -- Gabriel Genellina __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From mkent at acm.org Fri Jun 1 00:59:32 2007 From: mkent at acm.org (Mike Kent) Date: Fri, 01 Jun 2007 00:59:32 -0400 Subject: Announcing: ACM SIGAPL apl 2007 -- Arrays and Objects In-Reply-To: <5btvf0F2tndakU1@mid.individual.net> References: <5btvf0F2tndakU1@mid.individual.net> Message-ID: <5c9nd8F2tdc6bU1@mid.individual.net> The APL2007 URL was given incorrectly .... should be http://www.sigapl.org/apl2007.html From devicerandom at gmail.com Thu Jun 28 08:30:34 2007 From: devicerandom at gmail.com (massimo s.) Date: Thu, 28 Jun 2007 05:30:34 -0700 Subject: problem with hack using multiple inheritance for plugins In-Reply-To: <46839f4c$0$22380$426a74cc@news.free.fr> References: <1183026288.857294.91620@q69g2000hsb.googlegroups.com> <1183028051.940679.145680@q69g2000hsb.googlegroups.com> <46839f4c$0$22380$426a74cc@news.free.fr> Message-ID: <1183033834.301669.7220@g4g2000hsf.googlegroups.com> On 28 Giu, 13:45, Bruno Desthuilliers wrote: > > wrt/ this snippet: > > for plugin_name in self.config['plugins']: > try: > plugin=__import__(plugin_name) > try: > print type(self) > eval('plugin.'+plugin_name+'Commands._plug_init(self)') > except AttributeError: > pass > except ImportError: > pass > > You may want to try this instead: > > for plugin_name in self.config['plugins']: > try: > plugin=__import__(plugin_name) > except ImportError: > # eventually do something like logging the error ? > continue > try: > cmdplug = getattr(plugin, plugin_name+'Commands') > cmdplug._plug_init(self) > except AttributeError: > # eventually do something like logging the error ? > continue Tried, same error as before :( From rw at smsnet.pl Wed Jun 6 03:45:24 2007 From: rw at smsnet.pl (Rob Wolfe) Date: Wed, 06 Jun 2007 00:45:24 -0700 Subject: Encoding problem with web application (Paste+Mako) In-Reply-To: <1181113712.128103.228180@q69g2000hsb.googlegroups.com> References: <1181113712.128103.228180@q69g2000hsb.googlegroups.com> Message-ID: <1181115924.234501.11260@p47g2000hsd.googlegroups.com> msj at infoserv.dk wrote: > Hi > > I have a problem with encoding non-ascii characters in a web > application. The application uses Paste and Mako. > > The code is here: http://www.webudkast.dk/demo.txt > > The main points are: > > After getting some user generated input using > paste.request.parse_formvars, how should this be correctly saved to > file? > > How should this afterward be read from the file, and fed correctly > into a Mako template? You have to know the encoding of user input and then you can use ``input_encoding`` and ``output_encoding`` parameters of ``Template``. Mako internally handles everything as Python unicode objects. For example: t = Template(filename="templ.mako", input_encoding="iso-8859-2", output_encoding="iso-8859-2") content = t.render(**context) -- HTH, Rob From thopfin at umich.edu Tue Jun 5 13:22:48 2007 From: thopfin at umich.edu (Todd Hopfinger) Date: Tue, 5 Jun 2007 13:22:48 -0400 Subject: TLSAbruptCloseError Message-ID: <000d01c7a796$23691250$6a3b36f0$@edu> I am using TLS Lite and J2ME SecureConnection for the purposes of encrypting traffic to/from a Java Midlet client and a multithreaded Python server. However, I encounter a TLSAbruptCloseError. I have tried to determine the cause of the exception to no avail. I understand that it has to do with close_notify alerts. My abbreviated code follows. // Server def sslSockRecv(conn, num): data = '' while len(data) < num: data = conn.recv(num - len(data)) # TLSAbruptCloseError thrown here if len(data) == 0: raise NotEnoughBytes ('Too few bytes from client. Expected ' + str(num) + '; got ' + str(len(data)), num, len(data)) return data sslSockRecv() throws NotEnoughBytes exception to indicate that the client has closed the connection. The NotEnoughBytes exception handler subsequently closes the SSL connection and then the underlying socket. // Client import javax.microedition.io.SecureConnection; sc = (SecureConnection)Connector.open("ssl://host:port"); inStream = sc.openInputStream(); outStream = sc.openOutputStream(); // read/write some data using streams if (inStream != null) inStream.close(); if (outStream != null) outStream.close(); if (sc != null) sc.close(); When using the Java phone emulator, SSLDump indicates after the application data portions. 3 13 0.3227 (0.0479) C>SV3.0(22) Alert level warning value close_notify 3 0.3228 (0.0000) C>S TCP FIN 3 14 0.3233 (0.0005) S>CV3.0(22) Alert level warning value close_notify However, the server doesn't throw a TLSAbruptCloseError when using the emulator. Using the actual phone does cause a TLSAbruptCloseError on the server but SSLDump reports no errors, just. 4 1.6258 (0.7012) C>S TCP FIN 4 1.6266 (0.0008) S>C TCP FIN Any thoughts? Todd Hopfinger -------------- next part -------------- An HTML attachment was scrubbed... URL: From zeevb.public at gmail.com Sun Jun 17 05:01:34 2007 From: zeevb.public at gmail.com (Ze'ev) Date: Sun, 17 Jun 2007 09:01:34 -0000 Subject: PythonWin crash - works only once after installation In-Reply-To: <1181906344.466356.21570@k79g2000hse.googlegroups.com> References: <1181906344.466356.21570@k79g2000hse.googlegroups.com> Message-ID: <1182070894.188049.268660@k79g2000hse.googlegroups.com> On Jun 15, 2:19 pm, Ze'ev wrote: > Hi, > I've installed Python 2.5 and PythonWin (pywin32-210.win32-py2.5) on > my new XP machine. The first time I run PythonWin after installation > it runs normally but if I close it and try to run it again it crashes > ("PyWin32 has encountered a problem and needs to close") every time. > If I re-install it then it will run once more but subsequent runs > fail. > I've installed and ran this before (on my old machine and at work) and > it runs ok. > > Any clues? > > Thanks, > Ze'ev I found a workaround but this is still a mystery - if I delete the.pyc files in site-packages/pythonwin/pywin/ then I can run Pythonwin again (otherwise it crashes upon starting up). Ze'ev From tjreedy at udel.edu Sat Jun 9 03:48:12 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 9 Jun 2007 03:48:12 -0400 Subject: interating over single element array References: <4Beai.13210$5j1.6184@newssvr21.news.prodigy.net> <1181345593.788652.275380@h2g2000hsg.googlegroups.com> Message-ID: "Basilisk96" wrote in message news:1181345593.788652.275380 at h2g2000hsg.googlegroups.com... | On Jun 8, 11:54 am, "T. Crane" wrote: | You can also do this (if tuples are okay in your case): | | a = 1, | | The comma turns 'a' into a tuple (1,) which is both iterable and has a | length of 1. | | I have run into this issue before with a function that took a list of | filenames (strings), and needed to iterate over the list to operate on | the input files. For the case when the input would be a single file, I | needed to turn the input string into an iterable such that the 'for' | loop would not iterate on the filename characters (a rather | undesirable gotcha, you understand :-) ). So I solved my problem like | this: | | def loadfiles(filelist): | if not isinstance(filelist, list): | filelist = filelist, Any what if 'filelist' is any iterable other than a string or list? Your code is broken, and unnecessarily so. So I would call the parameter 'files' and test for isinstance(files, str) #or basestring. And wrap if it is. | for filename in filelist: | f = open(filename,'r') | #do interesting stuff with file, etc... | | ..and it's been working very well. | | Cheers, | -Basilisk96 | | -- | http://mail.python.org/mailman/listinfo/python-list | From paddy3118 at googlemail.com Wed Jun 20 16:50:45 2007 From: paddy3118 at googlemail.com (Paddy) Date: Wed, 20 Jun 2007 20:50:45 -0000 Subject: PEP 3107 and stronger typing (note: probably a newbie question) In-Reply-To: References: <1182369568.941307.316260@p77g2000hsh.googlegroups.com> Message-ID: <1182372645.512773.57070@c77g2000hse.googlegroups.com> On Jun 20, 9:05 pm, Stephen R Laniel wrote: > On Wed, Jun 20, 2007 at 12:59:28PM -0700, bruno.desthuilli... at gmail.com wrote: > > Then you should use another language. > > This is what I meant about knowing how Internet discussions > go. > And knowing that, why not take more care with the tone of your original post, or do more searching and/or lurking before posting? Your original post *could* be paraphrased as: I'm new to Python, Python doesn't have X, X is obviously a great feature can't you give me X in Python? P.S. Its obviously been debated before but I haven't looked - send me a link. I know this might start a flame war, but I'll ask anyway. And sure enough, you then goad a regular *contributor* to comp.lang.python . I suggest you rephrase your question in a less confrontational tone but only if you are interested in civil answers. - Paddy. From apatheticagnostic at gmail.com Tue Jun 12 07:22:54 2007 From: apatheticagnostic at gmail.com (kaens) Date: Tue, 12 Jun 2007 07:22:54 -0400 Subject: for ... else ? In-Reply-To: <466e71a0$0$90271$14726298@news.sunsite.dk> References: <1181622331.955264.31610@i38g2000prf.googlegroups.com> <1181640889.439145.60020@g37g2000prf.googlegroups.com> <466e71a0$0$90271$14726298@news.sunsite.dk> Message-ID: <163f0ce20706120422o1d2fba1by402cbe9487efc2e8@mail.gmail.com> On 6/12/07, Nis J?rgensen wrote: > exhuma.twn skrev: > > >> for number in range(10,100): > >> for divisor in range(2,number): > >> if number % divisor == 0: > >> break > >> else: > >> print number, > >> > > > > Oh my. Would it not be an idea to rename this "else" into a "finally"? > > As Gabriel points out, the else-block gets executed after the for loop > > exits *normally*. In that case, is the "else" not semantically > > misleading? I would surely misunderstand it if I saw it the first time. > > "finally" would be at least equally confusing IMO, indicating that the > code is always called (although this would of course make it a > ridiculous construct). > > /Nis > -- > http://mail.python.org/mailman/listinfo/python-list > I think finally would be semantically nicer than else. . . maybe something like "andthen" instead (yeah that's ugly). I mean, else works (so would herbivore), but the terminology is a bit weird. From showell30 at yahoo.com Mon Jun 4 21:58:06 2007 From: showell30 at yahoo.com (Steve Howell) Date: Mon, 4 Jun 2007 18:58:06 -0700 (PDT) Subject: Python, Dutch, English, Chinese, Japanese, etc. In-Reply-To: <1180997172.657169.134660@o5g2000hsb.googlegroups.com> Message-ID: <505659.91506.qm@web33511.mail.mud.yahoo.com> --- MRAB wrote: > Instead of having many different Pythons for many > different languages, > how about one for a language like Esperanto? > > http://en.wikipedia.org/wiki/Esperanto > > That could be the language for the standard > libraries instead of > English. > English beats Esperanto by a long shot in terms of practical acceptance. Also, Esperanto's 28-letter alphabet makes it inferior to other written languages that are compatible with Python's current 26-letter alphabet that it inherits from English. >From wikipedia: ''' Because a working knowledge of English is required in certain fields, professions, and occupations, English is studied and spoken by up to a billion people around the world, to at least a basic level... ''' http://en.wikipedia.org/wiki/English_language >From the same article: ''' [When] combining native and non-native speakers [English] is probably the most commonly spoken language in the world, though possibly second to a combination of the Chinese Languages, depending on whether or not distinctions in the latter are classified as "languages" or "dialects." ''' See also: http://en.wikipedia.org/wiki/List_of_languages_by_number_of_native_speakers ____________________________________________________________________________________ Choose the right car based on your needs. Check out Yahoo! Autos new Car Finder tool. http://autos.yahoo.com/carfinder/ From jjl at pobox.com Tue Jun 26 17:54:32 2007 From: jjl at pobox.com (John J. Lee) Date: Tue, 26 Jun 2007 21:54:32 GMT Subject: something similar to shutil.copytree that can overwrite? References: <1182331815.865344.190700@u2g2000hsc.googlegroups.com> <1182336006.442871.287590@a26g2000pre.googlegroups.com> <1182423939.466780.322230@c77g2000hse.googlegroups.com> Message-ID: <87hcouidpk.fsf@pobox.com> Ben Sizer writes: > On 20 Jun, 11:40, Justin Ezequiel > wrote: >> On Jun 20, 5:30 pm, Ben Sizer wrote: >> >> > I need to copy directories from one place to another, but it needs to >> > overwrite individual files and directories rather than just exiting if >> > a destination file already exists. >> >> What version of Python do you have? >> Nothing in the source would make it exit if a target file exists. >> (Unless perhaps you have sym-links or the like.) > > I have 2.5, and I believe the behaviour I saw was that it exits if a > directory already exists and it skips any files that already exist. It > certainly wouldn't overwrite anything. How about distutils.dir_util.copy_tree? It's a documented API: http://docs.python.org/dist/module-distutils.dirutil.html Here's a demo. Note the arguments to distutils.dir_util.copy_tree have a different meaning to shutil.copytree IIRC (you need to pass the parent of the directory rather than the directory itself): from distutils.dir_util import copy_tree import os def mkdir(dirname): os.mkdir(dirname) def write(filename, data): f = open(filename, "w") try: f.write(data) finally: f.close() def read(filename): f = open(filename) try: return f.read() finally: f.close() def make_tree_1(): mkdir("1") mkdir(os.path.join("1", "1")) write(os.path.join("1", "1", "a"), "abc") return "1" def make_tree_2(): mkdir("2") mkdir(os.path.join("2", "1")) write(os.path.join("2", "1", "a"), "bcd") return "2" dirname_1 = make_tree_1() dirname_2 = make_tree_2() copy_tree(dirname_1, dirname_2) result = read(os.path.join(dirname_2, "1", "a")) assert result == "abc", result John From gagsl-py2 at yahoo.com.ar Sat Jun 9 23:19:27 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 10 Jun 2007 00:19:27 -0300 Subject: Are there any python jobs worked at home from the internet? References: Message-ID: En Sat, 09 Jun 2007 22:53:08 -0300, boyeestudio escribi?: > Are there any python jobs worked at home from the internet? > I want to find a part time job. > Please give a clue to this for me. I know of http://www.rentacoder.com/ but I've never actually used it. -- Gabriel Genellina From winexpert at hotmail.com Sat Jun 2 16:41:37 2007 From: winexpert at hotmail.com (David Stockwell) Date: Sat, 02 Jun 2007 20:41:37 +0000 Subject: Help with win32 com_error exception In-Reply-To: Message-ID: Hi Rich, I've seen errors like this before. first off it will help you better if you represent your error in hex. Doing so yields this FFFFFFFF80020009 <==> -2147352567 0xFFFFFFFF 0x80020009 Anyways, its probably the result of something not being either registered/installed correctly (COM issue) or something else. Under COM I believe thats a standard issue just telling you that something unexpected occurred. I'd take a look at http://msdn.microsoft.com. Good Luck David Stockwell Lanham, MD >From: "Richard Gordon" >To: python-list at python.org >Subject: Help with win32 com_error exception >Date: Sat, 02 Jun 2007 20:28:56 GMT >MIME-Version: 1.0 >Received: from smtp-vbr6.xs4all.nl ([194.109.24.26]) by >bay0-mc10-f17.bay0.hotmail.com with Microsoft SMTPSVC(6.0.3790.2668); Sat, >2 Jun 2007 13:31:22 -0700 >Received: from bag.python.org (bag.python.org [194.109.207.14])by >smtp-vbr6.xs4all.nl (8.13.8/8.13.8) with ESMTP id l52KVLxg031447for >; Sat, 2 Jun 2007 22:31:21 +0200 >(CEST)(envelope-from python-list-bounces+winexpert=hotmail.com at python.org) >Received: from bag.python.org (bag [127.0.0.1])by bag.python.org (Postfix) >with ESMTP id 6421A1E4012for ; Sat, 2 Jun 2007 >22:31:21 +0200 (CEST) >X-Message-Info: >oG9qAjD2BNEKOO/ojloMHZY07EZB5Us4bOLWVGLHXVIL+amzV6Z4QzwmLaq+zJlt >Path: >news.xs4all.nl!newsspool.news.xs4all.nl!transit.news.xs4all.nl!xs4all!transit1.news.tiscali.nl!tiscali!newsfeed1.ip.tiscali.net!news.tiscali.de!newsfeed.freenet.de!newspeer1.nwr.nac.net!border2.nntp.dca.giganews.com!nntp.giganews.com!cyclone1.gnilink.net!spamkiller.gnilink.net!gnilink.net!trnddc08.POSTED!0775c1e7!not-for-mail >Newsgroups: comp.lang.python >Lines: 47 >X-MSMail-Priority: Normal >X-Newsreader: Microsoft Outlook Express 6.00.2900.3028 >X-MIMEOLE: Produced By Microsoft MimeOLE V6.00.2900.3028 >X-RFC2646: Format=Flowed; Original >NNTP-Posting-Host: 70.17.187.153 >X-Complaints-To: abuse at verizon.net >X-Trace: trnddc08 1180816136 70.17.187.153 (Sat, 02 Jun 2007 16:28:56 EDT) >NNTP-Posting-Date: Sat, 02 Jun 2007 16:28:56 EDT >Xref: news.xs4all.nl comp.lang.python:497807 >X-BeenThere: python-list at python.org >X-Mailman-Version: 2.1.9 >Precedence: list >List-Id: General discussion list for the Python programming >language >List-Unsubscribe: >, >List-Archive: >List-Post: >List-Help: >List-Subscribe: >, >Errors-To: python-list-bounces+winexpert=hotmail.com at python.org >X-Virus-Scanned: by XS4ALL Virus Scanner >Return-Path: python-list-bounces+winexpert=hotmail.com at python.org >X-OriginalArrivalTime: 02 Jun 2007 20:31:22.0646 (UTC) >FILETIME=[FBF71B60:01C7A554] > >Sorry if this is sent twice, but I didn't see it get posted the first time. > >I've got a fatal bug using Parente's pyTTS with Python 2.3 on Windoze 32 >using MS SAPI 5.1 and Hammond's win32 module. The test program is > import pyTTS > tts = pyTTS.Create() > tts.Speak('Hello world.') > >The resulting debug trace is: > > PythonWin 2.3.5 (#62, Feb 8 2005, 16:23:02) [MSC v.1200 32 bit (Intel)] >on win32. > Portions Copyright 1994-2006 Mark Hammond - see 'Help/About PythonWin' >for >further copyright information. > Traceback (most recent call last): > File >"C:\PROGRA~1\Python23\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py", >line 307, in RunScript > debugger.run(codeObject, __main__.__dict__, start_stepping=0) > File >"C:\PROGRA~1\Python23\Lib\site-packages\pythonwin\pywin\debugger\__init__.py", >line 60, in run > _GetCurrentDebugger().run(cmd, globals,locals, start_stepping) > File >"C:\PROGRA~1\Python23\Lib\site-packages\pythonwin\pywin\debugger\debugger.py", >line 631, in run > exec cmd in globals, locals > File "C:\yakitome\test\examples\ex1.py", line 4, in ? > tts.Speak('Hello world.') > File "C:\PROGRA~1\Python23\Lib\site-packages\pyTTS\sapi.py", line 213, >in Speak > self.speech.Speak(text, flagsum) > File "C:\Program >Files\Python23\lib\site-packages\win32com\gen_py\C866CA3A-32F7-11D2-9602-00C04F8EE628x0x5x0.py", >line 2637, in Speak > , Flags) > com_error: (-2147352567, 'Exception occurred.', (0, None, None, None, >0, -2147201015), None) > >>> > >The system does not have a sound card --- could that be an issue? > >My head is about to explode trying to solve this problem, so your help and >suggestions will be much appreciated. > > > >-- >http://mail.python.org/mailman/listinfo/python-list _________________________________________________________________ Don?t miss your chance to WIN $10,000 and other great prizes from Microsoft Office Live http://clk.atdmt.com/MRT/go/aub0540003042mrt/direct/01/ From bruno.42.desthuilliers at wtf.websiteburo.oops.com Thu Jun 21 10:58:37 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Thu, 21 Jun 2007 16:58:37 +0200 Subject: PEP 3107 and stronger typing (note: probably a newbie question) In-Reply-To: References: <1182369568.941307.316260@p77g2000hsh.googlegroups.com> <5dveb4F360un0U1@mid.individual.net> Message-ID: <467a9209$0$22165$426a74cc@news.free.fr> Peter Decker a ?crit : (snip) > Oh, c'mon. The OP was asking for an explanation, and got an indignant > response. There is a world of difference between explaining *why* > Python is the way it is, and getting the equivalent of a 4-year-old's > "Because!" as a reply. Python is the way it is because the creator of the language decided to make it so. More seriously, wrt/the dynamic vs static typing religion war, any developer familiar with usenet should be able to find endless threads covering the topic, so I don't see any need for one more. > To someone who admits that he is largely unfamiliar with the language, > it would seem obvious that Python is "lacking" something that is > important in other languages. To someone who is only familiar with declarative static typing. One can be unfamiliar with Python but familiar with one (or more) of the many other dynamic languages around... > An explanation as to why this would be > Bad Thing for Python would be a helful response. Did you actually bother to read the full answer ? If so, you missed the explanation, so let's quote it: """ Given that one can add/replace/remove methods and attributes dynamically either on a per-class or per-instance basis, and even dynamically change the class of an object, I fail to see how static typechecking could be meaningfull. "" It seems obvious from this that static typecheking would require dropping all dynamism from Python - then turning it into another, very different (and mostly useless as far as I'm concerned) language. IOW : you can't have Python *and* static typechecks - both are mutually exclusive. Hence my answer : if you want static typecheking, you'll have to use another language - one way or another. From gagsl-py2 at yahoo.com.ar Tue Jun 26 21:17:42 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 26 Jun 2007 22:17:42 -0300 Subject: Python changing keywords name In-Reply-To: References: <1182630774.701295.50890@k79g2000hse.googlegroups.com> <1182651282.747106.239720@o61g2000hsh.googlegroups.com> Message-ID: En Tue, 26 Jun 2007 13:11:50 -0300, Sion Arrowsmith escribi?: > Gabriel Genellina wrote: >> (I hope nobody will abuse this technique... Y perd=F3n a los >> hispanoparlantes por lo horrible de la traducci=F3n). > > Ah, I only spotted this when I came to post a response. And the > reason I was going to post a response was that these: > >> 'assert': 'afirmar', >> 'exec': 'ejecutar', >> 'import': 'importar', >> 'pass': 'pasar', >> 'print': 'imprimir', >> 'raise': 'lanzar', >> 'return': 'retornar', >> 'try': 'intentar', >> 'yield': 'producir', > > look rather odd to this non-native Spanish speaker (or at least > reader), and I was going to ask if they sounded more idiomatically > correct if it's not your nth language. I guess they don't 8-) They are... ugly, yes. If I were to choose the names in Spanish, I'd use other words unrelated to the Python original keywords. For example, "pass" would become "nada" ("nothing") (why was chosen "pass" in the first place?) and "continue" would be "siguiente" ("next") and "break" would be "salir" ("go out","quit"). "except" is hard to translate, and even in English I don't see what is the intended meaning (is it a noun? a verb? an adverb? all look wrong). The pair "throw/catch" would be easier to use. And "with" would be "usando" ("using"). BTW, usage of "print" instead of "display" or "show" became obsolete 30 years ago or so... For a "real" Python translation, new versions with new keywords are a problem - what if "using" is added to the language and it conflicts with the translation of "with"? So... let's stay with the original keywords (english or dutglish or whatever they are...) -- Gabriel Genellina From scott.daniels at acm.org Sun Jun 24 22:57:16 2007 From: scott.daniels at acm.org (Scott David Daniels) Date: Sun, 24 Jun 2007 19:57:16 -0700 Subject: try/except with multiple files In-Reply-To: <1182458782.395214.45990@w5g2000hsg.googlegroups.com> References: <1182452425.793305.193370@u2g2000hsc.googlegroups.com> <1182458782.395214.45990@w5g2000hsg.googlegroups.com> Message-ID: <137ubn3fdlfam0d@corp.supernews.com> bruno.desthuilliers at gmail.com wrote: > On Jun 21, 9:00 pm, Robert Hicks wrote: >> Is it good practice to do something like: >> >> try: >> f1 = file('file1') >> f2 = file('file2') >> except: >> # catch the exception > > If what you want is to make sure that resources will be released, you > can use a try/finally block or (Python 2.5) a with block. You could do something like this: files = [] try: for name in ['abc.txt', 'def.txt', 'ghi.txt']: files.append(open(name)) a, b, c = files finally: while files: files.pop().close() --Scott David Daniels scott.daniels at acm.org From timr at probo.com Mon Jun 11 02:39:52 2007 From: timr at probo.com (Tim Roberts) Date: Mon, 11 Jun 2007 06:39:52 GMT Subject: read 9 bytes References: <1181533948.427220.14650@j4g2000prf.googlegroups.com> Message-ID: nik wrote: > >I need to read a 9 byte response from a device on the serial port. >From reading the pySerial documentation it appears that I can only >read in characters at a time. Yes, but it is 8-bit characters. That is, characters == bytes in this instance. >If I do: serialport.read(4) >I would get 8 bytes, No. You would get 4 bytes. Do you see documentation to the contrary? -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From __peter__ at web.de Sun Jun 17 08:09:33 2007 From: __peter__ at web.de (Peter Otten) Date: Sun, 17 Jun 2007 14:09:33 +0200 Subject: sqlite3 bug?? References: <46752230$0$31685$db0fefd9@news.zen.co.uk> Message-ID: mark carter wrote: > I hesitate to ask, but ... Don't :-) > I'm using Ubuntu Feisty: > * Python 2.5.1 (r251:54863, May 2 2007, 16:56:35) > [GCC 4.1.2 (Ubuntu 4.1.2-0ubuntu4)] on linux2 > * SQLite version 3.3.13 > > Suppose I run the following program: > import sqlite3 > > conn = sqlite3.connect('example') > > > c = conn.cursor() > > # Create table > c.execute('''create table stocks > (date text, trans text, symbol text, > qty real, price real)''') > > # Insert a row of data > c.execute("""insert into stocks > values ('2006-01-05','BUY','RHAT',100,35.14)""") > > and then I go into sqlite: > % sqlite3 example > sqlite3> select * from stocks ; > > It returns 0 rows. I'm in the right directory. I have experienced this > problem with some other sqlite3 database work I have done with python, > so I'm figuring there is something fishy going on. I've tried doing > similar exercises with Ruby, and they have worked OK. > > Anyone else getting these problems? How about conn.commit()? Peter From steve at holdenweb.com Thu Jun 28 20:59:00 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 28 Jun 2007 20:59:00 -0400 Subject: Python's "only one way to do it" philosophy isn't good? In-Reply-To: <5N0C7KBirhgGFwUp@woodrowhorsfall.plus.com> References: <7x3b0nmkk6.fsf@ruckus.brouhaha.com> <1182750077.570603.160240@q69g2000hsb.googlegroups.com> <7xir9cbm0g.fsf@ruckus.brouhaha.com> <7xejjzmk7u.fsf@ruckus.brouhaha.com> <7xy7i7xjl5.fsf@ruckus.brouhaha.com> <5N0C7KBirhgGFwUp@woodrowhorsfall.plus.com> Message-ID: Douglas Woodrow wrote: > On Wed, 27 Jun 2007 01:45:44, Douglas Alan wrote >> A chaque son gout > > I apologise for this irrelevant interruption to the conversation, but > this isn't the first time you've written that. > > The word "chaque" is not a pronoun. > > http://grammaire.reverso.net/index_alpha/Fiches/Fiche220.htm Right, he probably means "Chaqu'un ? son gout" (roughly, each to his own taste). regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From bruno.42.desthuilliers at wtf.websiteburo.oops.com Thu Jun 21 03:22:34 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Thu, 21 Jun 2007 09:22:34 +0200 Subject: Help With Better Design In-Reply-To: <1182367303.089441.265180@i13g2000prf.googlegroups.com> References: <1182303267.427179.223720@i13g2000prf.googlegroups.com> <467919ca$0$28811$426a74cc@news.free.fr> <1182367303.089441.265180@i13g2000prf.googlegroups.com> Message-ID: <467a2729$0$23935$426a74cc@news.free.fr> apollonius2 at gmail.com a ?crit : (snip) >>> I would like to be able to get a good hold of the concept >> state machines ? > > Well both state machines and classes (objects). That may be a bit of a > tall order to take on all at once but the concepts seem to be quite > related. They are, since OO was born from the use of state machines for simulation (the Simula language). But you can do state machines with a database and a procedural language too, and FWIW, the "state machine" aspect of OO is more often very informal and ad hoc. > I already have a great deal of material on Classes so good to > go there. Don't confuse "classes" with OO. The "OO" in OOP means "object-oriented", not class-oriented, and nothing in the most basics definitions of OO [1] requires nor even imply the notion of "class". This notion is mostly an artifact for easing the definition of a family of objects having similar implementation, and some 00 languages managed to get by without classes (look for "prototype-based languages" - the most known being javascript). wrt/ Python, classes are actually objects too, and instances have a reference to their class. Since one can dynamically modify the instance object -> class object relation at runtime, we're quite close to prototype-based languages !-) [1] "an object is defined by an identity, a state and a behaviour." From josiah.carlson at sbcglobal.net Mon Jun 25 11:05:51 2007 From: josiah.carlson at sbcglobal.net (Josiah Carlson) Date: Mon, 25 Jun 2007 08:05:51 -0700 Subject: Chroot Jail Not Secure for Sandboxing Python? In-Reply-To: <1182782910.811850.284350@u2g2000hsc.googlegroups.com> References: <1182748892.916068.146780@p77g2000hsh.googlegroups.com> <467f55f7$0$20850$9b622d9e@news.freenet.de> <1182782910.811850.284350@u2g2000hsc.googlegroups.com> Message-ID: gregpinero at gmail.com wrote: > On Jun 25, 1:43 am, "Martin v. L?wis" wrote: >> gregpin... at gmail.com schrieb: >> >>> This wiki page suggests using a chroot jail to sandbox Python, but >>> wouldn't running something like this in your sandboxed Python instance >>> still break you out of the chroot jail: >>> os.execle ('/usr/bin/python','-c','import os; os.execlp("/bin/sh")', >>> {}) >> Depending on how the chroot jail is set up, this command might not >> work - in the jail, /bin/sh might not exist. > > I followed up with my ISP. Here's the answer I got: > > The os.exec call prepends the chroot directory to the absolute path, > but does NOT provide chroot for the child process. However, as long > as the environment is maintained, which contains an LD_PRELOAD, the > "chroot" will also be maintained. If LD_PRELOAD is removed or > ignored, then the chroot is ineffective. > > Another way of saying it is that every process is responsible for > providing and maintaining the chroot through the LD_PRELOAD variable. > Those processes only maintain the chroot if that variable remains set. > > The only solution that would bypass this problem altogether would be a > statically linked python. (is that possible?) It would have to be > statically linked to a custom-modified glibc to provide the virtual > chroot environment. It seems to me that if a (potentially malicious) process needs to behave itself in order for chroot to not allow the process access to the full system, then chroot is broken. But perhaps I don't understand the intent and scale of what chroot intends to do. - Josiah From kyosohma at gmail.com Mon Jun 25 11:10:31 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Mon, 25 Jun 2007 08:10:31 -0700 Subject: How to save initial configuration? (program installation) In-Reply-To: <1182783746.718276.209460@w5g2000hsg.googlegroups.com> References: <1182783746.718276.209460@w5g2000hsg.googlegroups.com> Message-ID: <1182784231.530101.258640@q75g2000hsh.googlegroups.com> On Jun 25, 10:02 am, Jason Zapman II wrote: > I've written a program. To install this program, I'm going to need to > initialize some stuff for the users environment, specifically the name/ > location of an internal state file. > > Currently, I'm hard coding the location of this file, but that's in- > elegant. What I'd like to do is just ask the user, with a suggested > default. > > My question is how do I save this answer? It's kind of a chicken-and- > egg problem. > > The only solution I've thought of is to write something that's self > modifying, but that's ugly (go in, grep for this variable > initialization, re-write that line with the new value, quit). Is > there a better way to do this? There almost has to be... > > If not, are there some 'best practices' on how to do the self- > modification? > > Thanks for any help; > Jason I would think you could pop-up some dialog when the program is first run to ask where they want the file to be. On the first run though, you can just have the config file located in the current working directory with the script file itself. Then just move it or save a new copy to the new location and delete the original. Mike From martin at v.loewis.de Sat Jun 23 14:31:01 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sat, 23 Jun 2007 20:31:01 +0200 Subject: C API: passing by reference In-Reply-To: <1182623135.952521.174410@w5g2000hsg.googlegroups.com> References: <1182623135.952521.174410@w5g2000hsg.googlegroups.com> Message-ID: <467d66e5$0$2795$9b622d9e@news.freenet.de> stuart.tett at gmail.com schrieb: > I'm writing my own python extension module with the C API. In python > all functions pass arguments by reference Can you please show an example what you mean by that? There is no "pass-by-reference" in Python: a function can not normally modify the variable in the caller. When you show what precisely you want to achieve, it should be easy to say how to do that in C. Regards, Martin From urbangabo at gmail.com Thu Jun 21 02:57:44 2007 From: urbangabo at gmail.com (Gabor Urban) Date: Thu, 21 Jun 2007 08:57:44 +0200 Subject: Emacs topic Message-ID: Hi guys, I kindly ask you to stop this topic. Though I see the importance to have a good editor for programming, this is outside of the focus of a Python mailing list. The open source world offers a lot of very good tools to edit source files, even for cross-platform development. Emacs is one of them, and IMHO could be set as an efficiency/proficiency standard. But if it does not fit to your fingers or working style, do not use it. I am open to personal debate outside of this list, Gabor -------------- next part -------------- An HTML attachment was scrubbed... URL: From warren at muse.com Sat Jun 2 14:25:04 2007 From: warren at muse.com (Warren Stringer) Date: Sat, 2 Jun 2007 11:25:04 -0700 Subject: c[:]() In-Reply-To: <6faf39c90706012146l551dfe60o6358f48dd5127505@mail.gmail.com> References: <1180504190.055427.173610@h2g2000hsg.googlegroups.com> <135tv1bjqgbmsc9@corp.supernews.com> <9qudnbFRU9QHJsLbnZ2dnUVZ_rKvnZ2d@speakeasy.net> <005f01c7a471$6f4b8b30$240110ac@Muse> <6faf39c90706012146l551dfe60o6358f48dd5127505@mail.gmail.com> Message-ID: <003701c7a543$57b09290$240110ac@Muse> Andre Engels wrote: > > I am not insisting on anything. I use ``c[:]()`` as shorthand way of > saying > > "c() for c in d where d is a container" > > > > Having c() support containers seems obvious to me. It jibes with duck > > typing. Perhaps the title of this thread should have been: "Why don't > > containers quack?" > > > > A change is surprising only if it breaks something. I still haven't seen > any > > code that breaks by making such a change. Seeing such code would teach a > > great deal. > > I think it very much bites duck typing. Currently, if I try to execute > a string or a list or whatever, I get: > > TypeError: 'str' object is not callable > > But under your proposed semantics, suppose a is a list with some > executable and some non-executable elements. What should > > a() > > now give? It cannot be a TypeError, because a list (in your semantics) > is callable. Whatever error it gives, and whether or not the preceding > executables are executed first, it will not be an existing error > acting the way it normally does ... Since `a()` translates to `a() for a in b` then the error would be the exact same `TypeError: 'str' object is not callable` > - there is no Python error for "you > cannot do this with this object, but you can do it with other objects > of the same type". Yes there is: #------------------------ def yo(): print "yo" def no(): print blah yo() no() Starting Python debug run ... yo Traceback (most recent call last):... NameError: global name 'blah' is not defined #------------------------ > And that does not seem to be a case of "We have > never needed it yet" - the join method seems to have been specifically > tailored so that no such error is needed. The join example is pretty cool - I want to study it a bit more - maybe I'm missing your point? There are two domain discussions, here: 1) is c[:]() is a good idea for python 2) is c[:]() a good idea in general Where c[:]() symbolizes [c() for c in a] In my opinion: 1a) might break something in Python 2.x - 1b) may or may not be a good idea for Python 3K 2a) is a great idea for a specific range of applications 2b) should attempt to coincide with existing idioms Pragmatically speaking: I'm not interested in 1a because it may break something. There may be an edge case where catching a `TypeError: 'str' object is not callable` may change the behavior of existing code. I am somewhat interested in 1b but intend to lurk on the python.ideas and python3k lists before entering a discussion. I tend to shy away from proposing changes from ignorance. This is QUITE DIFFERENT from asking WHY something works a certain way. Consider people who ask dumb questions, like me, to be an opportunity to discover what isn't obvious. I am intensely interested in 2a. Specifically visual music performances over the web. I have spent 7 full years and my life's savings on developing a platform. This particular application will involve millions of simultaneous events that get passed around as objects. Two of those years have been spent on developing a domain specific language that needs a very fast `c[:]()` -- which relates to 1b. I am very interested in 2b. The two most inspiring languages to me are Python and Occam (a now defunct language Transputers) Both use lexical indentation. Although I am building a domain specific language I want make it seamlessly integrate with Python. So that a 12-year-old may start by patching performances, but ultimately, she may become inspired in writing python script. So, this thread has been of keen interest to me, mostly because of 2b. 1b is of interest because extending Python with C has historically required separate distributions between various versions of 2.x So, Andre, you and others have a point, in regards to 1a. I find your post particularly interesting, because it points out some history with join, which helps me better understand how to approach 2b. It wasn't my intent to ruffle feathers, but that in its own regard is instructive, both in the topic, at hand, and in regard to the Python community. Meanwhile, I have written very little code, in the last couple days. It means that I've taken everyone's suggestions very seriously, often leading me to blogs and blogs of blogs. Looking back, there have been a couple of helpful suggestions that I didn't respond to directly. So, for them, my apologies and thanks! For now, I am out of here! Cheers, \~/ From DustanGroups at gmail.com Sat Jun 16 20:28:31 2007 From: DustanGroups at gmail.com (Dustan) Date: Sun, 17 Jun 2007 00:28:31 -0000 Subject: a_list.count(a_callable) ? In-Reply-To: <1182026221.039617.56320@n2g2000hse.googlegroups.com> References: <1181850818.567840.251090@x35g2000prf.googlegroups.com> <1181853479.914070.217270@i13g2000prf.googlegroups.com> <1181855184.511137.100870@z28g2000prd.googlegroups.com> <1181916937.648267.163070@z28g2000prd.googlegroups.com> <1181981527.960296.135820@i13g2000prf.googlegroups.com> <1182026221.039617.56320@n2g2000hse.googlegroups.com> Message-ID: <1182040111.087082.222160@k79g2000hse.googlegroups.com> On Jun 16, 3:37 pm, Dustan wrote: > class SmartCountingList(list): > def count(self, item, func=lambda x: x): > return sum(1 for i in self if func(item)==item) > > Then, you would call it as follows: > a_list.count(True, a_function) I need to learn to think things through before hitting the send button (or test my examples); none of the mistakes I've made on this thread have been from ignorance. If a_function returns a true value other than True or the number 1 (which are technically the same), it is not 'equal' to True. Either the function would return True, or the count method could be written differently: class SmartCountingList(list): def count(self, item, is_func=False): if is_func: # item being a function: return sum(1 for i in self if item(i)) else: return super(SmartCountingList, self).count(item) And just to prove that it works: >>> s = SmartCountingList((1,2,3)) >>> s [1, 2, 3] >>> s.count(1) 1 >>> s.count(2) 1 >>> s.count(3) 1 >>> s.count(4) 0 >>> s.count(lambda n: n<3, True) 2 From borud-news at borud.no Sat Jun 23 10:45:53 2007 From: borud-news at borud.no (Bjorn Borud) Date: 23 Jun 2007 16:45:53 +0200 Subject: The Modernization of Emacs: terminology buffer and keybinding References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182272495.990807.99110@a26g2000pre.googlegroups.com> <87tzt3ihev.fsf@kobe.laptop> <1182370216.961241.6960@n60g2000hse.googlegroups.com> <85zm2ufjpb.fsf@lola.goethe.zz> <1182372592.803332.288260@u2g2000hsc.googlegroups.com> <1182373919.262388.100740@c77g2000hse.googlegroups.com> <85r6o6fhkb.fsf@lola.goethe.zz> <1182375045.626510.188170@m36g2000hse.googlegroups.com> <85myyufgwj.fsf@lola.goethe.zz> <1182375528.985142.293900@q69g2000hsb.googlegroups.com> <1182545268.055596.228700@i38g2000prf.googlegroups.com> Message-ID: [Twisted ] | You end up having to memorize the help, because *you can't | have arbitrary parts of the help and your document open side by side | and be working on the document*. All because you can't simply tab or | click to the document. yes you can. you even have a lot of choice as to how you want to do it and it even works on the simplest of text terminals (which is useful when you are on the road and only have a computer with a browser availabe and you've had the foresight to set up the Mindterm SSH applet on a machine so you can log in and edit code from anywhere in the world). I use multiple frames on-screen most of the time. either to edit and view multiple files at once or to edit different locations of the same file. if you're a programmer it is often useful to be able to do this. you can look at more than one file at the same time, have documentation up on screen etc. | At minimum, you have to *memorize* some arcane key controls for | switching panes ... er, "windows", that are totally unintuitive and | unlike what is normally used. following the built-in tutorial in Emacs I understood how to manipulate buffers and split windows in various ways. there are basically three commands you need to know. one of them is used to switch between active buffers in a given window, so it is not specific to splitting. it took me minutes to learn and within days I didn't even think about what I was doing -- I was just using the features. I think you fail to understand the approach. if you know an editor like VI or Emacs properly you have a much bigger bag of tricks, that are applicable to a wide range of scenarios, than what is encouraged by GUI intensive editors. and you don't think of them as "tricks". it is just the way you edit text. | Oops. The interface design is a nightmare. The most basic requirement, | that it be easy to have the help open side by side with your document | and switch back and forth and navigate inside the help easily, is | broken. If you have to consult the help just to navigate the help or | to switch focus between document and help, then you're trapped, and | that is what happens with emacs. why don't you learn Emacs before you say what it can and can't do? it is so frustrating to debate editors with people who haven't even bothered to make a minimal effort to at least spend a day or two learning it. let's look at Word and word processing. how long does it take you to learn Word properly? to understand how to efficiently edit large documents, automate common tasks, use the built-in features for helping you organize documents? -Bj?rn From tim at tdw.net Mon Jun 18 13:17:40 2007 From: tim at tdw.net (Tim Williams) Date: Mon, 18 Jun 2007 18:17:40 +0100 Subject: avoid script running twice In-Reply-To: References: <4676AB35.7060500@chamonix.reportlab.co.uk> Message-ID: <9afea2ac0706181017n102c8a82xd93c0c6e819942dc@mail.gmail.com> On 18/06/07, Evan Klitzke wrote: > On 6/18/07, Robin Becker wrote: > > I wish to prevent a python script from running twice; it's an hourly job, but > > can take too long. > > > > My simplistic script looks like > > > > > > ....... > > def main(): > > fn = 'MARKER' > > if os.path.isfile(fn): > > log('%s: hourly job running already' % formatTime()) > > else: > > f = open(fn,'w') > > f.write(str(os.getpid())) > > f.close() > > try: > > work() > > finally: > > os.remove(fn) > > > > if __name__=='__main__': > > main() > > > > but it occurs to me that I might be killed with prejudice during the long > > running work(). Is there a smart way to avoid running simultaneously. > > Another method that you can use is to open up a socket on some > predetermined port (presumably above 1024), and then have your program > try to connect to that port and "talk" to the other program to > determine whether or not to run (or whether to do some of the > remaining work, etc.). You don't need to talk to the socket, a second script trying to create a second socket on the same number will throw an exception and you can exit the script cleanly without running a second copy. You can also do this by holding a file open in write mode until the script has finished. try: open('lock.txt','w') my_script() except: #print script is already running If the file is already open the script won't run, if the script finshes/crashes or the machine reboots the open file will close. In both cases if the script finishes normally or crashes, or the machine is restarted. The lock (ie socket or open file) is released. HTH :) -- Tim Williams From horpner at yahoo.com Wed Jun 6 13:13:35 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Wed, 06 Jun 2007 17:13:35 GMT Subject: lists - append - unique and sorted References: <1181143597.563633.241640@o5g2000hsb.googlegroups.com> Message-ID: On 2007-06-06, Josiah Carlson wrote: > Neil Cerutti wrote: >> On 2007-06-06, rhXX wrote: >>> and/or >>> >>> - SORTED - INSERT in the correct place using some criteria? >> >> Consult the Python Docs about the heapq module. > > Heaps (as produced by heapq) are not sorted. This will not > produce correct results unless one then pops everything and > de-dupes the output. i agree that using bisect and inserting manually clearly meets the stated requirements, while there isn't enough information to know if a heapq will meet his requirements. Thanks for the correction. -- Neil Cerutti In my prime I could have handled Michael Jordan. Of course, he would be only 12 years old. --Jerry Sloan From notbob at nothome.com Tue Jun 26 21:12:00 2007 From: notbob at nothome.com (notbob) Date: Tue, 26 Jun 2007 20:12:00 -0500 Subject: The Modernization of Emacs: terminology buffer and keybinding References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182272495.990807.99110@a26g2000pre.googlegroups.com> <87tzt3ihev.fsf@kobe.laptop> <1182370216.961241.6960@n60g2000hse.googlegroups.com> <85zm2ufjpb.fsf@lola.goethe.zz> <1182372592.803332.288260@u2g2000hsc.googlegroups.com> <1182549094.366282.286740@m37g2000prh.googlegroups.com> <877iprhos9.fsf@kobe.laptop> <1182843872.488493.153700@m36g2000hse.googlegroups.com> <87myync95b.fsf@mail.eng.it> <1182905443.074236.128290@w5g2000hsg.googlegroups.com> Message-ID: On 2007-06-27, Twisted wrote: > irritating was the necessary frequent trips to the help. Even when the > help was easy to use (itself rare) that's a load of additional task > switching and crap. Of course, lots of the time the help was not easy > to use. Man pages and anything else viewed on a console, for example On the plus side, you only have to learn it once. With new releases of Windows/Office, more often than not, Bill n' The Boys rename functions and hide them somewhere else in an attempt to make it look like they actually did something, so you end up wasting a lot of time relearning what you already knew. Talk about irritating! nb From peter.mosley at talk21.com Tue Jun 19 05:43:09 2007 From: peter.mosley at talk21.com (peter) Date: Tue, 19 Jun 2007 02:43:09 -0700 Subject: Python and (n)curses In-Reply-To: <87y7igzapo.fsf@benfinney.id.au> References: <1182211133.956524.160020@g4g2000hsf.googlegroups.com> <87y7igzapo.fsf@benfinney.id.au> Message-ID: <1182246189.210723.16280@w5g2000hsg.googlegroups.com> I've said it before and I'll say it again. Why does Python have no platform neutral commands for simple screen manipulation? yabasic (a 'hobby' type language - http://www.yabasic.de/) has commands clear screen, inkey$ and putscreen$ which perform the basic functions of clearing the screen, reading a key press and printing a string at an arbitrary xy position in either Windows or Linux, leaving all the messy implementation away from the user. For me, introducing similar commands in Python would be by far the biggest single improvement that could be made to the language. Yes, I know the argument that it's up to me to contribute such a module. But I'm afraid my knowledge and skill are way below the threshold needed for such work. Which is why I need it as an addition to the core language! Peter From http Thu Jun 28 01:02:30 2007 From: http (Paul Rubin) Date: 27 Jun 2007 22:02:30 -0700 Subject: 16bit hash References: <46833DC0.3050503@v.loewis.de> Message-ID: <7xk5toy8m1.fsf@ruckus.brouhaha.com> "Martin v. L?wis" writes: > So: what are your input data, and what is the > distribution among them? With good enough hash functions one shouldn't need to care about the input distribution. Basically functions like SHA can be used as extractors: http://en.wikipedia.org/wiki/Extractor If there's a concern that the input distribution is specially concocted to give nonuniform results with some known hash function, then use one unknown to the input provider, e.g. import hmac def hash(obj, key='some string unknown to the input source'): return int(hmac.HMAC(key,repr(obj)).hexdigest()[:4], 16) Anyway I don't have the impression that the OP is concerned with this type of issue. Otherwise s/he'd want much longer hashes than 16 bits. From aleax at mac.com Wed Jun 27 11:39:57 2007 From: aleax at mac.com (Alex Martelli) Date: Wed, 27 Jun 2007 08:39:57 -0700 Subject: equality & comparison by default (was Re: Too many 'self' in python.That's a big flaw in this language.) References: <1182942154.185461.89620@e9g2000prf.googlegroups.com> Message-ID: <1i0cy8z.z94q5d1dxgexxN%aleax@mac.com> A.T.Hofkamp wrote: > I think that again now with the default implementation of the > object.__eq__ and object.__hash__ methods. I believe these methods should > not exist until the programmer explicitly defines them with a suitable > notion of equivalence. > > Anybody have a good argument against that? :-) It's very common and practical (though not ideologically pure!) to want each instance of a class to "stand for itself", be equal only to itself: this lets me place instances in a set, etc, without fuss. I don't want, in order to get that often-useful behavior, to have to code a lot of boilerplate such as def __hash__(self): return hash(id(self)) and the like -- so, I like the fact that object does it for me. I'd have no objection if there were two "variants" of object (object itself and politically_correct_object), inheriting from each other either way 'round, one of which kept the current practical approach while the other made __hash__ and comparisons abstract. In Python 3000, ordering comparisons will not exist by default (sigh, a modest loss of practicality on the altar of purity -- ah well, saw it coming, ever since complex numbers lost ordering comparisons), but equality and hashing should remain just like now (yay!). Alex From esj at harvee.org Sun Jun 10 12:29:31 2007 From: esj at harvee.org (Eric S. Johansson) Date: Sun, 10 Jun 2007 12:29:31 -0400 Subject: Python in the Mozilla world In-Reply-To: <97241.77728.qm@web33511.mail.mud.yahoo.com> References: <97241.77728.qm@web33511.mail.mud.yahoo.com> Message-ID: Steve Howell wrote: > --- "Eric S. Johansson" wrote: > http://www.voidspace.org.uk/python/weblog/arch_d7_2007_04_28.shtml#e702 >> interesting. Very interesting but I suspect the >> message is "don't hold your >> breath but don't give up hope." >> > > Exactly. :) This is one of those things where a foundation, with a smart person for making really simple things should get some money from the foundation and get it built. I don't know about you but when I have a customer asking for a modification to an open source project, I respond much more quickly when they say "here's your budget". Although sometimes the budget is so small, I'm tempted to find someone in Romania or other cheap locations and stretch my dollar as far as possible. I'm certainly tempted to do that on my own projects. > Well, that sounds pretty reasonable, and I'm sure a > lot of folks are in a similar quandary. They need to > use JS to a certain degree, but nobody wants to make a > career out of plug-in writing, etc. (I certainly > don't!) It wouldn't surprise me that there are lots of > Python programmers who do JS maybe 5% of the time, and > many of those folks can't justify the effort to go a > bit deeper on the learning curve, create more of a > community, etc. > > I guess I'm not helping you much other than to > commiserate, but can I ask you to what extent you've > looked into existing Python web frameworks, to see how > much code there is out there that you could mine for > your projects? I stumbled on some pretty high quality > Python code a few weeks ago that amounted to > Javascript helpers, but now I can't find it for the > life of me. But it's out there... actually, I've looked at some toolkits and they look really nice if I had a week to spend on them. I'm trying to figure out how to fit something like these toolkits into my own framework (yes, another web framework. This time, with accessibility in mind. The motto is, learn in the morning, use in the afternoon, go home at night.) But figuring out how to fit in Ajax type stuff in the same way that the HTML has been simplified for 80% of the uses, requires a deeper knowledge of Ajax than I have. And I'm unlikely to acquire in the near term unless I have a partner in crime to show me common idioms. which is a pity because I have in mind a tool which could help writers for online comments. Most of the current common techniques involve comments to a log entry or in some cases inter-line comments but the primary failing of these models is the ability to highlight just what the comment is about. The user interface would be fairly simple. Highlight the region and a text area appears below. You enter text and hit submit or you can cancel. A marker is left in the margins indicating the presence of a comment when you hit the marker, the text becomes visible again and the highlighted region becomes visible again. There are other refinements but that's fundamentally it. I'll probably be motivated to jump into the JavaScript necessary after I finish and publish to other projects in Python. From fredrik at pythonware.com Fri Jun 15 02:56:52 2007 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 15 Jun 2007 08:56:52 +0200 Subject: Failing on string exceptions in 2.4 In-Reply-To: <20070614214506.GA27937@slaniel-laptop.itasoftware.com> References: <20070614214506.GA27937@slaniel-laptop.itasoftware.com> Message-ID: Stephen R Laniel wrote: > End goal being that string exceptions would cause > compilation to fail. A few times now, I've found myself > doing > > class SomeClass: > """docstring""" > pass > > raise SomeClass, "Some description" > > and I've gotten a weird compiler error about the constructor > for SomeClass. weird as in TypeError: this constructor takes no arguments ? this has nothing to do with string exceptions (using string objects as exception objects), and all to do with the fact that raise SomeClass, "Some description" is equivalent to raise SomeClass("Some description") which of course doesn't work if your class constructor isn't accepting any arguments. this is no different from doing: class SomeClass: pass obj = SomeClass("an argument") # fails with a TypeError (note that it's the runtime that's complaining, not the compiler) to fix this, just make sure that your exception class takes an argument (the exception value), either by adding an __init__ method, or by inheriting from a suitable built-in exception class. From nagle at animats.com Fri Jun 29 15:00:30 2007 From: nagle at animats.com (John Nagle) Date: Fri, 29 Jun 2007 19:00:30 GMT Subject: Rappresenting infinite In-Reply-To: References: <1182940919.351011.267020@n2g2000hse.googlegroups.com> <1182945569.081290.40870@c77g2000hse.googlegroups.com> <20070628234618.2907b52d@localhost> <20070629004542.31bbc7ac@localhost> Message-ID: Robert Kern wrote: > mmanns at gmx.net wrote: > >>On Thu, 28 Jun 2007 23:20:30 -0500 >>Robert Kern wrote: >> >> >>>mmanns at gmx.net wrote: >>> >>>>Does it differ from the >>>>built-in inf? >>> >>>What built-in inf? >> >>$ python >>Python 2.4.4 (#2, Apr 5 2007, 20:11:18) >>[GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-21)] on linux2 >>Type "help", "copyright", "credits" or "license" for more information. >> >>>>>a = 1.0e1000 >>>>>b = 2.0e1000 >>>>>a >> >>inf >> >>>>>b >> >>inf >> >>>>>a == b >> >>True >> >>>>>type(a) >> >> > > > Okay, I thought you meant that there was an actual symbol 'inf' in the builtins > or in a module somewhere. > > >>>No. You can make one that fits your requirements, though. That sounds like a bug. If Python numerics don't define +INF, -INF, and NaN, along with the tests for them, that's a flaw in the language. We can assume IEEE floating point at this late date; it's been standard for twenty years and Java assumes it. John Nagle From squabbit7 at gmail.com Thu Jun 28 20:17:31 2007 From: squabbit7 at gmail.com (Seltzer) Date: Thu, 28 Jun 2007 18:17:31 -0600 Subject: process stdin grab In-Reply-To: <20070628210701.GP30401@lass.lfod.us> References: <6151cc730706281301y255e2cefo8d3e2a1f191ee5a0@mail.gmail.com> <20070628210701.GP30401@lass.lfod.us> Message-ID: <6151cc730706281717g7b4b785bhc6affbbf56b709a0@mail.gmail.com> thanks for the suggestions. I'm not able to modify the mplayer command... and they do not create a fifo and yes, i meant 'pid', sorry. -felix On 6/28/07, Will Maier wrote: > > On Thu, Jun 28, 2007 at 08:01:18PM +0000, Seltzer wrote: > > I need to send commands to a process that i did not start. > > (mplayer specifically) I have the PIP of the process, and thats > > about all. > > I assume you mean 'PID'. This is somewhat offtopic, but mplayer > supports receiving commands from a FIFO: > > mplayer -quiet -slave -idle -input file=/home/you/.mplayer/fifo > > Then you can write commands (like 'loadfile song.ogg') to the fifo. > Doing this in Python is as trivial as opening, writing to, and > closing a file object. > > > Any ideas on how to do this in python? i need only to write to its > > stdin, not read any information from it, and i don't really need > > to know if my command worked for now, so error handling isn't > > really an issue. > > I don't know of any magic to write to a running program's stdin. > > -- > > [Will Maier]-----------------[willmaier at ml1.net|http://www.lfod.us/] > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From bruno.desthuilliers at gmail.com Thu Jun 21 16:46:22 2007 From: bruno.desthuilliers at gmail.com (bruno.desthuilliers at gmail.com) Date: Thu, 21 Jun 2007 20:46:22 -0000 Subject: try/except with multiple files In-Reply-To: <1182452425.793305.193370@u2g2000hsc.googlegroups.com> References: <1182452425.793305.193370@u2g2000hsc.googlegroups.com> Message-ID: <1182458782.395214.45990@w5g2000hsg.googlegroups.com> On Jun 21, 9:00 pm, Robert Hicks wrote: > Is it good practice to do something like: > > try: > f1 = file('file1') > f2 = file('file2') > except: > # catch the exception It's bad practice. Because you use a bare except clause, and don't do anything useful with the exceptions you catch. > Or do you do a try/except for each open? If what you want is to make sure that resources will be released, you can use a try/finally block or (Python 2.5) a with block. From doug at alum.mit.edu Wed Jun 27 23:37:18 2007 From: doug at alum.mit.edu (Douglas Alan) Date: Wed, 27 Jun 2007 23:37:18 -0400 Subject: Python's "only one way to do it" philosophy isn't good? References: <7xir9cbm0g.fsf@ruckus.brouhaha.com> <7xejjzmk7u.fsf@ruckus.brouhaha.com> <7xy7i7xjl5.fsf@ruckus.brouhaha.com> Message-ID: "Chris Mellon" writes: > On 6/27/07, Douglas Alan wrote: >> The C++ folks feel so strongly about this, that they refuse to provide >> "finally", and insist instead that you use destructors and RAII to do >> resource deallocation. Personally, I think that's taking things a bit >> too far, but I'd rather it be that way than lose the usefulness of >> destructors and have to use "when" or "finally" to explicitly >> deallocate resources. > This totally misrepresents the case. The with statement and the > context manager is a superset of the RAII functionality. No, it isn't. C++ allows you to define smart pointers (one of many RAII techniques), which can use refcounting or other tracking techniques. Refcounting smart pointers are part of Boost and have made it into TR1, which means they're on track to be included in the next standard library. One need not have waited for Boost, as they can be implemented in about a page of code. The standard library also has auto_ptr, which is a different sort of smart pointer, which allows for somewhat fancier RAII than scope-based. > It doesn't overload object lifetimes, rather it makes the intent > (code execution upon entrance and exit of a block) explicit. But I don't typically wish for this sort of intent to be made explicit. TMI! I used "with" for *many* years in Lisp, since this is how non-memory resource deallocation has been dealt with in Lisp since the dawn of time. I can tell you from many years of experience that relying on Python's refcounter is superior. Shouldn't you be happy that there's something I like more about Python than Lisp? > Nobody in their right mind has ever tried to get rid of explicit > resource management - explicit resource management is exactly what you > do every time you create an object, or you use RAII, or you open a > file. This just isn't true. For many years I have not had to explicitly close files in Python. Nor have I had to do so in C++. They have been closed for me implicitly. "With" is not implicit -- or at least not nearly as implicit as was previous practice in Python, or as is current practice in C++. > *Manual* memory management, where the tracking of references and > scopes is placed upon the programmer, is what people are trying to > get rid of and the with statement contributes to that goal, it > doesn't detract from it. As far as I am concerned, memory is just one resource amongst many, and the programmer's life should be made easier in dealing with all such resources. > Before the with statement, you could do the same thing but you > needed nested try/finally blocks No, you didn't -- you could just encapsulate the resource acquisition into an object and allow the destructor to deallocate the resource. > RAII is a good technique, but don't get caught up on the > implementation details. I'm not -- I'm caught up in the loss of power and elegance that will be caused by deprecating the use of destructors for resource deallocation. > The with statement does exactly the same thing, but is actually > superior because > > a) It doesn't tie the resource managment to object creation. This > means you can use, for example, with lock: instead of the C++ style > Locker(lock) I know all about "with". As I mentioned above, Lisp has had it since the dawn of time. And I have nothing against it, since it is at times quite useful. I'm just dismayed at the idea of deprecating reliance on destructors in favor of "with" for the majority of cases when the destructor usage works well and is more elegant. > b) You can tell whether you exited with an exception, and what that > exception is, so you can take different actions based on error > conditions vs expected exit. This is a significant benefit, it > allows the application of context managers to cases where RAII is > weak. For example, controlling transactions. Yes, for the case where you might want to do fancy handling of exceptions raised during resource deallocation, then "when" is superior, which is why it is good to have in addition to the traditional Python mechanism, not as a replacement for it. >> Right, but that doesn't mean that 99.9% of the time, the programmer >> can't immediately tell that cycles aren't going to be an issue. > They can occur in the most bizarre and unexpected places. To the point > where I suspect that the reality is simply that you never noticed your > cycles, not that they didn't exist. Purify tells me that I know more about the behavior of my code than you do: I've *never* had any memory leaks in large C++ programs that used refcounted smart pointers that were caused by cycles in my data structures that I didn't know about. > And if you think you won't need it because python will get "real" GC > you're very confused about what GC does and how. Ummm, I know all about real GC, and I'm quite aware than Python has had it for quite some time now. (Though the implementation is rather different last I checked than it would be for a language that didn't also have refcounted GC.) > A generic threadsafe smart pointer, in fact, is very nearly a GIL. And how's that? I should think that modern architectures would have an efficient way of adding and subtracting from an int atomically. If they don't, I have a hard time seeing how *any* multi-threaded applications are going to be able to make good use of multiple processors. > Get cracking then. You're hardly the first person to say this. > However, of the people who say it, hardly anyone actually produces > any code and the only person I know of who did dropped it when > performance went through the floor. Maybe you can do better. I really have no desire to code in C, thank you. I'd rather be coding in Python. (Hence my [idle] desire for macros in Python, so that I could do even more of my work in Python.) > There's no particular reason why Lisp is any better for AI research > than anything. Yes, there is. It's a very flexible language that can adapt to the needs of projects that need to push the boundaries of what computer programmers typically do. > I'm not familiar with the TIOBE metric, but I can pretty much > guarantee that regardless of what it says there is far more COBOL > code in the wild, being actively maintained (or at least babysat) > than there is lisp code. I'm agree that there is cedrtainly much more Cobol code being maintained than there is Lisp code, but that doesn't mean that there are more Cobol programmers writing new code than there are Lisp programmers writing new code. A project would have to be run by a madman to begin a new project in Cobol. >> Re Lisp, though, there used to be a joke (which turned out to be >> false), which went, "I don't know what the most popular programming >> language will be in 20 years, but it will be called 'Fortran'". In >> reality, I don't know what the most popular language will be called 20 >> years from now, but it will *be* Lisp. > And everyone who still uses the language actually called Lisp will > continue to explain how it isn't a "real" lisp for a laundry list of > reasons that nobody who gets work done actually cares about. And where are you getting this from? I don't know anyone who claims that any commonly used dialect of Lisp isn't *really* Lisp. |>oug From __peter__ at web.de Thu Jun 14 03:44:53 2007 From: __peter__ at web.de (Peter Otten) Date: Thu, 14 Jun 2007 09:44:53 +0200 Subject: Method much slower than function? References: <1181781612.939800.238890@q19g2000prn.googlegroups.com> <1181799961.148499.32210@o11g2000prd.googlegroups.com> Message-ID: Leo Kislov wrote: > On Jun 13, 5:40 pm, ido... at gmail.com wrote: >> Hi all, >> >> I am running Python 2.5 on Feisty Ubuntu. I came across some code that >> is substantially slower when in a method than in a function. >> >> >>> cProfile.run("bar.readgenome(open('cb_foo'))") >> >> 20004 function calls in 10.214 CPU seconds > >> >>> cProfile.run("z=r.readgenome(open('cb_foo'))") >> >> 20004 function calls in 0.041 CPU seconds >> > > I suspect open files are cached so the second reader > picks up where the first one left: at the of the file. > The second call doesn't do any text processing at all. > > -- Leo Indeed, the effect of attribute access is much smaller than what the OP is seeing: $ cat iadd.py class A(object): def add_attr(self): self.x = 0 for i in xrange(100000): self.x += 1 def add_local(self): x = 0 for i in xrange(100000): x += 1 add_local = A().add_local add_attr = A().add_attr $ python2.5 -m timeit -s 'from iadd import add_local' 'add_local()' 10 loops, best of 3: 21.6 msec per loop $ python2.5 -m timeit -s 'from iadd import add_attr' 'add_attr()' 10 loops, best of 3: 52.2 msec per loop Peter From stefan.sonnenberg at pythonmeister.com Thu Jun 21 03:34:23 2007 From: stefan.sonnenberg at pythonmeister.com (Stefan Sonnenberg-Carstens) Date: Thu, 21 Jun 2007 09:34:23 +0200 (CEST) Subject: Making decimal default datatype for floats during runtime Message-ID: <1068189.31481.BlRUCl8VTQA=.1182411263.squirrel@webmailer.hosteurope.de> Hi, I was wondering if there are any tricks around to do some sort of changing types, float in particular. I do many operations like summing etc on lots of floats and always have to do some extra checks where results are heading 0.0, like round(n,10) for example. My idea was to tell python in some way not to take the type float but decimal in an implicit fassion. It that possible ? And, is it still true for python 2.4/2.5 that one needs to do a = Decimal(str(aFloat)) instead of a = Decimal(aFloat) as it is in python 2.3 ? And, at least, has some tried to link (lib)python against tc_malloc and benchmarked it ? Thx in advance. From parasuram.nooranianand at wipro.com Tue Jun 26 02:23:22 2007 From: parasuram.nooranianand at wipro.com (parasuram.nooranianand at wipro.com) Date: Tue, 26 Jun 2007 11:53:22 +0530 Subject: Hi How to implement switch case statement. Message-ID: Hi My requirement is to check a variable with a set of constant values and call a particular function depending on the value of the variable. A C-language implementation might look something like : switch (a) { case 1 : func1(); case 2 : func2() ; default : func3(); } How to do it in Python ? Ofcourse an if-elif construct can also be used to do the job, which is indeed my last option. However i would like to know if a 'switch-case' option is available. I found some implementations involving dictionaries and lambdas but i don't know how suitable they might be for this kind of an implementation. Any suggestions and ideas welcome Thanks and regards Parasuram N.A. I know the answers to all the questions But its just that i don't find some of them worth answering The information contained in this electronic message and any attachments to this message are intended for the exclusive use of the addressee(s) and may contain proprietary, confidential or privileged information. If you are not the intended recipient, you should not disseminate, distribute or copy this e-mail. Please notify the sender immediately and destroy all copies of this message and any attachments. WARNING: Computer viruses can be transmitted via email. The recipient should check this email and any attachments for the presence of viruses. The company accepts no liability for any damage caused by any virus transmitted by this email. www.wipro.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From doug at alum.mit.edu Thu Jun 21 18:14:03 2007 From: doug at alum.mit.edu (Douglas Alan) Date: Thu, 21 Jun 2007 18:14:03 -0400 Subject: Python's "only one way to do it" philosophy isn't good? References: <1181368143.874341.273140@r19g2000prf.googlegroups.com> <7x3b0nmkk6.fsf@ruckus.brouhaha.com> Message-ID: Neil Cerutti writes: >>> But why is the ability to abstract syntax good? >> It allows the community to develop language features in a >> modular way without having to sully the code base for the >> language itself. > That's not an advantage exclusive to macros, though. No, but macros are often are necessary to be able to implement such features in (1) an efficient-enough manner, and (2) in a manner that is syntactically palatable. E.g., PEAK for Python implements multiple predicate-based dispatch, but you have to define the predicates as Python code within strings. That's not very pretty. And probably not very fast either. Though Python, in general, is not very fast, so perhaps that doesn't matter too much for Python. > Some time last week I found myself writing the following thing in > Python: > [...] > I deleted it right after I tried to use it the first time. Using it > is more cumbersome than simply repeating myself, due to syntax > limitations of Python. See what I mean! > And other, more bizarre syntax extensions have been perpetrated. > mx.TextTools uses Python tuples to write a completely different > programming language. Sounds like "the Loop macro" for Lisp, which implements a mini sort of Cobol-like language just for coding gnarly loops within Lisp. It turns out that when restricted to just coding gnarly loops, this is a much better idea than it sounds. Yes, you can do this sort of thing, sort of, without macros, but, as we discussed above, the result is often ugly and slow. >> A prime example of this is how CLOS, the Common Lisp Object >> System was implemented completely as a loadable library (with >> the help of many macros) into Common Lisp, which was not an OO >> language prior to the adoption of CLOS. > Is there a second example? ;) Why yes, now that you mention it: the Loop macro. Also, in many implementations of Lisp, much of the core language is actually implemented using macros against an even smaller core. Keeping this inside core as small as possible helps make the implementation easier to construct, maintain, and optimize. Also, way back when, when I used to code in Maclisp, I implemented my own object system and exception handling system in macros, as Maclisp had neither of these off the shelf. The object system took me a couple of weeks to do, and the exception handing system a couple of days. They worked well, looked good, and ran fast. > Seriously, maybe Python looks like 'blub' (thanks, Paul Graham), to > the skilled Lisp user, but it makes a lot of other languages look > like 'blub', too, including, sometimes, Lisp: Lisp has to 'blub' > generators. Actually, Scheme has first class continuations, and with continuations and macros you could easily implement generators, and I'm sure someone has. Whether such a library has been widely adopted for Scheme, though, I have no idea. You're probably right about Common Lisp, which is probably missing generators due to efficiency concerns. Lisp Machines had "stack groups", which were basically the same thing as generators, but making a call to a stack group was 100 times slower than a normal function call. This meant that people generally didn't use them even when it would make their code more elegant, due to the huge performance cost. Now, since Python is like 100 times slower than Common Lisp anyway, you don't notice this performance issue with Python's generators. They just happen to be only as slow as the rest of Python. |>oug "Lisp is worth learning for the profound enlightenment experience you will have when you finally get it; that experience will make you a better programmer for the rest of your days, even if you never actually use Lisp itself a lot." -- Eric Raymond From gagsl-py2 at yahoo.com.ar Mon Jun 11 23:49:14 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 12 Jun 2007 00:49:14 -0300 Subject: Accessing global namespace from module References: <1181577768.728377.262720@m36g2000hse.googlegroups.com> <1181593775.957808.136050@m36g2000hse.googlegroups.com> <200706112119.16124.techlist@pathfinder.phys.utk.edu> Message-ID: En Mon, 11 Jun 2007 22:19:15 -0300, Reuben D. Budiardja escribi?: > One last question. Do I have to do this for ever script I write, or can > I put > this into separate file and "include" it somehow ? > I am going to have several mainscripts.py, and all is going to import > myModule > that will need access to this plots subroutine. It'll be great if I can > put > this trick on a single file that is included by the main scripts, to > avoid > violating DRY principle. According to your description on how things work, you will need the globals() from mainscript.py; try this: --- mainscript.py --- import plot_setup plot_setup.setup(globals()) ... rest of script, perhaps importing myModule.py ... --- plot_setup.py --- import sys from types import ModuleType as module def setup(namespace): plotModule = module('plot') for key,value in namespace.items(): if key[:2] != '__': setattr(plotModule, key, value) sys.modules['plot'] = plotModule --- myModule.py --- import plot def do_work(): plot.DrawPlot(...) ... (Having to type two lines at the top of your main scripts doesn't look so bad...) -- Gabriel Genellina From hg at nospam.org Tue Jun 12 17:02:40 2007 From: hg at nospam.org (hg) Date: Tue, 12 Jun 2007 16:02:40 -0500 Subject: stdout/err and C extentions References: <5rCbi.98038$vE1.59482@newsfe24.lga> Message-ID: Robert Bauck Hamar wrote: > hg wrote: > >> Robert Bauck Hamar wrote: >> >>> hg wrote: >>> >>>> Hi, >>>> >>>> I have the following >>>> >>>> ********************* C extention - redir.c >>>> >>>> >>>> #include "Python.h" >>>> >>>> PyObject * test_redir_test(PyObject *self) { >>>> fprintf(stdout, "Hello from an extention!\n"); >>>> Py_INCREF(Py_None); >>>> return Py_None; >>>> } >>>> >>> [...] >>>> *********************** python test script: test.py: >>>> import sys >>>> >>>> >>>> class My_Stdout: >>>> def write(self, p_string): >>>> l_file = open('res.txt','a') >>>> l_file.write(p_string) >>>> l_file.close >>>> >>>> >>>> sys.stdout = My_Stdout() >>>> >>>> print 'toto' >>>> import test_redir >>>> >>>> >>>> >>>> test_redir.test() >>>> >>>> >>>> >>>> **************** Question: >>>> >>>> print 'toto' does go to "res.txt" while "Hello from an extention!\n" >>>> goes to the console. >>>> >>>> Any clue ? >>> >>> There is no portable way to change the location of stdout during >>> execution of a program. If you want to print with whatever is sys.stdout >>> from an extension module, you should call sys.stdout's write method >>> dynamically from C. >>> >> >> Robert, thanks, >> >> I understand that sys.stdout and stdout of an extention are two different >> entities ... correct ? > > Yes. Python's sys.stdout and C's stdout are both objects wrapping the call > os.write(1, "string") in Python and write(1, "string", strlen("string")) > in C, or some other function on platforms using other mechanisms for > output. > > In that way sys.stdout in Python and stdout in C will be portable to many > more systems. > > -- > Robert Bauck Hamar Thanks Robert. hg From "sergio\" at (none) Tue Jun 19 10:33:11 2007 From: "sergio\" at (none) (none) Date: Tue, 19 Jun 2007 15:33:11 +0100 Subject: HTMLParser.HTMLParseError: EOF in middle of construct In-Reply-To: References: <1182195498.16548.5.camel@localhost.localdomain> Message-ID: <4677e903$0$28479$a729d347@news.telepac.pt> Gabriel Genellina wrote: > En Mon, 18 Jun 2007 16:38:18 -0300, Sergio Monteiro Basto > escribi?: > >> Can someone explain me, what is wrong with this site ? >> >> python linkExtractor3.py http://www.noticiasdeaveiro.pt > test >> >> HTMLParser.HTMLParseError: EOF in middle of construct, at line 1173, >> column 1 >> >> at line 1173 of test file is perfectly normal . > > That page is not valid HTML - http://validator.w3.org/ finds 726 errors > in it. ok but my problem is not understand what is the specific problem at line 1173 > HTMLParser expects valid HTML - try a different tool, like > BeautifulSoup, which is specially designed to handle malformed pages. > > --Gabriel Genellina > From mail at microcorp.co.za Tue Jun 5 02:29:33 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Tue, 5 Jun 2007 08:29:33 +0200 Subject: Who uses Python? References: <1180985830.288414.208850@q69g2000hsb.googlegroups.com> Message-ID: <01df01c7a73d$98920ae0$03000080@hendrik> "walterbyrd" wrote: > Anything else? Finance? Web-analytics? SEO? Digital art? Industrial control and alarm annunciation - Hendrik From ask at me Fri Jun 29 19:36:32 2007 From: ask at me (alf) Date: Fri, 29 Jun 2007 18:36:32 -0500 Subject: overriding base class Message-ID: Hi, I want to develop a following lib: lib space user space A -> B -> | -> user_class however A and B are abstrac enough to have following: user_super_base_class -> | -> A -> B -> | -> user_class user space lib space user spaca Any idea how to do that? -- alfz1 From george.sakkis at gmail.com Wed Jun 20 19:41:24 2007 From: george.sakkis at gmail.com (George Sakkis) Date: Wed, 20 Jun 2007 23:41:24 -0000 Subject: PEP 3107 and stronger typing (note: probably a newbie question) In-Reply-To: References: <1182369568.941307.316260@p77g2000hsh.googlegroups.com> Message-ID: <1182382884.307144.210920@q75g2000hsh.googlegroups.com> On Jun 20, 5:22 pm, Stephen R Laniel wrote: > Perhaps it would help for me to explain what I'd like. > > Under both Perl and Python, I've found myself > having/wanting to write things like so: > > def my_func( int_arg, str_arg ): > try: > int_arg = int( int_arg ) > str_arg = str( str_arg ) > except ValueError: > sys.stderr.write( "Args are not of the right type\n" ) > sys.exit(1) After several hundreds of such checks, good luck making the 2.0 version of your application Unicode-friendly. > Granted, in a dynamic language we won't always (maybe "won't > often") have a situation where the types are known this well > at compile time. But sometimes we will. And it would be nice > to catch these before the program even runs. Optional typing has its merits but your example is more of a counterexample, an example where the explicit try/catch doesn't really buy you anything. You'd get essentially the same effect if you just attempted the conversion and let any exception propagate: def my_func(some_non_hungarian_notation_meaningful_name, other_non_hungarian_notation_meaningful_name): a = int(some_non_hungarian_notation_meaningful_name) b = str(other_non_hungarian_notation_meaningful_name) More often than not the types that you *think* are required will turn out to be more (and sometimes less) restrictive than necessary. Still, If you're addicted to manifest typing [1], the typechecking module [2] may give you a warm and fuzzy feeling: from typecheck import accepts @accepts(int, str) my_func(some_non_hungarian_notation_meaningful_name, other_non_hungarian_notation_meaningful_name): HTH, George [1] http://c2.com/cgi/wiki?ManifestTyping [2] http://oakwinter.com/code/typecheck/tutorial/basics.html From doug at alum.mit.edu Sat Jun 30 14:06:09 2007 From: doug at alum.mit.edu (Douglas Alan) Date: Sat, 30 Jun 2007 14:06:09 -0400 Subject: Python's "only one way to do it" philosophy isn't good? References: <7xejjzmk7u.fsf@ruckus.brouhaha.com> <7xy7i7xjl5.fsf@ruckus.brouhaha.com> <1183098228.517915.12140@q75g2000hsh.googlegroups.com> <1183184091.240942.29060@w5g2000hsg.googlegroups.com> Message-ID: Michele Simionato writes: >> Right. So? I understand this issue completely and I code >> accordingly. > What does it mean you 'code accordingly'? IMO the only clean way out > of this issue is to NOT rely on the garbage collector and to manage > resource deallocation explicitely, not implicitely. (1) I don't rely on the refcounter for resources that ABSOLUTELY, POSITIVELY must be freed before the scope is left. In the code that I've worked on, only a small fraction of resources would fall into this category. Open files, for instance, rarely do. For open files, in fact, I actually want access to them in the traceback for debugging purposes, so closing them using "with" would be the opposite of what I want. (2) I don't squirrel away references to tracebacks. (3) If a procedure catches an exception but isn't going to return quickly, I clear the exception. |>oug From exarkun at divmod.com Wed Jun 27 05:37:40 2007 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Wed, 27 Jun 2007 05:37:40 -0400 Subject: PyKQueue In-Reply-To: <1182919726.121679.292020@g4g2000hsf.googlegroups.com> Message-ID: <20070627093740.4947.679209825.divmod.quotient.4640@ohm> On Tue, 26 Jun 2007 21:48:46 -0700, Adam Atlas wrote: >Does anyone have a copy of PyKQueue 2.0 around? The site it's supposed >to be on (http://python-hpio.net/trac/wiki/PyKQueue) is down. > >-- >http://mail.python.org/mailman/listinfo/python-list > http://twistedmatrix.com/trac/browser/sandbox/foom/pykqueue From evan at yelp.com Tue Jun 12 11:27:36 2007 From: evan at yelp.com (Evan Klitzke) Date: Tue, 12 Jun 2007 08:27:36 -0700 Subject: Convert String to Int and Arithmetic In-Reply-To: <1181658761.300066.118210@a26g2000pre.googlegroups.com> References: <1181658761.300066.118210@a26g2000pre.googlegroups.com> Message-ID: On 6/12/07, tereglow wrote: > Basically, I want to come out with 1000 for the above string. Any > help would be appreciated. > Tom There are any number of techniques you can use to parse out the integer part of the string -- the most generic is to use the re module to match regular expressions, but you may not have to use that module if you know the exact form of the strings you are parsing. Once you parse out the number into a string such as '1000000' you can just cast it as an integer using some code like x = int('1000000') -- Evan Klitzke From bbxx789_05ss at yahoo.com Tue Jun 26 16:38:30 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: Tue, 26 Jun 2007 13:38:30 -0700 Subject: subprocess.Popen() problem Message-ID: <1182890310.087603.273390@n60g2000hse.googlegroups.com> I have this program: mytest.py -------------- myinput = raw_input("Enter input: ") if myinput == "hello": print "goodbye" -------------- and I want to execute it using subprocess.Popen(). I tried the following but it just hangs: ----------- import subprocess f = open("/Users/me/2testing/dir1/aaa.txt", "w") my_path = "/Users/me/2testing/" my_file = "mytest.py" p = subprocess.Popen(["python", "mytest.py"], stdin=subprocess.PIPE, stdout = f, stderr = f, cwd = my_path ) f.close() p.stdin.write("hello") p.wait() f.open("/Users/me/2testing/dir1/aaa.txt") print f.read() ------------ From steven.bethard at gmail.com Sat Jun 2 12:02:05 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Sat, 02 Jun 2007 10:02:05 -0600 Subject: Observer-Pattern by (simple) decorator In-Reply-To: <1180781727.519949.172580@q75g2000hsh.googlegroups.com> References: <1180781727.519949.172580@q75g2000hsh.googlegroups.com> Message-ID: David Wahler wrote: > On Jun 2, 12:27 am, Steven Bethard wrote: >> I think you want to define __get__ on your Observable class so that it >> can do the right thing when the method is bound to the instance: [snip] > Is this desired behavior? > >>>> a = SomeActor() >>>> b = SomeActor() >>>> a.meth.observers is b.meth.observers > True >>>> a.meth.add_callback(callback) >>>> b.meth(42) > 42 > Yippie, I've been called on <__main__.SomeActor object at 0x00C23550> Yeah, I wasn't sure whether the observers were meant to be shared or not. Yes, they are shared in the previous code. If you don't want them to be shared, you can just use a WeakKeyDictionary to map instances to their appropriate observer lists:: >>> class Observable(object): ... _observer_map = weakref.WeakKeyDictionary() ... def __init__(self, func, instance=None): ... if instance is None: ... observers = [] ... else: ... observers = self._observer_map.setdefault(instance, []) ... self.func = func ... self.instance = instance ... self.observers = observers ... def __get__(self, obj, cls=None): ... if obj is None: ... return self ... else: ... func = self.func.__get__(obj, cls) ... return Observable(func, obj) ... def __call__(self, *args, **kwargs): ... result = self.func(*args, **kwargs) ... for observer in self.observers: ... observer(self.instance) ... return result ... def add_callback(self, callback): ... self.observers.append(callback) ... >>> class SomeActor(object): ... @Observable ... def meth(self, foo): ... print foo ... >>> def callback(instance): ... print "Yippie, I've been called on", instance ... instance.bar = True ... >>> a1 = SomeActor() >>> a2 = SomeActor() >>> a1.meth.observers is a2.meth.observers False >>> a1.meth.add_callback(callback) >>> a1.meth('boring old argument') boring old argument Yippie, I've been called on <__main__.SomeActor object at 0x00E87890> >>> a2.meth('boring old argument') boring old argument STeVe From mail at timgolden.me.uk Tue Jun 12 10:31:17 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Tue, 12 Jun 2007 15:31:17 +0100 Subject: file open default location In-Reply-To: References: Message-ID: <466EAE35.2010302@timgolden.me.uk> T. Crane wrote: > myFile = file('test.txt','w') > > Here I'm opening/creating a file but I have not specified the exact path, so > how does Python determine where to 'put' this file? More to the point, how > do I change what the default path is? Right now it's a networked drive that > should not be getting my Python clutter. Python doesn't choose anything. Whatever your Operating System deems the current drive when you start Python is the one which will contain any other unqualified files. You can find out what it is by running a script which just does: import os print os.getcwd () and you can change it by doing this: import os os.chdir ("new-path-of-my-choosing") > Interestingly, this network drive is also where I can find my _ipython > folder from my ipython install as well as my .matplotlib folder. Can anyone > tell me how to change where these folders and files go by default? Different question. (And, I'm afraid, a more complicated one). You haven't said, but I'm going to guess you're running on Windows, not least because any *nix setup I know of will place the user in a well-known "Home" directory (typically /home/username). The trouble is that applications like ipython, and maybe matplotlib, were developed under *nix where you can rely on getting hold of a user's "Home" directory either by expanding the "~" shell variable -- or whatever it's called -- or by examining the HOME shell variable. Windows doesn't traditionally have either of these things, and has over the years had several locations with legitimate claim to be "Home". Python's own os.expanduser, for example, uses this approach: """ On Windows, only "~" is supported; it is replaced by the environment variable HOME or by a combination of HOMEDRIVE and HOMEPATH """ I think IPython now uses expandvar. Maybe it always did; I've an idea its current behaviour was a more recent addition to Python under Windows. But IPython used to fall back to C:\ if it couldn't do anything else. Don't know about matplotlib. You'll need to check the docs (or the source). TJG From vicent at vcubells.net Sat Jun 30 02:23:01 2007 From: vicent at vcubells.net (Cubells) Date: Sat, 30 Jun 2007 08:23:01 +0200 Subject: Close/hide a child window Message-ID: <4685F6C5.9060903@vcubells.net> Hi there: I have two simple classes in two diferent files: $ cat first.py #/usr/bin/env python # -*- coding: utf-8 -*- import pygtk pygtk.require('2.0') import gtk import second class first: def close_program(self, widget, data=None): gtk.main_quit() return False def open_second(self, widget): second_window = eval("second.second")(self) def __init__(self): window = gtk.Window(gtk.WINDOW_TOPLEVEL) window.connect("delete_event", self.close_program) window.set_title("First") window.set_border_width(10) button = gtk.Button("Open") button.connect("clicked", self.open_second) window.add(button) window.show_all() def main(): gtk.main() return 0 if __name__ == "__main__": first() main() That's the second one: $ cat second.py #/usr/bin/env python # -*- coding: utf-8 -*- import pygtk pygtk.require('2.0') import gtk class second(gtk.Window): def close_second(self,widget): self.hide() #self.destroy() #gtk.main_quit() return False def __init__(self, parent=None): gtk.Window.__init__(self) try: self.set_screen(parent.get_screen()) except: self.connect("destroy", lambda *w: gtk.main_quit()) window2 = gtk.Window(gtk.WINDOW_TOPLEVEL) window2.set_title("Second") window2.set_border_width(10) window2.set_modal(True) window2.set_resizable(False) button2 = gtk.Button("Second") button2.connect("clicked", self.close_second) window2.add(button2) window2.show_all() def main(): gtk.main() return 0 if __name__ == "__main__": second() main() The question is simple: How can I close/hide/destroy the second window without to destroy the first window when I click the button2?? When I close the second window it works, but when I click the button2 it doesn't. A lot of thanks... From kinch1967 at gmail.com Sun Jun 10 07:55:38 2007 From: kinch1967 at gmail.com (bullockbefriending bard) Date: Sun, 10 Jun 2007 04:55:38 -0700 Subject: matching objects by a tuple field criterion In-Reply-To: References: <1181473124.790391.293120@r19g2000prf.googlegroups.com> Message-ID: <1181476538.812941.37490@r19g2000prf.googlegroups.com> > Instead of passing a wild-card tuple like (*,*,*,4,*,*) simply pass the > integer you want to match and the position you want to match it in. for sure. that was more for expository purpose rather than how i was planning to go about it. > As a generator expression: > > (obj for obj in list_of_objects if obj.data[what] == where) above or equivalent list comprehension was what i had in mind as far as linear search goes. and scanning the list like this will most likely be 'good enough' performance-wise. however, partly just out of curiosity, i was wondering if there is some kind of data structure which might let me find all the matches a bit faster. From MI5Victim at mi5.gov.uk Fri Jun 8 09:53:07 2007 From: MI5Victim at mi5.gov.uk (MI5Victim at mi5.gov.uk) Date: 8 Jun 2007 13:53:07 GMT Subject: MI5 Persecution: Goldfish and Piranha 29/9/95 (5104) Message-ID: I just thought I'd let you know what I've been reading into the "Crusader" spam. I don't want to post this to usenet because somebody might try to tie that in to my posts in some way (someone already has, in uk.misc). First of all, I'd like to ask you to believe that my phone line in my apartment is bugged, and has been for many months. I have moved a couple of times this year, but "they" have faithfully been on my trail. Anyway, let's suppose my phone line is bugged. Now, when I talk to my internet service provider, it's over a SLIP (now PPP) connection. So if you wanted to bug what was said, either you'd listen in over the line and have to decode the transmission, or you could go to the service provider (more difficult) and ask them to decode a particular user's connection. OK, so now they're listening to everything I do over my SLIP/PPP connection. A couple of months ago I was messing around with faking articles through nntp servers and through anonymous remailers. I chose a nice inconspicuous newsgroup for my little tests, something no-one would ever notice. Guess which newsgroup I chose??? Yes, _FISH_!!! or rec.aquaria to be precise And guess what articles I tried to post? Goldfish, Koi carp and, you'll never guess... PIRANHA!!! The goldfish article and the Koi went through, but the piranha didn';t appear. by now you probably think this is too silly for words. But if you look in the papers a few eeks ago you will find John Major, Tonny Blair and Paddy Ashdown sharing a "private joke" about Major's sunburnt goldfish. We haven't had anything about Koi yet (they must be too dull ). Now, sent by someone who clearly knew what they were doing (they chose an Italian backbone site for their launch point) we have many thousands of messages to people all over the globe. All about piranha, and with the punchline "that gives you something to think about, doesn't it?" The way it works is that they're trying to kill two birds with one stone again. I don't knoiw why they should be against these national alliance people, but my interpretation is that they simultaneously try to discredit them, and stem the flow of Corley articles. ================================================================= In article , Mike Corley wrote: > >John J Smith (J.J.Smith at ftel.co.uk) wrote: > >: b) we do know who you are. Or are you someone else we don't know about? >: You are currently known as "That bloody persistant net nutter, who's >: expanding from uk.misc to the rest of the world". > >I think the point I was trying to make is that I could tell you things >from my personal life, at home and at work, which would add credibility >to my story. But if I named people, then (a) they would object violently >to being included in this shenanigans, and (b) I would be revealing my >identity which would be bad for my personal life and my work life. Of >course some people in my personal life, and at work, do know who "mike >corley" is. But at least we're observing a studied silence for now. :People can always be called "MR X", to save them being named. : :I'm completely perplexed as to what you mean by b). Revealing identity? :To who? And why would this be bad for any part of your life when you :already have a less than respectful reputation here? I'll just enumerate one or two things that I can still remember. Sometime around August/Sept 1992 I was living in a house in Oxford, and coming out of the house was physically attacked by someone - not punched, just grabbed by the coat, with some verbals thrown in for good measure. That was something the people at work shouldn't have known about... but soon after a couple of people were talking right in front of me about, "yeah, I heard he was attacked". Again, one I went for a walk in some woods outside Oxford. The next day, at work, someone said "you know he went to the forest yesterday". I don't want to put details on usenet of what happened because to do so would be to risk it happening again. If you put ideas in peoples' heads then you can find them reflecting back at you, and I don't want that. Also I can't remember that much from three years ago. From november 1992 I started taking "major tranquilizers" and just blotted the whole thing from my mind. >This is a feature time and time again, that the security services >(presumed) get at you by manipulating other people around you to get at >you. If you have their contacts, manpower, resources and technology then >you can do that sort of thing. :But why? Are you a threat? They pretend they "have" to get at me. After the first few weeks they had to find a reason to spy and abuse. You can't abuse someone unless they're in the wrong in some way. What I did "wrong" was to be ill. So it became "nutter" and "monster" and "he's going to attack us" coupled with "ha ha ha, he can't do anything to defend himself, it was so funny". That obvious contradiction within their propaganda is something they blithely ignore. :So, the Security Services never *actually* appear, and you assume that :they get someone else to do your dirty work. This is a bit of a big :logical step, here: That person doesn't like me, or is causing me trouble, :it's not because they've got problems themselves, it must be the "Security :Services". Yes. Because people are infallible. Or is there more? A single source is indicated because of the range of harassment. BBC + Capital + manipulated_public_at_large + set_up_situations, what does that add up to? Add in the technology to carry out the covert spying and the manpower and knowhow to follow you around for five years without being spotted. It smells very much of the security services, because there is no other organization (to my knowledge) which does the things I've seen these people do. Remember, they have deliberately chosen the softest of soft targets to victimize. They purposely chose a mentally ill person who they thought would be likely to kill himself anyway, so that they could get away with murder. And in all likelihood it will have started as a personal vendetta by someone. Who could that be? I don't know, but I can give you some clues. The first possibility (deep breath) is that someone from my college set me up. Six years ago I graduated from university in the UK, during the last year there I was steadily getting more and more ill. I know that I was talking in my sleep; although I don't know what I was saying, it got me a reputation, and if someone from my college talked afterwards to the "wrong" people then that could be the reason for all that has followed. I think that's the strongest contender for source. Directly beneath my room lived another bloke who frequently had his friends round late at night, after the time that I went to sleep. So they could have heard what I was saying in my sleep, and that could have got me the reputation for "talking to myself". What I don't know is why that should have rebounded a year after I left. You'd think it would have happened sooner; it's a bit odd to wait for a year and then start abuse. That leads me to question what in particular happened around May/June 1990 for them to start then. >What I don't know is how it looks from the other side, from the side of >the people who are being manipulated to get at me. On a couple of >occasions I have challenged people to tell the truth of the matter, but >they have alwats ducked the challenge. :Have you ever considered the possibility, that you have made a mistake, and :the people don't know what you are talking about? Yes. I am currently considering the possibility that some people around me know only what is being posted on Usenet, and have not been "contacted" by "them". But I _know_ that others have been contacted. :What words? Are they in common use? Could they be a catchphrase of a :popular comedian?: "Nice to see you, to see you nice"? In England the all-time No. 1 is "nutter". Easter this year, returning home from Clapham police station to report five years of harassment ("we're not saying it's happening and we're not saying it isn't happening"), another "not happening" incident of harassment when a cowardly little slut did her country proud by yelling "nutter, nutter, nutter" in the face of the hated enemy. What can you do about that? You can't yell abuse back in their face, because they know they're supported by their peers, by the media, by the murderers in the security forces. You can't put them down when the fascist establishment is on their side. You can't hit them, because they would deny their abuse, they would deny knowing anything, and bring charges against the "nutter" who attacked them "at random". >You know, you're >passing saomeone, they're hardly going to construct an argument for your >benefit, so they work a word of abuse into the conversation which they >can giggle at. :Abuse such as what? We're all adults here, we can take it. Is this abuse :aimed at you? How can you tell it is? I think I've said already what the words are. Thing is, at any given time the language is consistent. In January everyone's calling you X, then a few weeks later people stop calling you X and start calling you Y. You can tell it's aimed at me, because when people repeatedly say the same words are you walk past, then laugh, you would have to be hard of understanding not to recognize it. >Or they repeat something that's been said somewhere else... the PE thing >being a case in point. PE says it, then other people pick up the refrain. :Remind me who PE is again. PE = "Private Eye" >: >To give you an example, which I mentioned in another posting. In around >: >October 1992, Private Eye ran a cover with the heading "Major's support >: >lowest ever", with John calling to Norma on the cover "come back, Norma". >: >Only one obvious interpretation to that, isn';;t there? I certainly >: >thought so when I saw that cover. Wrongo!! Down the pub with people from work >: >Simon says to phil, "don';t you think it's wrong then?" phil says, "well >: >private eye are usuallyright"..."hislop strikes again.. > >: Erm. Mike? Heeeelllllooo? What are you on about. What is the other >: interpretation then? Norma having an affair? Seems a bit wrong, with the >: heading "Majors support Lowest ever"... > >No, this one isn't obvious , it really does need to be explained. I >certainly didn't understand it when I first saw it. You see, the kernel >of vitriol is in the words "come back". At the time, the themes of >abuse were centred around interpretations of those two words (stretch your >mind a little bit, I don't have to spell it out for you, surely). :You did in your mail item. : :You seem to be scouting about something called a "Double Entendre". The :inference being "Come" = Ejaculation, "Back" = Anus (not the first part :of the body I would have went for, I would have foolishly gone for "Back", :silly old me). : :You see to have picked a sodomy double entendre out of a Private Eye :headline. They are everywhere. The English language has much double :meaning in it, and if you put your mind to it, you could pull a double :entendre out of a randomly chosen page of the bible. So what? >The point is that when Simon pointed it out to Phil, he did recognise >what it meant after a moment's thought... and so did I... and so did the >people who repeated it several times later... so however murky it may >seem to you, that is the meaning they intended it to have... I still don't really know if the meaning was intended when that headline was written, or if it was simply "found" after the fact. The reason I think it might be the former is that I got quite a lot of abuse along the lines of "sound-alike" or "double-entendre" at work, in particularly from Steve. So "double" inevitably came to mean split-personality, "two people in one"; "back" inevitably came to mean "backside", "come" inevitably meant you-know- what, "split" (well, we'd better split now) again you can guess, "bent" (of a similar bent), the list goes on forever. These aren't "nice" double- entendres intended for comedy, they're nasty words to humiliate and cause pain. If I could turn the clock back three years then I would sue my former employers for harassment and I would almost certainly win. I had to take pills after a year of Oxford, so they wouldn't be able to lie their way out of it. Actually, I could still take them to court - the main obstacle being that three years after the fact is a bit late and much of what happened, the details that would be necessary for a case to go to court, has just been obliterated by time. : Smid ============================================== From: flames at flames.cityscape.co.uk (Peter Kr|ger) Newsgroups: uk.misc,soc.culture.british,alt.conspiracy,uk.media,uk.legal Subject: Re: Mike Corley - a (helpful) suggestion Date: Mon Oct 2 05:43:42 1995 In article <812551172snz at objmedia.demon.co.uk>, Snail says: >Indeed, I feel that my Usenet access is censored simply because I don't want >to download groups he is partaking in, because of his behaviour. > >I wasn't that bothered, but I am starting to get seriously pissed off >with him. Which takes a lot. Hi Snail This person Corley seems quite interesting for three reasons. I put the following at the end of a post in another thread just to see if he was reading any other threads in uk.media. It seems he is probably not. ----------------------------------------------------------------------- Heres an interesting little story from back in the early days of CCD technology. There was this miniature camera which was designed to fit behind the infrared receiver lens of the remote control system (just beside the IR sensor itself) the camera clocked out the data in 256 lines of 256 pixels from a Fairchild chip and fed it out, a line at a time, into the VBI within the TV set itself. The signal could be picked up remotely from a standard license detector van from where it was stripped out of the surrounding RF signal and relayed back to the TV station where it was displayed as a slowscan monochrome image in a corner of the news readers monitor. 5104 From reubendb at gmail.com Mon Jun 11 12:02:48 2007 From: reubendb at gmail.com (reubendb) Date: Mon, 11 Jun 2007 16:02:48 -0000 Subject: Accessing global namespace from module Message-ID: <1181577768.728377.262720@m36g2000hse.googlegroups.com> Hello, I am new to Python. I have the following question / problem. I have a visualization software with command-line interface (CLI), which essentially is a Python (v. 2.5) interpreter with functions added to the global namespace. I would like to keep my own functions in a separate module and then import that module to the main script (that will be executed using the CLI interpreter). The problem is, I cannot access the functions in the global namespace of the main script from my module. Is there anyway to do that ? Here is an example of what I meant. The function AddPlot() and DrawPlots() are added to the global namespace by the software CLI. If I do this: mainscript.py: --------------------------- AddPlot("scatter", "coordinate") # set other things here DrawPlots() it works fine. But I want to be able to do this: myModule.py: ---------------------- def defaultScatterPlot(): AddPlot("scatter", "coordinate") #do other things DrawPlots() and then in mainscript.py: --------------------------------------- import myModule myModule.defaultScatterPlot() This won't work because myModule.py doesnot have access to AddPlot(). How do I do something like this ? Thank you in advance for any help. RDB From rene at korteklippe.de Tue Jun 12 14:04:29 2007 From: rene at korteklippe.de (=?UTF-8?B?UmVuw6kgRmxlc2NoZW5iZXJn?=) Date: Tue, 12 Jun 2007 20:04:29 +0200 Subject: List sequential initialization In-Reply-To: <1181670619.086709.116730@g37g2000prf.googlegroups.com> References: <1181670619.086709.116730@g37g2000prf.googlegroups.com> Message-ID: <466ee02b$0$10192$9b4e6d93@newsspool4.arcor-online.net> HMS Surprise schrieb: > I thought if I could do this: > >>> a = b = '' Bind both the names a and b to the same string object. > >>> a = 'a' Bind the name a to a *new* string object with the value 'a'. This replaces the previous binding of the name a. > >>> la = lb = [] Bind both the names la and lb to the same list object. > >>> la.append('a') Append the string 'a' to the *existing* list object referenced by the name la. This modifies the object that is referenced by the name la (and also by the name lb), it does not create a new object. The equivalent to what you did with the strings above would have been: la = ['a'] This would have created a new list object and bound the name la to it, while the name lb would still reference the other list object you created earlier. If you want to modify the list referenced by la but not the one referenced by lb, you need to actually *copy* the list with one of these methods: lb = list(la) or lb = la[:] -- Ren? From duncan.booth at invalid.invalid Sun Jun 17 07:00:58 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 17 Jun 2007 11:00:58 GMT Subject: Trivial string substitution/parser References: Message-ID: Samuel wrote: > Hi, > > How would you implement a simple parser for the following string: > > --- > In this string $variable1 is substituted, while \$variable2 is not. > --- > > I know how to write a parser, but I am looking for an elegant (and lazy) > way. Any idea? > The elegant and lazy way would be to change your specification so that $ characters are escaped by $$ not by backslashes. Then you can write: >>> from string import Template >>> t = Template("In this string $variable1 is substituted, while $$variable2 is not.") >>> t.substitute(variable1="hello", variable2="world") 'In this string hello is substituted, while $variable2 is not.' If you must insist on using backslash escapes (which introduces the question of how you get backslashes into the output: do they have to be escaped as well?) then use string.Template with a custom pattern. From __peter__ at web.de Wed Jun 6 16:39:03 2007 From: __peter__ at web.de (Peter Otten) Date: Wed, 06 Jun 2007 22:39:03 +0200 Subject: Determinant of Large Matrix References: Message-ID: James Stroud wrote: > I'm using numpy to calculate determinants of matrices that look like > this (13x13): > > [[ 0. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1.] > [ 1. 0. 1. 4. 1. 9. 4. 4. 1. 1. 4. 9. 4. 9.] > [ 1. 1. 0. 1. 4. 4. 9. 9. 4. 4. 1. 4. 1. 4.] > [ 1. 4. 1. 0. 9. 1. 4. 4. 9. 1. 4. 1. 4. 1.] > [ 1. 1. 4. 9. 0. 4. 4. 4. 1. 4. 1. 9. 4. 9.] > [ 1. 9. 4. 1. 4. 0. 4. 4. 9. 4. 1. 1. 4. 1.] > [ 1. 4. 9. 4. 4. 4. 0. 1. 1. 1. 9. 1. 9. 4.] > [ 1. 4. 9. 4. 4. 4. 1. 0. 4. 1. 9. 4. 4. 1.] > [ 1. 1. 4. 9. 1. 9. 1. 4. 0. 4. 4. 4. 4. 9.] > [ 1. 1. 4. 1. 4. 4. 1. 1. 4. 0. 9. 4. 9. 4.] > [ 1. 4. 1. 4. 1. 1. 9. 9. 4. 9. 0. 4. 1. 4.] > [ 1. 9. 4. 1. 9. 1. 1. 4. 4. 4. 4. 0. 4. 1.] > [ 1. 4. 1. 4. 4. 4. 9. 4. 4. 9. 1. 4. 0. 1.] > [ 1. 9. 4. 1. 9. 1. 4. 1. 9. 4. 4. 1. 1. 0.]] > > For this matrix, I'm getting this with numpy: > > 2774532095.9999971 > > But I have a feeling I'm exceeding the capacity of floats here. Does > anyone have an idea for how to treat this? Is it absurd to think I could > get a determinant of this matrix? Is there a python package that could > help me? Here's some anecdotal evidence that your result may be correct: import operator m = eval("""[[ 0. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1.] [ 1. 0. 1. 4. 1. 9. 4. 4. 1. 1. 4. 9. 4. 9.] [ 1. 1. 0. 1. 4. 4. 9. 9. 4. 4. 1. 4. 1. 4.] [ 1. 4. 1. 0. 9. 1. 4. 4. 9. 1. 4. 1. 4. 1.] [ 1. 1. 4. 9. 0. 4. 4. 4. 1. 4. 1. 9. 4. 9.] [ 1. 9. 4. 1. 4. 0. 4. 4. 9. 4. 1. 1. 4. 1.] [ 1. 4. 9. 4. 4. 4. 0. 1. 1. 1. 9. 1. 9. 4.] [ 1. 4. 9. 4. 4. 4. 1. 0. 4. 1. 9. 4. 4. 1.] [ 1. 1. 4. 9. 1. 9. 1. 4. 0. 4. 4. 4. 4. 9.] [ 1. 1. 4. 1. 4. 4. 1. 1. 4. 0. 9. 4. 9. 4.] [ 1. 4. 1. 4. 1. 1. 9. 9. 4. 9. 0. 4. 1. 4.] [ 1. 9. 4. 1. 9. 1. 1. 4. 4. 4. 4. 0. 4. 1.] [ 1. 4. 1. 4. 4. 4. 9. 4. 4. 9. 1. 4. 0. 1.] [ 1. 9. 4. 1. 9. 1. 4. 1. 9. 4. 4. 1. 1. 0.]]""".replace(".", ".,").replace("]", "],"))[0] M = [[int(x) for x in row] for row in m] def subdet(m, rowindex): return [row[1:] for index, row in enumerate(m) if index != rowindex] def det(m): if len(m) == 1: return m[0][0] sign = 1 sigma = 0 for index, row in enumerate(m): x = row[0] if x: sigma += sign * x * det(subdet(m, index)) sign = -sign return sigma def common_multiple(items): items = set(items) items.discard(0) if items: return reduce(operator.mul, items) else: return 0 def det3(m, switch_algo=8): p = 1 q = 1 while 1: if len(m) == switch_algo: a, b = divmod(p*det(m), q) assert b == 0 return a cm = common_multiple(row[0] for row in m) if cm == 0: return 0 sign = 1 e = enumerate(m) for first_index, first_row in e: if first_row[0]: f = cm // first_row[0] assert (cm % first_row[0]) == 0 p *= sign * cm q *= f first_row[:] = [f*x for x in first_row[1:]] break first_row[:] = first_row[1:] sign = -sign for index, row in e: if row[0]: f = cm // row[0] assert (cm % row[0]) == 0 q *= f row[:] = [f*x - fx for x, fx in zip(row[1:], first_row)] else: row[:] = row[1:] del m[first_index] if __name__ == "__main__": import pprint pprint.pprint(M) result = det3(M) assert result == 2774532096 print "det(M) =", result As I use only integers, any errors should be algorithmic rather than caused by rounding. Peter From efrat_regev at yahoo.com Fri Jun 22 02:22:35 2007 From: efrat_regev at yahoo.com (Efrat Regev) Date: Fri, 22 Jun 2007 09:22:35 +0300 Subject: Error in following code In-Reply-To: <1182491886.184746.104640@x35g2000prf.googlegroups.com> References: <1182491886.184746.104640@x35g2000prf.googlegroups.com> Message-ID: <467b678d$1@news.bezeqint.net> zaperaj at gmail.com wrote: > Im working with python2.2 on red hat linux. > The following program is supposed to print decreasing numbers from an > entered number till 1, each decrement being = 1 : > > #! usr/bin/env/python > > def f(n=int(raw_input("enter number: "))): > print 'n=',n > if n>1: > return n*f(n-1) > else: > print 'end' > return 1 > > > > > Though it works fine on the python interpretor, i dont get the > required output when i write this code in gedit (text editor). The > output that i get is (where t4.py is the name of the file): > > [root at localhost root]# python t4.py > enter number: 6 > [root at localhost root]# > > i.e it takes the input but doesn't print anything. If anybody can > help... Thanx! > Hello, When you run it through the interpreter, then the interpreter "looks" at your definition of f, "understands" it, and continues on. What follows your definition of f? Nothing. In particular, nothing instructs the interpreter to *execute* f. So your problem is not that f is being executed but is not printing anything, but rather that f is not being executed. To do what you want it to do, maybe try the following: #! usr/bin/env/python def f(n): print 'n=',n if n>1: return n*f(n-1) else: print 'end' return 1 if __name__ == '__main__': n = int(raw_input("enter number: ")) f(n) The line (if __name__...) means that if the interpreter is running your module the way you mean here, then it should get the raw input for n, then call f. HTH, Efrat P.S. Note that I changed your f so that it doesn't do input itself. Coupling calculation code with user-interaction code is maybe not so good (IMHO). From vedrandekovic at v-programs.com Fri Jun 22 13:42:56 2007 From: vedrandekovic at v-programs.com (vedrandekovic at v-programs.com) Date: Fri, 22 Jun 2007 10:42:56 -0700 Subject: Promijena imena pythonovim kljucnim rijecima In-Reply-To: References: <1182519691.290422.134390@n60g2000hse.googlegroups.com> Message-ID: <1182534176.036783.125510@u2g2000hsc.googlegroups.com> Ognjen Bezanov je napisao/la: > vedrandekovic at v-programs.com escribi?: > > Hello again, > > > > Thanks for everything previously, I was change the grammar and Lib/ > > keyword.py, now > > Python recognize "koristiti" as a keyword, but that is not enough: > > > > when I write in my python shell: > > > >>>> koristiti os # "koristiti" get keyword "color", but I get error: > > > > File "", line 1 > > koristi os > > ^ > > SyntaxError: invalid syntax > > > > and now, when I write: > > > >>>> import os # "import" don't get keyword "color" but still working > > > > > > > > > > Please help me, thanks!!!!!!!!!!!!!!!! > > > > Sorry, but I am having some trouble understanding what exactly you are > trying to do. > > Mozda bi bilo lakse da objasnis na neki drugi jezik, sta mislis o tome? > > Ogi. Pozdrav, (Hrvatski) Pokusavam napraviti nesto kao "programski jezik" tj. program za 3D modeliranje kodom, u tom programu zelim sve kljucne rijeci iz programskog jezika Python ali i preimenovati kao svoje npr. kada korisnik u mom programu upise: >>> koristiti os ja zelim da moj program to procita kao " import os" ja sam u file-u Lib/keywords.py zamijenio kljucnu rijec s "koristiti",sada python "koristiti" prepoznaje kao kljucnu rijec, a "import" ne.Sada kada napisem: >>> import os # i dalje je sve uredu samo sto import ne "dobije" boju >>> koristiti os # a kod ovoga koristiti "dobije" boju kljucne rijeci ali ja dobim gresku: SyntaxError: invalid syntax Molim vas pomoc s ovim se mucim vec mjesec dana,pozdrav i HVALA!!!!!!!!!!!!!!!!! From jadamson at partners.org Fri Jun 22 12:11:25 2007 From: jadamson at partners.org (Joel J. Adamson) Date: Fri, 22 Jun 2007 12:11:25 -0400 Subject: The Modernization of Emacs References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182344981.372713.298580@w5g2000hsg.googlegroups.com> <1182370884.853838.321440@c77g2000hse.googlegroups.com> <2jpok4-ajt.ln1@zoogz.gregorie.org> Message-ID: <87645gj7f6.fsf@W0053328.mgh.harvard.edu> Martin Gregorie writes: > Bjorn Borud wrote: > Yep, and the same people think a command line is to be avoided at all > costs. "I mean, its so /last century/ and you can't do anything useful > with it anyway". Funny ;) It's funny that people consider typing commands to be "old-fashioned" because pointing with a mouse is the stone-age device; typing was only invented in the 19th century ;) Xerox PARC (not Apple nor MIcrosoft) excelled in helping computers fit in to how people already lived, not the other way around. Joel -- Joel J. Adamson Biostatistician Pediatric Psychopharmacology Research Unit Massachusetts General Hospital Boston, MA 02114 (617) 643-1432 (303) 880-3109 A webpage of interest: http://www.gnu.org/philosophy/sylvester-response.html From gagsl-py2 at yahoo.com.ar Thu Jun 21 17:14:22 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 21 Jun 2007 18:14:22 -0300 Subject: Split file into several and reformat References: <1182404738.467a1082458f7@webmail.aapt.net.au> Message-ID: En Thu, 21 Jun 2007 02:45:38 -0300, escribi?: > I want to take read an input file (sels.txt) that looks like: > > Begin sels > sel1 = {1001, 1002, 1003, ... > ... > 1099} > > sel2 = {1001, 1008, 1009 ... > ... > 1299} > End sels > > And turn it into an output file for each of the "sels" in the input > file, i.e > sel1.txt: > > L1001 > L1002 > L1003 > ... > L1099 - You could ignore the begin and end lines; the important delimiters appear to be { and } - Repeat: - read lines until you find a { - extract whatever is at the left of = as the "sel" name; keep whatever is at the right of the { as the first line of data - keep reading more lines until you find a } - split each of those lines on every "," to get your output items - write the output file, you are done with one "sel" - Keep going until end of input file. Some tips: - You can iterate along the lines in a file using for line in some_file: .... but perhaps in this case it may be more convenient to use some_file.readline() - The expression: "x" in line, tests if line contains any "x" - You will find the string methods useful: http://docs.python.org/lib/string-methods.html In particular: find, split, strip, partition look promising in this case. -- Gabriel Genellina From mblume at socha.net Wed Jun 6 09:13:27 2007 From: mblume at socha.net (Martin Blume) Date: Wed, 6 Jun 2007 15:13:27 +0200 Subject: Need a Little Help on Tkinter and Python References: Message-ID: <4666b2f8$0$23408$5402220f@news.sunrise.ch> "W. Watson" schrieb > I have about a 1600 line Pythron program I'd like to > make some simple mods to, but have really just a nodding > acquaintance with Python and Tkinter. > [...] > Let's change that. > The book "Learning Python" from O'Reilly is excellent. If you are into scientific programming, the book "Python Scripting for Computational Science" by Hans Petter Langtangen from Springer is useful. HTH Martin From josiah.carlson at sbcglobal.net Sat Jun 9 16:21:21 2007 From: josiah.carlson at sbcglobal.net (Josiah Carlson) Date: Sat, 09 Jun 2007 13:21:21 -0700 Subject: Hooking exceptions outside of call stack In-Reply-To: References: Message-ID: Warren Stringer wrote: > Here is what I would like to do: > > #------------------------------------------------------------ > a = Tr3() # implements domain specific language > a.b = 1 # this works, Tr3 overrides __getattr__ > a.__dict__['b'] = 2 # just so you know that b is local > a[b] = 3 # I want to resolve locally, but get: > > Traceback (most recent call last): ... > exec cmd in globals, locals ... > NameError: global name 'b' is not defined > #------------------------------------------------------------ Note that your a[b]=3 is the same as '__ = b;a[__]=3' You get that exception because b is not a bound name in the namespace you are currently using. In order to get what you want, you will either need to use a['b'] = 3, a.b = 3, or a method that I refuse to describe to you. > This is intended for production code. The reason I refuse to describe to you the method that could 'solve' your particular problem is because it would be very difficult to differentiate between what you *want* to happen, and actual errors, which would make production code *very* difficult to get right. As an alternative to a['b'], you could use a[Z.b], for an object Z: class Z: def __getattr__(self, a): return a Z = Z() Which will have much less potential for destroying the maintainability and testability of your production code than hooking any trace function. - Josiah From warren at muse.com Sat Jun 2 14:47:00 2007 From: warren at muse.com (Warren Stringer) Date: Sat, 2 Jun 2007 11:47:00 -0700 Subject: c[:]() In-Reply-To: <003701c7a543$57b09290$240110ac@Muse> References: <1180504190.055427.173610@h2g2000hsg.googlegroups.com><135tv1bjqgbmsc9@corp.supernews.com> <9qudnbFRU9QHJsLbnZ2dnUVZ_rKvnZ2d@speakeasy.net><005f01c7a471$6f4b8b30$240110ac@Muse><6faf39c90706012146l551dfe60o6358f48dd5127505@mail.gmail.com> <003701c7a543$57b09290$240110ac@Muse> Message-ID: <003901c7a546$679a55d0$240110ac@Muse> Oops, forgot to cut and paste the point, to this: > > - there is no Python error for "you > > cannot do this with this object, but you can do it with other objects > > of the same type". > > Yes there is: > > #------------------------ > def yo(): print "yo" > def no(): print blah > yo() > no() > > Starting Python debug run ... > yo > Traceback (most recent call last):... > NameError: global name 'blah' is not defined > #------------------------ The point is that if the object is ill formed, then you get a traceback regardless. But, as this is an addendum to the other post, please read that first. Now, I really am out of here. From DustanGroups at gmail.com Fri Jun 15 17:17:24 2007 From: DustanGroups at gmail.com (Dustan) Date: Fri, 15 Jun 2007 21:17:24 -0000 Subject: a_list.count(a_callable) ? In-Reply-To: <1181929975.491931.3200@o11g2000prd.googlegroups.com> References: <1181850818.567840.251090@x35g2000prf.googlegroups.com> <1181853479.914070.217270@i13g2000prf.googlegroups.com> <1181855184.511137.100870@z28g2000prd.googlegroups.com> <1181916937.648267.163070@z28g2000prd.googlegroups.com> <1181920645.597497.133930@m36g2000hse.googlegroups.com> <1181929975.491931.3200@o11g2000prd.googlegroups.com> Message-ID: <1181942244.992149.298380@o61g2000hsh.googlegroups.com> On Jun 15, 12:52 pm, Ping wrote: > On 6 15 , 11 17 , Dustan wrote: > > > > > On Jun 15, 9:15 am, Ping wrote: > > > > > sum(1 for i in a_list if a_callable(i)) > > > > > -- > > > > Carsten Haesehttp://informixdb.sourceforge.net > > > > This works nicely but not very intuitive or readable to me. > > > > First of all, the generator expression makes sense only to > > > trained eyes. Secondly, using sum(1 ...) to mean count() > > > isn't very intuitive either. > > > Then wrap it in a function: > > def count(a_list, a_function): > > return sum(1 for i in a_list if a_function(i)) > > > And call the function. You can also give it a different name (although > > I can't think of a concise name that would express it any better). > > Hmm... This sounds like the best idea so far. It is efficient both > in memory and time while exposes an easy-to-understand name. > I would name the function count_items though. > > n = count_items(a_list, lambda x: x > 3) # very readable :) Although that particular example would be more efficient inlined, because of the additional time spent creating the lambda function in your count_items call. sum(1 for i in a_list if i > 3) From Eric_Dexter at msn.com Fri Jun 22 00:05:36 2007 From: Eric_Dexter at msn.com (Eric_Dexter at msn.com) Date: Thu, 21 Jun 2007 21:05:36 -0700 Subject: subprocess.popen question In-Reply-To: References: <1182353267.200998.43900@w5g2000hsg.googlegroups.com> <1182380572.235876.113160@n2g2000hse.googlegroups.com> <1182389286.706352.64780@o61g2000hsh.googlegroups.com> Message-ID: <1182485136.821993.315710@o11g2000prd.googlegroups.com> On Jun 21, 1:22 am, "Gabriel Genellina" wrote: > En Wed, 20 Jun 2007 22:28:06 -0300, Eric_Dex... at msn.com > escribi?: > > > > > > > On Jun 20, 7:50 pm, "Gabriel Genellina" > > wrote: > >> En Wed, 20 Jun 2007 20:02:52 -0300, Eric_Dex... at msn.com > >> escribi?: > >> > On Jun 20, 1:46 pm, "Gabriel Genellina" > >> > wrote: > > >> >> cmd = ["gawk", "-f", "altertime.awk", "-v", "time_offset=4", "-v", > >> >> "outfile=testdat.sco", "i1.sco"] > >> >> Now, what do you want to do with the output? Printing it line by > >> line? > >> >> output = subprocess.Popen(cmd, > >> stdout=subprocess.PIPE).communicate()[0] > >> >> lines = output.splitlines() > >> >> for line in lines: > >> >> print line > > >> > C:\dex_tracker\pipe1.py > >> > Traceback (most recent call last): > >> > File "C:\dex_tracker\pipe1.py", line 14, in > >> > last_line = subprocess.Popen([cmd], > >> > stdout=subprocess.PIPE).communicate()[0] > >> > File "C:\Python25\lib\subprocess.py", line 593, in __init__ > >> > errread, errwrite) > >> > File "C:\Python25\lib\subprocess.py", line 793, in _execute_child > >> > startupinfo) > >> > WindowsError: [Error 2] The system cannot find the file specified > >> > Script terminated. > > >> > I can write it out as a batch file and then run it but that is a messy > >> > hack.. > > >> If cmd is a list of arguments, like the example above, you should use > >> subprocess.Popen(cmd,...) (like the example above, too). > > > I had cut and pasted the example in to get that error... could it be > > a problem with ms windows??? (I am at a library computer befour work > > so that ended my testing) > > Note the call to subprocess.Popen- is the first argument [cmd] or cmd? > What do you get with print repr(cmd)? > Do you have gawk installed on that machine too? > > -- > Gabriel Genellina- Hide quoted text - > > - Show quoted text - gawk is installed.. I do fine when I just call gawk I get all the options to use with it but the minute I try to use the options with it I have problems. I have done it with batch files but then I would have to write out a batch file and then run the batch file. seems like more work than I should have to do to use options with a command line program.. I have done this in other cases with os.startfile and other cases and would like to fix it. From hamish at cloud.net.au Thu Jun 7 09:20:40 2007 From: hamish at cloud.net.au (Hamish Moffatt) Date: Thu, 07 Jun 2007 23:20:40 +1000 Subject: Integer division In-Reply-To: <1181210265.809659.87170@i13g2000prf.googlegroups.com> References: <1181207216.890336.99990@r19g2000prf.googlegroups.com> <4667CCBD.2040709@cloud.net.au> <1181210265.809659.87170@i13g2000prf.googlegroups.com> Message-ID: <46680628.3090501@cloud.net.au> jm.suresh at no.spam.gmail.com wrote: > On Jun 7, 2:15 pm, Hamish Moffatt wrote: >> jm.sur... at no.spam.gmail.com wrote: >>> Hello all, >>> I have two integers and I want to divide one by another, and want to >>> get an integer result which is the higher side whenever the result is >>> a fraction. >>> 3/2 => 1 # Usual behavior >>> some_func(3, 2) => 2 # Wanted >>> Any easier solution other than int(math.ceil(float(3)/2)) >> The normal solution is to add (divisor-1) to the dividend before division. >> >> Ie ceil(3/2) = floor((3+(2-1))/2) = 2. Correct. >> But ceil(4/2) = floor((4+(2-1))/2) = 2 also. Correct. > > What about this? > >>>> def div_ceil(a, b): > ... if a%b: > ... return ((a/b)+1) > ... else: > ... return (a/b) Yes, although it's not as short or as fast (probably as my version): def div_ceil(a, b): return ((a+(b-1))/b) Hamish From grue at mail.ru Wed Jun 27 03:20:53 2007 From: grue at mail.ru (Timofei Shatrov) Date: Wed, 27 Jun 2007 07:20:53 GMT Subject: The Modernization of Emacs: terminology buffer and keybinding References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182272495.990807.99110@a26g2000pre.googlegroups.com> <87tzt3ihev.fsf@kobe.laptop> <1182370216.961241.6960@n60g2000hse.googlegroups.com> <85zm2ufjpb.fsf@lola.goethe.zz> <1182372592.803332.288260@u2g2000hsc.googlegroups.com> <1182373919.262388.100740@c77g2000hse.googlegroups.com> <85r6o6fhkb.fsf@lola.goethe.zz> <1182375045.626510.188170@m36g2000hse.googlegroups.com> <1182546050.465987.115740@q19g2000prn.googlegroups.com> <871wg3k8c8.fsf@thalassa.lan.informatimago.com> <1182546979.295368.146110@q19g2000prn.googlegroups.com> <87wsxviqol.fsf@thalassa.lan.informatimago.com> <1182552172.406571.116390@i38g2000prf.googlegroups.com> <1182902824.736206.37010@m36g2000hse.googlegroups.com> Message-ID: <46820f5a.58222469@news.readfreenews.net> On Wed, 27 Jun 2007 00:07:04 -0000, Twisted tried to confuse everyone with this message: >"Stubbornly insisting on being odd" appears to be a particularly >prevalent character flaw among the geeknoscenti. > Oh the irony. -- |Don't believe this - you're not worthless ,gr---------.ru |It's us against millions and we can't take them all... | ue il | |But we can take them on! | @ma | | (A Wilhelm Scream - The Rip) |______________| From mike.klaas at gmail.com Thu Jun 7 18:43:05 2007 From: mike.klaas at gmail.com (Klaas) Date: Thu, 07 Jun 2007 22:43:05 -0000 Subject: Running a process every N days In-Reply-To: <1181255261.648057.184930@x35g2000prf.googlegroups.com> References: <1181255261.648057.184930@x35g2000prf.googlegroups.com> Message-ID: <1181256185.747576.268460@r19g2000prf.googlegroups.com> On Jun 7, 3:27 pm, "danmcle... at yahoo.com" wrote: > What's the best way to run either an entire python process or a python > thread every N days. I'm running Python 2.4.3 on Fedora Core 5 Linux. > My code consists of a test and measurement system that runs 24/7 in a > factory setting. It collects alot of data and I'd like to remove all > data older than 30 days. My ideal solution would be something that > runs in the background but only wakes up to run every few days to > check for old data. google "cron" -Mike From martin at see.sig.for.address Tue Jun 26 07:43:40 2007 From: martin at see.sig.for.address (Martin Gregorie) Date: Tue, 26 Jun 2007 12:43:40 +0100 Subject: The Modernization of Emacs: terminology buffer and keybinding In-Reply-To: <1182808864.211161.155920@u2g2000hsc.googlegroups.com> References: <87tzt3ihev.fsf@kobe.laptop> <1182370216.961241.6960@n60g2000hse.googlegroups.com> <85zm2ufjpb.fsf@lola.goethe.zz> <1182372592.803332.288260@u2g2000hsc.googlegroups.com> <1182373919.262388.100740@c77g2000hse.googlegroups.com> <85r6o6fhkb.fsf@lola.goethe.zz> <1182375045.626510.188170@m36g2000hse.googlegroups.com> <85myyufgwj.fsf@lola.goethe.zz> <1182375528.985142.293900@q69g2000hsb.googlegroups.com> <1182545268.055596.228700@i38g2000prf.googlegroups.com> <1182547318.325617.16370@o11g2000prd.googlegroups.com> <1182657564.912472.55570@g4g2000hsf.googlegroups.com> <1182713541.449966.195970@o61g2000hsh.googlegroups.com> <1182808864.211161.155920@u2g2000hsc.googlegroups.com> Message-ID: Twisted wrote: > > First, I didn't claim the ideal WP was necessarily perfectly WYSIWYG. > Maybe I should have clarified my viewpoint. When it comes to programs that operate on the content of textual documents a word processor is WYSIWYG by definition. Anything else is a text editor. You may have a different view but that's mine. > Your quiet change from discussing word processing to discussing > WYSIWYG is interesting. > See above. We were actually discussing text editors whose formatting capabilities (unless they are syntax-sensitive) are generally limited to line wrapping and auto-indentation. You introduced more complex document reformatting - something that I regard as a capability of word processors rather than text editors. > Programming in role-playing game? And I meant my roguelike-filesystem- > interface suggestion at least partly in jest... > RPG is "Report Generating Program" in the context of programming languages. The RPG language is horrid: its a bastardized, fixed column assembler derivative that's been shoehorned into a typical report generator's processing loop. Even PL/1 and COBOL shine as paragons of programming language design by comparison. > If it's so great, why hasn't it, and why hasn't OS/400 managed to > escape from persistent obscurity? > A fair question. I don't know, but it probably has a lot to do with AIX and the UNIX command shell with its great power but lack of consistency in naming, etc. > In other words, the implementation was a dog. That doesn't refute the > basic concept's validity. > True, but doing better would be really hard because of all the information and context that would need to be associated with every mouse click in case it was needed to record a macro. At best it might make macro recording tedious. At worst it could make the whole GUI unresponsive. -- martin@ | Martin Gregorie gregorie. | Essex, UK org | From len-l at telus.net Sat Jun 23 00:11:15 2007 From: len-l at telus.net (Lenard Lindstrom) Date: Sat, 23 Jun 2007 04:11:15 GMT Subject: Python's "only one way to do it" philosophy isn't good? In-Reply-To: References: <1181368143.874341.273140@r19g2000prf.googlegroups.com> <7x3b0nmkk6.fsf@ruckus.brouhaha.com> Message-ID: Douglas Alan wrote: > "Terry Reedy" writes: > >> "Douglas Alan" wrote in message > >> | > But why is the ability to abstract syntax good? > >> | It allows the community to develop language features in a modular way >> | without having to sully the code base for the language itself. > >> Anyone can write modules, experimental or otherwise, without touching the >> code base for any particular implementation. > >> For those whose know one of the implementation languages, source code >> control systems allow one to do experiments on branches without 'sullying' >> the trunk or impeding the development thereof. > > When I said "without having to sully the code base", I meant that one > can implement a language feature for the target language as a loadable > module written entirely within the language itself, and without having > to understand anything particularly deep or specific about the language > implementation details. > > I.e., I could write a new object system for Lisp faster than I could > even begin to fathom the internal of CPython. Not only that, I have > absolutely no desire to spend my valuable free time writing C code. > I'd much rather be hacking in Python, thank you very much. > CPython's class system is independent of the interpreter proper. That is how two class systems, classic and new-style, can exist in the same language. Both class types implement hooks into attribute lookup. By providing __getattr__/__getattribute__, __setattr__, and __delattr__ methods one can effectively alter object behavior, such as method resolution. And metaclasses change the nature of class statements. Novel objects systems, such as prototypes, are possible. So the Python language provides more of a framework for handling objects rather than defining an actual object model. Python is the syntax; objects define the behavior. Finally, with the advent of Python 2.2, built-in types like int and list became far more class like. Subclassing became possible. The object types were reworking at the interpreter level. No amount of macro wizardry could have done it. >> One of the goals of the PyPy project was to allow people to experiment with >> syntax extensions in Python itself. (But I don't know how easy that is >> yet.) > > PyPy sounds like a very interesting project indeed! > PyPy uses aspects without needing macros. >> But I think that overall the problem of designing new syntax is more >> in the design than the implementation. Anything new has to be >> usable, readable, not clash too much with existing style, not >> introduce ambiguities, and not move the extended language outside >> the LL(1) [I believe that is right] subset of CFLs. > > People (myself included) haven't had much trouble implementing nice > and useful macro packages for Lisp. Admittedly, it's a harder problem > for a language that doesn't have a Lisp-like syntax. I believe that > Dylan has macros without having a Lisp-like syntax, but Dylan is > really a dialect of Lisp, only with a more traditional Algol-like > syntax veneered onto it. My guess is that a macro developer for Dylan > would have to be familiar with an underlying hidden intermediate Lisp > syntax. (Though I'm just really just spouting that guess out of my > butt.) > Dylan macros do not use an "underlying hidden intermediate Lisp syntax". They are language-based, doing pattern matching on Dylan language elements ( http://www.opendylan.org/books/dpg/db_329.html ). > A few years back, I designed a somewhat Python-like language with a > macro facility for a class on dynamic languages and their > implementations. I didn't implement it, however, and I doubt that > I'll have time to get around to it in this lifetime. > It's easy to say Python would benefit from macros. Macros have solved problems in Common Lisp and Scheme and so it is assumed they can do the same for Python. But no concrete suggestions are made in this thread. No specific macro mechanism is put forward for Python. No example is given on how to implement some Python feature with it. No point has been identified in the Python compiler chain for macro expansion. When this thread turned to the topic of macros I did an Internet search for information on macros relevant to Python. Dylan's macros look promising. The Python-inspired language Converge has macros ( http://convergepl.org/ ). Michael Hudson's Bytecodehacks package supports limited Python macros ( http://bytecodehacks.sourceforge.net/bch-docs/bch/module-bytecodehacks.macro.html ). There is also the __macro__ package, which I still have on my computer, but I cannot find its home page. The __macro__ package simply allows text substitution of source code at module import time. The bytecodehack.macro module lets one define what amounts to inlined functions. IMO neither package represents a productive macro system. And I could find no other attempts to take Python macros beyond wishful thinking. So until some solid proposal for Python macros is put on the table any discussion of their merits is unproductive. I can suggest though that procedural macros are a natural starting point given the runtime nature of class and function creation. -- Lenard Lindstrom From natefico at gmail.com Thu Jun 28 07:46:13 2007 From: natefico at gmail.com (swordofrue) Date: Thu, 28 Jun 2007 11:46:13 -0000 Subject: Evolution of a pythonistas! Message-ID: <1183031173.173821.104990@e16g2000pri.googlegroups.com> Hello everyone, I just started reading the python documentation and then I got to thinking. How does a pythonistas evolve? What kind of natural evolution does a pythonistas endure? The reason why I wonder is simply because I have no idea of where I should be going. What kind of goals should I set? Any stories related to your own evolution as a python programming would most likely help give me some direction in this vast world of python. Thanks, --Swordofrue From hg at nospam.org Sat Jun 30 21:13:45 2007 From: hg at nospam.org (hg) Date: Sat, 30 Jun 2007 20:13:45 -0500 Subject: Python app as a Display Manager Message-ID: Hi, I asked that question a while back ... and then gave up: I want to write a simple display manager (*nix / X11) in Python. I'm going through lots of documentation as well as the code of XDM. 1) I currently understand that the "X11 Intrinsics" are what I need to master in order to get there. 2) Also, it seems that The Python app needs to adjust to X11 callbacks ... although I will use TKinter or another Framework to actually do the drawing. I feel at this stage that what I miss is: assuming I manage to get a python-based dialog box started automatically from init.rc (instead of xdm, gdm, ...): how do I start an X11 session with the user/pw information retrieved ... + set the correct *nix environment variables. Can you direct me some info / give me a clue ? Many thanks, hg From toby at tobiah.org Thu Jun 14 16:47:07 2007 From: toby at tobiah.org (Tobiah) Date: Thu, 14 Jun 2007 13:47:07 -0700 Subject: Serialization across languages? Message-ID: <46719c90$0$10851$88260bb3@free.teranews.com> I want to do SOAP like calls from a device who's libraries don't include SOAP. I'm thinking of using simple HTTP posts, but I'm going to want to send arrays and hashes. First, what do I need to be aware of when sending arbitrary data by a POST, and Second, is there a universally supported version of what python can do with pickle? I mostly need python and PHP, but perl would be nice too. Thanks, Toby -- Posted via a free Usenet account from http://www.teranews.com From mcl.office at googlemail.com Fri Jun 1 10:57:36 2007 From: mcl.office at googlemail.com (mosscliffe) Date: Fri, 01 Jun 2007 07:57:36 -0700 Subject: Cookie: Not understanding again In-Reply-To: <1180709394.151350.103200@q69g2000hsb.googlegroups.com> References: <1180709394.151350.103200@q69g2000hsb.googlegroups.com> Message-ID: <1180709856.807814.152480@p77g2000hsh.googlegroups.com> On 1 Jun, 15:49, mosscliffe wrote: > I have the following code, which I thought would create a cookie, if > one did not exist and on the html form being sent to the server, it > would be availabe for interrogation, when the script is run a second > time. > > It seems to me there is something basic missing in that I should need > to tell the server I am sending a cookie, but all the docs I have read > imply it is done automatically, if one creates a 'Cookie.SimpleCookie' > > I know my understanding is poor of web server logic, but if anyone can > help, I will be most grateful. > > This may be more to do with Web Server behaviour than python > programming, but surely there is a way of doing this in python. > > Richard > > #!/usr/bin/env python > > import Cookie, os > import cgitb;cgitb.enable() > > def getCookie(): > c = Cookie.SimpleCookie() > if 'HTTP_COOKIE' in os.environ: > c.load(os.environ['HTTP_COOKIE']) > print "Found a Cookie", c, "
      " > c['mysession'].value += 1 > print "
      " > return c > else: > c['mysession'] = 45 > print "No Cookie Found so setting an initial value for a Cookie", c > print "
      " > return c > > if __name__ == '__main__': > > print "Content-type: text/html\n\n" > myCookie = getCookie() > #Print all Environment variables > for k, v in os.environ.items(): > print k, "=", v, "
      " > print "
      " > > print """ >
      > >
      > """ Forgot to add running python 2.3.4 on a hosted Apache server From xah at xahlee.org Tue Jun 19 13:04:01 2007 From: xah at xahlee.org (Xah Lee) Date: Tue, 19 Jun 2007 10:04:01 -0700 Subject: The Modernization of Emacs: technically superior In-Reply-To: <1182093200.598418.218620@e9g2000prf.googlegroups.com> References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> Message-ID: <1182272641.777476.195600@z28g2000prd.googlegroups.com> Here are some Frequently Asked Questions about The Modernization of Emacs. They are slightly lengthy, so i've separated each item per post. The whole article can be found at http://xahlee.org/emacs/modernization.html ------------ Q: Emacs's ways are technically superior. It should not change. A: Emac's user interface, when compared to modern software application's user interface, is complex and unusual, however, there's no basis whatsoever of it being actually a superior design with regards to any sensible metrics. (in fact, much of emacs's user interface are due to historical reasons. That is, how computers are in 1980s.) For example, let's consider emacs's system of keyboard shortcuts. For a keyboard shortcut system, we might judge its quality based on several aspects. Here are some examples of consideration: * Is it easy to learn? (is it familiar to most people?) * Is it easy to type? (is most frequently used commands easy to type?) * Is it easy to remember? * Are more frequently used commands have the easier-to-type shortcuts that less frequently used commands? * Are most frequently used commands all have a keyboard shortcut? * Can the shortcut system somehow be consistent and extensible to cover other user defined shortcuts? Emacs's keyboard shortcuts system, somewhat satisfies the last aspect, but do very bad with respect to all the others. Emacs keyboard shortcuts are perhaps one of the most difficult to learn among software, and is also one of the most difficult to remember. The worst aspect of emacs's keyboard shortcuts, is that it is ergonomically painful. (Many emacs-using programer celebrities have injured their hands with emacs. (e.g. Richard Stallman, Jamie Zawinski), and emacs's Cntl-x keyboard and Meta-x combinations are most cited as the major turn-off to potential users among programers) Computer keyboard is a hardware interface, and the mapping of commands to the key press combinations can be considered from a Operation Research point of view. The keyboard hardware itself can be designed with consideration of ergonomics (that's why we have split and curved keyboards), but consideration of what functions to map to what key presses is also non-trivial if the software has large number of functions or if the software is mission critical. Think of it this way, consider a airplane cockpit, filled with knobs, dials, buttons, and switches. Now, if your job is to map the airplane control functions to these switches, what are the things to consider for a optimal map? If we take careful consideration on creating a keyboard shortcut system for emacs, it is actually easy to create a system that are purely superior in some technical sense than the ad-hoc Emacs's ways. Aside from keyboard shortcuts system, Emacs's other user interfaces are also questionable. For example, one major aspect of emacs operation is that it uses a single window for multiple purposes and files. Emacs is this way not because of a design decision, but rather due to historical reasons. Computer resources in the 1980s are very limited. When emacs is around, graphical system of showing ?windows? is not practically available, and the emacs's method of using the screen (the textual-based-monitor) for presenting multiple tasks (?buffers?) is actually a very advanced user interface design not available in software of that era. When graphical systems becomes practical in the 1990s, drawing a window takes a lot memory, and opening multiple windows is slow and inpractical. Modern software interface (say, post 2000) usually uses one window per file (or task), and or show a tab if multiple task is to be represented in a single window. However, in general, emacs doesn't provide the tabs visual clue and still remained its old way of using a single window for all files and tasks as its standard operation. As far as user interface design is considered per se with respect to today's computing standards, the emacs's way is inferior because it is less intuitive. Arguably, emacs's operation methods may be more efficient for expert users. 20 years ago, efficiency for expert users may out weight the ease of use for majority of average users. But in today computing era, computers are standard tools in every household, efficiency and ease of use for general users is as important for professional users. Even for professional users, it is openly questionable that emacs's ways of operation induced by its default user interface allows faster or more efficient operation than a user interface based on modern software conventions. Xah xah at xahlee.org ? http://xahlee.org/ From spe.stani.be at gmail.com Sat Jun 23 07:46:26 2007 From: spe.stani.be at gmail.com (SPE - Stani's Python Editor) Date: Sat, 23 Jun 2007 04:46:26 -0700 Subject: subprocess.popen question In-Reply-To: References: <1182353267.200998.43900@w5g2000hsg.googlegroups.com> <1182380572.235876.113160@n2g2000hse.googlegroups.com> <1182389286.706352.64780@o61g2000hsh.googlegroups.com> <1182485136.821993.315710@o11g2000prd.googlegroups.com> <1182517729.509639.254860@m36g2000hse.googlegroups.com> Message-ID: <1182599186.807361.293060@w5g2000hsg.googlegroups.com> On Jun 23, 5:35 am, "Gabriel Genellina" wrote: > En Fri, 22 Jun 2007 10:08:49 -0300, Eric_Dex... at msn.com > escribi?: > > > I seemed to have it working sorta when I run it and save the results I > > am noticing that inspeit spaces correctly but when I save it to a > > file I can open it in wordpad there is only one line. when I open in > > up in WinXound (A csound editor) it is double spaced. if I do it in a > > batch file the output file is spaced correctly.. when I do splitlines > > it is giving me one charecter down the page as output.. Do I need to > > do something or can I do something to put an end of line charecter in > > the output?? > > Try > > print repr(your_data) > > to see exactly what you got. > > -- > Gabriel Genellina Did you take in account that line endings on Windows are '\r\n' and not '\n'? Stani -- http://pythonide.stani.be From sc0rp at hot.pl Fri Jun 22 17:30:31 2007 From: sc0rp at hot.pl (Jacek Trzmiel) Date: Fri, 22 Jun 2007 23:30:31 +0200 Subject: regular expression concatenation with strings In-Reply-To: <1182546637.032673.106920@a26g2000pre.googlegroups.com> References: <1182543519.337279.25800@z28g2000prd.googlegroups.com> <1182546637.032673.106920@a26g2000pre.googlegroups.com> Message-ID: <467C3F77.3000703@hot.pl> Hi, oscartheduck wrote: > I noticed a small error in the code (you referenced extension, which > you had renamed to filenameRx), and when I corrected it I received the > original error again. I haven't had PIL installed, so I just commented out im.* calls for test. Just change: im.save(file + ".thumbnail." + extension) to: im.save(file + ".thumbnail" + ext) > What was it you were trying to do to solve the > problem, though? You can't use glob with regexps. Instead use os.listdir() to get filenames and then rx.match() to find ones that does match the pattern. Best regards, Jacek. From bdesth.quelquechose at free.quelquepart.fr Thu Jun 28 03:08:16 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 28 Jun 2007 09:08:16 +0200 Subject: PEP 3107 and stronger typing (note: probably a newbie question) In-Reply-To: References: <1182369568.941307.316260@p77g2000hsh.googlegroups.com> <5dveb4F360un0U1@mid.individual.net> <467a9209$0$22165$426a74cc@news.free.fr> <1182858785.886469.93060@n60g2000hse.googlegroups.com> <46824d8d$0$2324$426a74cc@news.free.fr> Message-ID: <4682eddc$0$23164$426a74cc@news.free.fr> John Nagle a ?crit : > Bruno Desthuilliers wrote: > >> harri a ?crit : > > >> Indeed - static typing is for compilers, not for programmers. > > > Actually, static typing is for detecting errors before the > program is run. bruno at bibi ~ $ cat toto.c #include int main(void) { char *toto = (char *)42; printf("%s", toto); return 0; } bruno at bibi ~ $ gcc -ototo toto.c bruno at bibi ~ $ ./toto Erreur de segmentation bruno at bibi ~ $ You said ? From kyosohma at gmail.com Mon Jun 25 12:14:19 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Mon, 25 Jun 2007 09:14:19 -0700 Subject: How to save initial configuration? (program installation) In-Reply-To: <1182787082.740937.98590@n2g2000hse.googlegroups.com> References: <1182783746.718276.209460@w5g2000hsg.googlegroups.com> <1182784231.530101.258640@q75g2000hsh.googlegroups.com> <1182784412.829377.265320@q75g2000hsh.googlegroups.com> <1182787082.740937.98590@n2g2000hse.googlegroups.com> Message-ID: <1182788059.409235.243380@m36g2000hse.googlegroups.com> On Jun 25, 10:58 am, Jason Zapman II wrote: > On Jun 25, 11:37 am, Steve Holden wrote: > > > The traditional choices are the registry for Windows, and the /etc > > subtree for the various, almost uncountable, flavors of Unix and > > nixalikes. You're right, it's much more difficult per-system than > > per-user, since there are so many conventions. > > I forgot to mention that this is for Unix environments, so the > registry isn't an option, unfortunately (never thought I'd say > that... ;-) ). > > Is there anything in the distutils.* stuff that would be useful? This > isn't going to be a python package (it's a standalone program). > > --Jason Well, I don't know what your user file does, but couldn't you create a .ini type file to hold the user's choice for the other file's location and save the ini to the current working directory? Something like this: usersChosenPath = /usr/Path/to/Config Kind of redundant, but I would think it would still work. Mike From steven.bethard at gmail.com Wed Jun 20 03:09:33 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 20 Jun 2007 01:09:33 -0600 Subject: caseless dictionary howto ? In-Reply-To: References: <4dc64$46782a84$d443bb3a$4629@news.speedlinq.nl> <5c1e3$4678448d$d443bb3a$1513@news.speedlinq.nl> Message-ID: Gabriel Genellina wrote: > En Tue, 19 Jun 2007 19:40:10 -0300, Steven Bethard > escribi?: > >> Stef Mientki wrote: >>> Evan Klitzke wrote: >>>> On 6/19/07, Stef Mientki wrote: >>>>> >>>>> I need to search a piece of text and make all words that are equal >>>>> (except their case) also equal in their case, based on the first >>>>> occurrence. > >> ... def __setitem__(self, key, value): >> ... self._dict[key.lower()] = value >> ... if key not in self._original_keys: >> ... self._original_keys[key.lower()] = key >> ... >> >> Note that because I store the first form encountered for every key, I >> can always use the lower-case version to retrieve the "original string". > > As written, it stores the last used spelling; a small change is required > to get the intended behavior: > >> ... def __setitem__(self, key, value): >> ... self._dict[key.lower()] = value >> ... if key.lower() not in self._original_keys: >> ... self._original_keys[key.lower()] = key Good catch. Thanks! Steve From marcin.ciura at poczta.NOSPAMonet.pl Sun Jun 24 17:14:00 2007 From: marcin.ciura at poczta.NOSPAMonet.pl (Marcin Ciura) Date: Sun, 24 Jun 2007 23:14:00 +0200 Subject: Accessing variable from a function within a function In-Reply-To: References: Message-ID: Nathan Harmston wrote: > Unfortunately this doesnt work since a,a1,b,b1 arent declared in the > function. Is there a way to make these variables accessible to the > euclid function. Or is there a better way to design this function? The canonical recommendations are: use attributes of the inner function or one-element lists as writable variables visible in the outer function. Another possibility is to modify the bytecode of the functions by an appropriate decorator. See http://www-zo.iinf.polsl.gliwice.pl/~mciura/software/expose.py (you'll need the byteplay module by Noam Raphael to make it work). Marcin From peter.mosley at talk21.com Wed Jun 20 03:51:09 2007 From: peter.mosley at talk21.com (peter) Date: Wed, 20 Jun 2007 00:51:09 -0700 Subject: Python and (n)curses In-Reply-To: References: <1182211133.956524.160020@g4g2000hsf.googlegroups.com> <87y7igzapo.fsf@benfinney.id.au> <1182246189.210723.16280@w5g2000hsg.googlegroups.com> Message-ID: <1182325869.237652.157800@c77g2000hse.googlegroups.com> > > For me, introducing similar commands in Python would be by far the biggest single improvement that could be made to the language. > If it should be done, it should be done as a compatible subset of > curses, IMHO. It has such a long history as the standard "GUI toolkit" But curses doesn't run under Windows - thats the whole point! From gundalav at gmail.com Sat Jun 30 14:01:31 2007 From: gundalav at gmail.com (Gundala Viswanath) Date: Sun, 1 Jul 2007 02:01:31 +0800 Subject: Where to find Python Enthought Edition for Linux? Message-ID: <73f827b50706301101p25a44de3te5fda6e0af94bd94@mail.gmail.com> Dear all, Is there any way I can download Python 2.4.3 Enthought Edition for Linux. AFAIK, from your website I can only find Enthought Tool Suite for Linux, which is not exactly what I want. The Enthought Edition is truly incredible. I want to re-place my original Python in my Linux box with Enthought Edition. This really save me trouble installing all those packages on my own. Hope to hear from you again. -- Gundala Viswanath From gagsl-py2 at yahoo.com.ar Tue Jun 19 22:46:59 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 19 Jun 2007 23:46:59 -0300 Subject: How can I know the name of "caller" References: <1182285024.048003.310120@n2g2000hse.googlegroups.com> <1182287200.071007.112170@g4g2000hsf.googlegroups.com> Message-ID: En Tue, 19 Jun 2007 18:06:40 -0300, billiejoex escribi?: > On 19 Giu, 22:50, Stefan Sonnenberg-Carstens > wrote: >> billiejoex schrieb: >> >> >> > ...(if it is possible) how can I get, from method "called", the name >> > of function/method that called it (in this case "caller")? >> >> inspect.stack is your friend ;-)- Nascondi testo tra virgolette - >> > Thank you man. That's what I was searching for. > This should be production code. Is insepct.stack fast enough? > Considering that I'd have to use inspect.stack inside a 'while' > statement looping different times, I wouldn't slow down my application. A faster way is to use sys._getframe(1).f_code.co_name But it doesn't feel good for production code... can't you find a different approach? -- Gabriel Genellina From me at privacy.net Fri Jun 8 15:48:46 2007 From: me at privacy.net (Mark Carter) Date: Fri, 08 Jun 2007 20:48:46 +0100 Subject: Working with fixed format text db's In-Reply-To: References: Message-ID: <4669b2a6$0$31676$db0fefd9@news.zen.co.uk> Neil Cerutti wrote: > The underlying problem, of course, is the archaic flat-file > format with fixed-width data fields. Even the Department of > Education has moved on to XML for most of it's data files, :( I'm writing a small app, and was wondering the best way to store data. Currently the fields are separated by spaces. I was toying with the idea of using sqlite, yaml or json, but I think I've settled on CSV. Dull, but it's easy to parse for humans and computers. From needpassion at gmail.com Thu Jun 14 15:03:35 2007 From: needpassion at gmail.com (mike) Date: Thu, 14 Jun 2007 12:03:35 -0700 Subject: How can I capture all exceptions especially when os.system() fail? Thanks In-Reply-To: References: <1181782036.646379.28510@g37g2000prf.googlegroups.com> Message-ID: <1181847815.105463.169740@n15g2000prd.googlegroups.com> On Jun 14, 2:55 am, Michael Hoffman wrote: > Gabriel Genellina wrote: > > En Wed, 13 Jun 2007 21:47:16 -0300, mike escribi?: > > >> Following piece of code can capture IOError when the file doesn't > >> exist, also, other unknown exceptions can be captured when I press > >> Ctrl-C while the program is sleeping(time.sleep). Now the question is: > >> when I run the non-exist command, the exception cannot be captured. > > >> So far so good, then I changed the code to run a non-exist command > >> "wrong_command_test"(commented the open and sleep lines), then the > >> script printed: > >> sh: wrong_command_test: command not found > >> well Done > > > That's because it is not an exception, it is an error message coming > > from your shell, not from Python. > > Of course if you use subprocess.check_call() instead of os.system(), it > will become an exception (CalledProcessError). > -- > Michael Hoffman Really helps. Thanks Michael From gagsl-py2 at yahoo.com.ar Fri Jun 22 04:52:20 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 22 Jun 2007 05:52:20 -0300 Subject: string formatter %x and a class instance with __int__ cannot handle long References: <2ba587f0706210136p54363e04y974577aefdfef00b@mail.gmail.com> Message-ID: En Thu, 21 Jun 2007 05:36:42 -0300, Kenji Noguchi escribi?: > I confirmed that "%08x" % int(y) works. And yes, I'm hoping so. > It actually works that way if the v is less than or equal to 0x7ffffffff. > >> It is a bug, at least for me, and I have half of a patch addressing it. >> As a workaround, convert explicitely to long before formatting. > > I'm interested in your patch. What's the other half still missing? As you have seen, PyString_Format doesn't handle well objects that can be converted to long but are not longs themselves; I've modified that function, but PyUnicode_Format has a similar problem, that's "the other half". Maybe this weekend I'll clean those things and submit the patch. -- Gabriel Genellina From eopadoan at altavix.com Sat Jun 30 11:15:26 2007 From: eopadoan at altavix.com (Eduardo "EdCrypt" O. Padoan) Date: Sat, 30 Jun 2007 12:15:26 -0300 Subject: PEP 3107 and stronger typing (note: probably a newbie question) In-Reply-To: <468567b3$0$26422$426a74cc@news.free.fr> References: <1182448413.966430.299590@m36g2000hse.googlegroups.com> <7xhcp0fom4.fsf@ruckus.brouhaha.com> <87tzt0tgol.fsf@benfinney.id.au> <1182533987.715191.159850@m36g2000hse.googlegroups.com> <468567b3$0$26422$426a74cc@news.free.fr> Message-ID: On 6/30/07, Bruno Desthuilliers wrote: > Eduardo "EdCrypt" O. Padoan a ?crit : > > Remember that pure CPython has no different "compile time" and > > runtiime. > > Oh yes ? So what's the compiler doing, and what are those .pyc files ? > (hint: read the doc) Sorry, I surely know that Python has a compile time, I wanted to say somthing like "compile time checks except from syntax". My intention was to show that a *huge* change in the Python interpretation model would be needed to allow what he wanted, but I finished my email too early :P And yes, I readed the docs :) -- EduardoOPadoan (eopadoan->altavix::com) Bookmarks: http://del.icio.us/edcrypt From elpX at adsihqX.com Wed Jun 13 12:48:11 2007 From: elpX at adsihqX.com (Dr. Pastor) Date: Wed, 13 Jun 2007 09:48:11 -0700 Subject: Cretins. Message-ID: <1181753716_51257@sp12lax.superfeed.net> Please do not do business with those cretins who without authorization attaching the following text to my postings: ----== Posted via Newsfeeds.Com - Unlimited-Unrestricted-Secure Usenet News==---- http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ Newsgroups ----= East and West-Coast Server Farms - Total Privacy via Encryption =---- ----== Posted via Newsfeeds.Com - Unlimited-Unrestricted-Secure Usenet News==---- http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ Newsgroups ----= East and West-Coast Server Farms - Total Privacy via Encryption =---- From showell30 at yahoo.com Tue Jun 12 19:11:47 2007 From: showell30 at yahoo.com (Steve Howell) Date: Tue, 12 Jun 2007 16:11:47 -0700 (PDT) Subject: SimplePrograms challenge In-Reply-To: <466F27A3.8000106@gmail.com> Message-ID: <14019.37662.qm@web33508.mail.mud.yahoo.com> --- Steven Bethard wrote: > Steve Howell wrote: > > --- George Sakkis wrote: > >> from itertools import count, ifilter > >> def sieve(): > >> seq = count(2) > >> while True: > >> p = seq.next() > >> seq = ifilter(p.__rmod__, seq) > >> yield p > [snip] > > Is there a way to broaden the problem somehow, so > that > > it can be a longer solution and further down on > the > > page, and so that I can continue to enforce my > > somewhat arbitrary rule of ordering examples by > how > > long they are? > > How about we just comment it better? > > import itertools > > def iter_primes(): > # an iterator of all numbers between 2 and > +infinity > numbers = itertools.count(2) > > # generate primes forever > while True > > # generate the first number from the > iterator, > # which should always be a prime > prime = numbers.next() > yield prime > > # lazily remove all numbers from the > iterator that > # are divisible by prime we just selected > numbers = itertools.ifilter(prime.__rmod__, > numbers) > > I think that's 17-ish, though you could shrink it > down by removing some > of the spaces. No, that's perfect. Do you want me to post it, or do you want the honors? ____________________________________________________________________________________ Bored stiff? Loosen up... Download and play hundreds of games for free on Yahoo! Games. http://games.yahoo.com/games/front From steven.bethard at gmail.com Tue Jun 5 21:00:32 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 05 Jun 2007 19:00:32 -0600 Subject: copying generatrors In-Reply-To: References: <1181087423.361999.324710@o11g2000prd.googlegroups.com> Message-ID: <-JKdnb0ntvytmvvbnZ2dnUVZ_o_inZ2d@comcast.com> Horace Enea wrote: > My example wasn't very good. Here's another try: > > def foo(): > yield 1 > yield 2 > yield 3 > > f = foo() > f.next() > 1 > > g=copy(f) # copy the generator after an iteration > > f.next() > 2 > f.next() > 3 > > g.next() > 2 > > I want to copy the generator's state after one or more iterations. You could use itertools.tee(): >>> def foo(): ... yield 1 ... yield 2 ... yield 3 ... >>> import itertools >>> f = foo() >>> f.next() 1 >>> f, g = itertools.tee(f) >>> f.next() 2 >>> f.next() 3 >>> g.next() 2 >>> g.next() 3 But note that if your iterators get really out of sync, you could have a lot of elements stored in memory. STeVe From NoSpam at Hccnet.nl Fri Jun 29 16:03:12 2007 From: NoSpam at Hccnet.nl (Hans) Date: Fri, 29 Jun 2007 22:03:12 +0200 Subject: win32event.WaitForInputIdle() returns too soon References: <4684330c$0$742$3a628fcd@textreader.nntp.hccnet.nl> Message-ID: <4685657e$0$734$3a628fcd@textreader.nntp.hccnet.nl> "Gabriel Genellina" schreef in bericht news:mailman.184.1183090500.22759.python-list at python.org... > En Thu, 28 Jun 2007 19:15:40 -0300, Hans escribi?: > >> I'm sending keyboard and mouse events to a seperate windows application. >> I use win32event.WaitForInputIdle() before calling e.g. >> win32api.keybd_event() >> However it seems that WaitForInputIdle() returns too soon because some >> of my >> events get lost. Now I'v created my own WaitForInputIdle() which calls > > From the Microsoft docs for WaitForInputIdle: "The WaitForInputIdle > function only works with GUI applications. If a console application calls > the function, it returns immediately, with no wait." > A typical Python script is a console application. > > -- > Gabriel Genellina It would explain my problem. Perhaps I could create a small windows application as interface.. I have to think about it ( and wait, as I currently don't have access to visual C++, nor the MS documentation) Thanks, Hans From http Thu Jun 14 01:10:41 2007 From: http (Paul Rubin) Date: 13 Jun 2007 22:10:41 -0700 Subject: Method much slower than function? References: <1181781612.939800.238890@q19g2000prn.googlegroups.com> <1181795969.141307.94140@i13g2000prf.googlegroups.com> Message-ID: <7xtztbdstq.fsf@ruckus.brouhaha.com> "sjdevnull at yahoo.com" writes: > take virtually the same amount of time on my machine (2.5), and the > non-join version is clearer, IMO. I'd still use join in case I wind > up running under an older Python, but it's probably not a big issue here. You should not rely on using 2.5 or even on that optimization staying in CPython. Best is to use StringIO or something comparable. From aahz at pythoncraft.com Sat Jun 2 16:58:39 2007 From: aahz at pythoncraft.com (Aahz) Date: 2 Jun 2007 13:58:39 -0700 Subject: Python rocks References: <4661700a$0$19261$da0feed9@news.zen.co.uk> <1180807432.351720.123860@p47g2000hsd.googlegroups.com> Message-ID: In article <1180807432.351720.123860 at p47g2000hsd.googlegroups.com>, George Sakkis wrote: > >I had probably stumbled on many/most of the common pitfalls usually >mentioned (e.g. http://www.ferg.org/projects/python_gotchas.html, >http://zephyrfalcon.org/labs/python_pitfalls.html) while learning, but >picked them up easily after the first or second time. Off the top of >my head, two errors that keep coming back even years after are: >- Comparing instances of (semantically) incomparable types (http:// >www.ibm.com/developerworks/library/l-python-elegance-1.html). >Thankfully this will be fixed in Py3k. >- Strings being iterable; unfortunately this will stay in Py3K. I'll repeat the comment I made on python-3000: "...string iteration isn't about treating strings as sequences of strings, it's about treating strings as sequences of characters. The fact that characters are also strings is the reason we have problems, but characters are strings for other good reasons." Thing is, the fact that you can e.g. slice strings just like other sequence types creates the consequence that you can also iterate over strings -- moreover, some of us actually do iterate over strings (though of course we could if necessary create lists/tuples of characters). In the grand scheme of things, I rarely see people running into problems with iterating over strings. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "as long as we like the same operating system, things are cool." --piranha From alikakakhel at yahoo.com Sat Jun 2 19:54:29 2007 From: alikakakhel at yahoo.com (greenflame) Date: Sat, 02 Jun 2007 16:54:29 -0700 Subject: can this be implemented? Message-ID: <1180828469.633454.105970@z28g2000prd.googlegroups.com> First I should start with some introductory comments. When I first learned about programming, I started with BASIC, QBASIC to be more accurate. While I was at that stage, I learned about the INPUT command. I used it abundantly. Ok so now for the actual issue. I would like to implement something like the INPUT command from BASIC. I failed to find something on the python website documentation for beginners. Thank you for your time. From nis at superlativ.dk Tue Jun 12 06:12:41 2007 From: nis at superlativ.dk (=?ISO-8859-1?Q?Nis_J=F8rgensen?=) Date: Tue, 12 Jun 2007 12:12:41 +0200 Subject: for ... else ? In-Reply-To: <1181640889.439145.60020@g37g2000prf.googlegroups.com> References: <1181622331.955264.31610@i38g2000prf.googlegroups.com> <1181640889.439145.60020@g37g2000prf.googlegroups.com> Message-ID: <466e71a0$0$90271$14726298@news.sunsite.dk> exhuma.twn skrev: >> for number in range(10,100): >> for divisor in range(2,number): >> if number % divisor == 0: >> break >> else: >> print number, >> > > Oh my. Would it not be an idea to rename this "else" into a "finally"? > As Gabriel points out, the else-block gets executed after the for loop > exits *normally*. In that case, is the "else" not semantically > misleading? I would surely misunderstand it if I saw it the first time. "finally" would be at least equally confusing IMO, indicating that the code is always called (although this would of course make it a ridiculous construct). /Nis From larry.bates at websafe.com Fri Jun 1 11:51:11 2007 From: larry.bates at websafe.com (Larry Bates) Date: Fri, 01 Jun 2007 10:51:11 -0500 Subject: Using PIL to find separator pages In-Reply-To: References: Message-ID: <4660406F.7070506@websafe.com> Steve Holden wrote: > Larry Bates wrote: >> I have a project that I wanted to solicit some advice >> on from this group. I have millions of pages of scanned >> documents with each page in and individual .JPG file. >> When the documents were scanned the people that did >> the scanning put a colored (hot pink) separator page >> between the individual documents. I was wondering if >> there was any way to utilize PIL to scan through the >> individual files, look at some small section on the >> page, and determine if it is a separator page by >> somehow comparing the color to the separator page >> color? I realize that this would be some sort of >> percentage match where 100% would be a perfect match >> and any number lower would indicate that it was less >> likely that it was a coverpage. >> >> Thanks in advance for any thoughts or advice. >> > I suspect the easiest way would be to select a few small patches of each > image and average the color values of the pixels, then normalize to hue > rather than RGB. > > Close enough to the hue you want (and you could include saturation and > intensity too, if you felt like it) across several areas of the page > would be a hit for a separator. > > regards > Steve Steve, I'm completely lost on how to proceed. I don't know how to average color values, normalize to hue... Any guidance you could give would be greatly appreciated. Thanks in advance, Larry From DPhillips at cybergroup.com Sun Jun 17 18:09:12 2007 From: DPhillips at cybergroup.com (Doug Phillips) Date: Sun, 17 Jun 2007 17:09:12 -0500 Subject: Database Access using pyodbc. I've a problem In-Reply-To: <1182067583.976439.180170@z28g2000prd.googlegroups.com> References: <1181997323.384882.149020@i13g2000prf.googlegroups.com><1182008006.091353.194490@e9g2000prf.googlegroups.com> <1182067583.976439.180170@z28g2000prd.googlegroups.com> Message-ID: <9A9D5186629F3D428E3C7CBA92A66E47D2F944@mail-26ps.atlarge.net> > -----Original Message----- > From: python-list-bounces+dphillips=cybergroup.com at python.org > [mailto:python-list-bounces+dphillips=cybergroup.com at python.org] On > Behalf Of Rajendran > Sent: Sunday, June 17, 2007 3:06 AM > To: python-list at python.org > Subject: Re: Database Access using pyodbc. I've a problem > > Hi Robert, > Thanks for your response. > The problem I've mentioned comes up only with the Python but not with > the PHP. Is it because PHP has been integrated with Apache and Python > isn't? I mean, we have included these > > # For PHP 5 do something like this: > LoadModule php5_module "c:/php/php5apache2_2.dll" > AddType application/x-httpd-php .php > > # configure the path to php.ini > PHPIniDir "C:/php" > > > lines in the httpd.conf for Apache to understand PHP and no > corresponding lines for Python? > > Does this make Apache to run PHP with the permissions same as user? There are two user execution settings in Apache. The first (User) tells Apache which user to run as. The second (SuExec User) tells Apache which user to run CGI files as. These can (and should) be handled differently in a production system. I'm not familiar with how apache handles these functions in a Windows environment, but the references in a prior answer to this thread should help you out. -Doug From nebulous99 at gmail.com Fri Jun 22 19:08:02 2007 From: nebulous99 at gmail.com (nebulous99 at gmail.com) Date: Fri, 22 Jun 2007 23:08:02 -0000 Subject: The Modernization of Emacs: terminology buffer and keybinding In-Reply-To: <87bqf7fwmg.fsf@telesippa.clsnet.nl> References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182272495.990807.99110@a26g2000pre.googlegroups.com> <87tzt3ihev.fsf@kobe.laptop> <1182370216.961241.6960@n60g2000hse.googlegroups.com> <85zm2ufjpb.fsf@lola.goethe.zz> <1182372592.803332.288260@u2g2000hsc.googlegroups.com> <1182549094.366282.286740@m37g2000prh.googlegroups.com> <87bqf7fwmg.fsf@telesippa.clsnet.nl> Message-ID: <1182553682.197778.138500@g37g2000prf.googlegroups.com> On Jun 22, 6:32 pm, Cor Gest wrote: > > HOW IN THE BLOODY HELL IS IT SUPPOSED TO OCCUR TO SOMEONE TO ENTER > > THEM, GIVEN THAT THEY HAVE TO DO SO TO REACH THE HELP THAT WOULD TELL > > THEM THOSE ARE THE KEYS TO REACH THE HELP?! > > What's your problem ? > > Ofcourse a mere program-consumer would not look what was being > installed on his/her system in the first place ... > So after some trivial perusing what was installed and where : > WOW Look, MA ! .... it's all there! > > lpr /usr/local/share/emacs/21.3/etc/refcard.ps > or your install-dir........^ ^ > or your version.............................^ So now we're expected to go on a filesystem fishing expedition instead of just hit F1? One small step (backwards) for a man; one giant leap (backwards) for mankind. :P > But then again buying the GNU-book from 'O Reilly would have solved it > in the utmost nicest possible of ways anyway. So much for the "free" in "free software". If you can't actually use it without paying money, whether for the software or for some book, it isn't really free, is it? The book assumes the role of a copy protection dongle*. Of course, if the book is under the usual sort of copyright and not copyleft, so much for the "free as in speech" too, and nevermind the "free as in beer". * In fact, I not-too-fondly remember the days when a common copy protection scheme was for software to periodically (or at least on startup) insist that the user enter the first word on page N of the manual, for various changing choices of N. Making the interface simply unnavigable without the manual strikes me as nearly as effective. If someone did decide to intentionally cripple the interface of some "free" software and make a killing off a book de-facto required to use it, it would be quite the racket. I hope the open source movement would chew them to pieces and curse them in public though. From bignose+hates-spam at benfinney.id.au Thu Jun 28 19:44:21 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 29 Jun 2007 09:44:21 +1000 Subject: try/except/else/finally problem References: <1387teta99gajc4@corp.supernews.com> Message-ID: <87y7i3r6ei.fsf@benfinney.id.au> Ed Jensen writes: > I'm using: > Python 2.3.2 (#1, Oct 17 2003, 19:06:15) [C] on sunos5 > > And I'm trying to execute: > > #! /usr/bin/env python > > try: > f = file('test.txt', 'r') > except IOError: > print 'except' > else: > print 'else' > finally: > print 'finally' > > > What am I doing wrong? You're using syntax that is valid under Python 2.5, but invalid in earlier Python versions. -- \ "Military justice is to justice what military music is to | `\ music." -- Groucho Marx | _o__) | Ben Finney From jjl at pobox.com Sun Jun 17 12:57:21 2007 From: jjl at pobox.com (John J. Lee) Date: Sun, 17 Jun 2007 16:57:21 GMT Subject: WebThumb References: <1181901372.058925.322830@w5g2000hsg.googlegroups.com> Message-ID: <87bqfezfgu.fsf@pobox.com> Johny writes: > How can I get a website thumbnail? > I would like to allow visitors to add their URLs to our pages with > the thumbnail of their website. > Can anyone suggest a solution for web thumbnails? > Thanks > L. There are a number of ways to do it, most of them involving web browsers, and all of them painful in one way or anther. No doubt I've missed some out, and note that I've not actually tried most of these: * Find some commercial component to do it. I think I'd want to know what it was doing under the hood if I used something like this, since there will be implications for rendering reliability, flakiness, etc. I imagine most of these will be convenient wrappers around MSIE. * Use a library capable of HTML rendering. GUI toolkits like Qt, wx and GTK often have simple HTML rendering engines, for example. This is relatively convenient, but is ruled out in your case, since it sounds like you're dealing with arbitrary HTML. Only real battle-hardened web browsers can cope with rendering that reliably. * On Unix, send keystroke/mouse events to X11 to automate a browser (not sure how this is done, though I was looking at some (not open source) code that does it not long ago...). * Talk to Firefox using XPCOM and in-process Python code running inside Firefox. Example code and/or up-to-date documentation would make this much easier, but I don't think there's much around still. * Talk to Firefox using JSSH. I'm assuming this works, but never done it. Presumably it also involves XPCOM interfaces, but with presumably without the risk of Firefox build pain or PyXPCOM quirks. * Automate Konqueror with DCOP (or DBUS in KDE 4, I guess). Never tried it, but assume it must be capable of this. Perhaps other browsers support capable DBUS interfaces now, also... Konqueror will not generate the output you expect for some pages, though. PyKDE might work here, too. * Automate MSIE on Windows with COM (with pywin32 or with ctypes' "comtypes" COM support -- note you still need a third-party package for this -- the ctypes that's part of Python 2.5 standard library isn't enough). This is a mixture of very easy and incredibly painful, depending on what exactly you want to do -- can't say how awkward this particular case is. Last time I looked, it seemed that .NET didn't expose the necessary interfaces to do this, so it *does* have to be COM, not .NET (maybe Vista has changed that, though?). Many of the above would likely involve also either a printer driver that writes images rather than actually printing (perhaps print to .eps and then via ghostscript to a .png), or some code to take a "screen"shot (preferably just of the browser window contents!). It's plausible some browsers might be able to create images themselves rather than requiring you to talk to an external driver yourself, but I don't know of a specific one. The length of this reply indicates what a PITA this is! If I were doing something commercial on Windows, I'd look into the first option. Otherwise, I'd go for Firefox / X11 events or Firefox / JSSH. Note that both of the latter will involve work in creating an isolated environment for Firefox to run in. I've seen Xvnc, a temporary HOME directory, and a canned prefs.js working OK for this purpose. A few actual bits of code, which may or may not be robust ;-) http://marginalhacks.com/Hacks/html2jpg/ This looks better to use than DCOP/DBUS or PyKDE if you're willing to risk using KHTML (the rendering engine in Konqueror): http://khtml2png.sourceforge.net/ John From steve at REMOVE.THIS.cybersource.com.au Sat Jun 9 20:34:21 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sun, 10 Jun 2007 10:34:21 +1000 Subject: Python's "only one way to do it" philosophy isn't good? References: <1181368143.874341.273140@r19g2000prf.googlegroups.com> Message-ID: On Sat, 09 Jun 2007 22:52:32 +0000, Josiah Carlson wrote: > the only thing that optimization > currently does in Python at present is to discard docstrings Python, or at least CPython, does more optimizations than that. Aside from run-time optimizations like interned strings etc., there are a small number of compiler-time optimizations done. Running Python with the -O (optimize) flag tells Python to ignore assert statements. Using -OO additionally removes docstrings. Regardless of the flag, in function (and class?) definitions like the following: def function(args): "Doc string" x = 1 s = "this is a string constant" "and this string is treated as a comment" return s*x The string-comment is ignored by the compiler just like "real" comments. (The same doesn't necessarily hold for other data types.) Some dead code is also optimized away: >>> def function(): ... if 0: ... print "dead code" ... return 2 ... >>> dis.dis(function) 4 0 LOAD_CONST 1 (2) 3 RETURN_VALUE Lastly, in recent versions (starting with 2.5 I believe) Python includes a peephole optimizer that implements simple constant folding: # Python 2.4.3 >>> dis.dis(lambda: 1+2) 1 0 LOAD_CONST 1 (1) 3 LOAD_CONST 2 (2) 6 BINARY_ADD 7 RETURN_VALUE # Python 2.5 >>> dis.dis(lambda: 1+2) 1 0 LOAD_CONST 2 (3) 3 RETURN_VALUE The above all holds for CPython. Other Pythons may implement other optimizations. -- Steven. From deets at nospam.web.de Wed Jun 27 13:08:18 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 27 Jun 2007 19:08:18 +0200 Subject: Reversing a string References: Message-ID: <5efjs2F38m1reU1@mid.uni-berlin.de> Scott wrote: > Yeah I know strings == immutable, but question 1 in section 7.14 of "How > to think like a computer Scientist" has me trying to reverse one. > > I've come up with two things, one works almost like it should except that > every traversal thru the string I've gotten it to repeat the "list" again. > This is what it looks like: > > [code] >>>>mylist = [] >>>>def rev(x): > for char in x: > mylist.append(char) > mylist.reverse() > print mylist > [/code] The reverse() is totally useless to apply each when appending each character. Not only useless, but faulty: if you have a even number of characters, your string won't be reversed. All you need to do is this: >>> x = "abcdefg" >>> print "".join(reversed(x)) gfedcba HTH Diez From nagle at animats.com Tue Jun 12 19:16:35 2007 From: nagle at animats.com (John Nagle) Date: Tue, 12 Jun 2007 23:16:35 GMT Subject: Python's "only one way to do it" philosophy isn't good? In-Reply-To: References: Message-ID: Steve Howell wrote: > --- "Anders J. Munch" <2007 at jmunch.dk> wrote: > >>Converting tail-recursion to iteration is trivial, >>and perfectly reasonable for >>a human to do by hand. You add an outer "while >>True"-loop, the recursive call >>becomes a tuple assignment, and other code paths end >>with a break out of the >>loop. Completely mechanical and the resulting code >>doesn't even look that bad. >> > > > I have to ask the stupid question. If a human can do > this completely mechanically, why can't a machine? That's what tail recursion optimization is. It's not a high-priority optimization for CPython. The language has good iteration primitives, so iterating via simple recursion is relatively rare and not, typically, a performance bottleneck. In LISP, one might iterate over a list using tail recursion, but in Python, that would be both silly and inefficient. John Nagle From garrickp at gmail.com Thu Jun 21 16:31:54 2007 From: garrickp at gmail.com (Falcolas) Date: Thu, 21 Jun 2007 13:31:54 -0700 Subject: The Modernization of Emacs: terminology buffer and keybinding In-Reply-To: <1182456618.763414.219080@g4g2000hsf.googlegroups.com> References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182272495.990807.99110@a26g2000pre.googlegroups.com> <87tzt3ihev.fsf@kobe.laptop> <1182370216.961241.6960@n60g2000hse.googlegroups.com> <85zm2ufjpb.fsf@lola.goethe.zz> <1182372592.803332.288260@u2g2000hsc.googlegroups.com> <1182373919.262388.100740@c77g2000hse.googlegroups.com> <85r6o6fhkb.fsf@lola.goethe.zz> <1182375045.626510.188170@m36g2000hse.googlegroups.com> <1182453375.531950.141460@m36g2000hse.googlegroups.com> <1182456618.763414.219080@g4g2000hsf.googlegroups.com> Message-ID: <1182457914.940791.224080@n2g2000hse.googlegroups.com> On Jun 21, 2:10 pm, Kaldrenon wrote: > I don't think anyone can make the argument that any (past or current) > graphics-based editor is as efficient when being used to its fullest > as a text-based editor. It's basic math - it takes measurably more > time to move a hand to the mouse, move/click the mouse, and more the > hand back to the touch-typing position than it does to execute even a > moderately complex series of keystrokes. Maybe not large amounts of > time -per action-, but it doesn't take too long for it to add up if > you spend a lot of time editing. > > Contrast the time saved by not having to reposition one's hands, the > extensibility, and customization against the learning curve of an > interface that doesn't exactly throw its controls at the user, and > here's the conclusion I think results: graphical interfaces are - > easier- to develop some proficiency with, but proficiency with emacs > pays of far more in the long run. I have to point out, that this makes the assumption that the most oft- used commands in a GUI editor are not as easily accessed from the keyboard as they are in a terminal editor. I took a moment to look at the gui editor which has been made available to me, and short of the "remove leading spaces" commands, I do not need to remove my hands from the keyboard if I do not want to. Your statement holds true if, and only if, a user does not take full advantage of the keyboard commands. But if we're talking about experienced users in both cases, then that's not an issue, is it? From stefan.behnel-n05pAM at web.de Wed Jun 27 04:03:08 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Wed, 27 Jun 2007 10:03:08 +0200 Subject: XML from SQL result In-Reply-To: References: Message-ID: <468219BC.7000909@web.de> Marcin St?pnicki wrote: > I've skimmed through many Python&XML related books/articles but I am > unable to find anything that is similar to my problem - but it seems to > me that it should be common. > > Anyway: I've got the SQL query which returns: > > col1 | col2 | col3 > -----+------+----- > a | a10 | b20 > a | a10 | b30 > a | a20 | b30 > > I need to generate the following: > > > > > > > > > > > I'd use a two-step approach here. Collect the data in a dict of dicts, then write it out into XML. Something like this: c1d = {} for c1, c2, c3 in rows: c2d = c1d.get(c1) if c2d is None: c2d = c1d[c1] = {} c3_list = c2d.get(c2) if c3_list is None: c3d = c2d[c2] = [] c3_list.append(c3) root = ET.Element("root") # in case "col1" has more than one value for c1, c2d in c1d.iteritems(): el_c1 = ET.SubElement(root, "tag1", col1=c1) for c2, c3_list in c2d.iteritems(): el_c2 = ET.SubElement(el_c1, "tag2", col2=c2) for c3 in c3_list: ET.SubElement(el_c2, "tag3", col3=c3) Stefan From larry.bates at websafe.com Tue Jun 12 13:14:23 2007 From: larry.bates at websafe.com (Larry Bates) Date: Tue, 12 Jun 2007 12:14:23 -0500 Subject: how to kill a process In-Reply-To: <1181664061.381917.41270@a26g2000pre.googlegroups.com> References: <1181664061.381917.41270@a26g2000pre.googlegroups.com> Message-ID: Richard Rossel wrote: > Hi Fellows, > I have a problem with process termination. I have a python code that > apache runs through a django interface. > The code is very simple, first, it creates a process with the > subprocess.Popen call, and afterwards, (using a web request) the > python code uses the PID of the previously created process(stored in a > db) and kills it with an os.kill call using the SIGKILL signal. > > The creation of the process is ok, apache calls the python code, this > code creates the process and exits leaving the process up and > running :) > But when the python code is called to kill the created process, the > process is left in a zombie state. > > The kill code that I'm using is: > os.kill(pid, signal.SIGKILL) > > and I also tried: > kill_proc = Popen("kill -9 " + pid, shell=true) > but with no success. > > I suppose that the reason maybe that the python code exits before the > kill call has finished, > so I tried with a while loop until kill_proc.poll() != None, but > without success too :( > > do you know what is what I'm doing wrong? > > thanks very much.- > Wouldn't it be better to make the process that you start respond gracefully to some signal? Either a command over a socket or some other signal? -Larry From thorsten at thorstenkampe.de Fri Jun 29 12:12:04 2007 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Fri, 29 Jun 2007 18:12:04 +0200 Subject: Looking for an interpreter that does not request internet access References: <87y7i381ey.fsf@mulj.homelinux.net> Message-ID: * Hrvoje Niksic (Fri, 29 Jun 2007 13:07:01 +0200) > James Alan Farrell writes: > > > Hello, > > I recently installed new anti-virus software and was surprised the > > next time I brought up IDLE, that it was accessing the internet. > > > > I dislike software accessing the internet without telling me about it, > > especially because of my slow dial up connection (there is no option > > where I live), but also because I feel it unsafe. > > When I start up IDLE, I get this message: > > **************************************************************** > Personal firewall software may warn about the connection IDLE > makes to its subprocess using this computer's internal loopback > interface. This connection is not visible on any external > interface and no data is sent to or received from the Internet. > **************************************************************** > > It would seem to explain the alarm you're seeing. Actually it wouldn't. 127.0.0.1 is definitely not "the Internet" and it would make James' posting even mysterious... From durumdara at gmail.com Wed Jun 13 05:27:35 2007 From: durumdara at gmail.com (durumdara) Date: Wed, 13 Jun 2007 02:27:35 -0700 Subject: Where can I suggest an enchantment for Python Zip lib? In-Reply-To: References: <46684DB8.6080900@websafe.com> <1181287080.398800.194140@q75g2000hsh.googlegroups.com> Message-ID: <1181726855.129860.237130@i38g2000prf.googlegroups.com> > On my 3 year old 3Ghz Pentium III it takes about 8 seconds to zip 20Mb file. > So what is the problem? Not updating the process for 8-10 seconds > should be just fine for most applications. > > -Larry The problem, that: - I want to process 100-200 MB zip files. - I want to abort in process - I want to know the actual position - I want to slow the operation sometimes! Why I want to slow? The big archiving is slow operation. When it is slow, I want to working with other apps while it is processing. So I want to slow the zipping with time.sleep, then the background thread is not use the full CPU... I can work with other apps. dd From Dave.Baum at motorola.com Tue Jun 12 14:29:24 2007 From: Dave.Baum at motorola.com (Dave Baum) Date: Tue, 12 Jun 2007 13:29:24 -0500 Subject: List sequential initialization References: <1181670619.086709.116730@g37g2000prf.googlegroups.com> Message-ID: In article <1181670619.086709.116730 at g37g2000prf.googlegroups.com>, HMS Surprise wrote: > I thought if I could do this: > >>> a = b = '' a and b refer to the same object (the empty string) > >>> a = 'a' You are assigning a new value to a - it now refers to the string 'a', while b refers to the same thing it always has (the empty string) > >>> a > 'a' > >>> b > '' > > then this would behave similarly: > >>> la = lb = [] la and lb refer to the same object, an empty list > >>> la.append('a') You are appending 'a' to the list that la refers to. > >>> la > ['a'] > >>> lb > ['a'] Since lb referred to the same list as la, when you modified the list via la.append, those changes can also be seen via lb. If instead of la.append('a'), you had done: la = ['a'] Then it would have behaved similarly to the first example, and lb would still refer to an empty list. > > I thought wrong! But don't know why. For immutable objects (such as integers, strings, and tuples), the distinction between pointing to the same object or identical copies isn't important since you cannot modify the objects. However, when you use mutable objects (such as lists) and modify them, then it is important to understand when you are dealing with the same object and when you are copying the object. Assignment makes a name refer to an object. Multiple names can refer to the same object (which is what a=b=c does). If you want to make a copy of the object, you need to do so explicitly: >>> a = [1, 2, 3] >>> b = list(a) >>> a.append(4) >>> a [1, 2, 3, 4] >>> b [1, 2, 3] Dave From steve at REMOVE.THIS.cybersource.com.au Mon Jun 11 19:46:07 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Tue, 12 Jun 2007 09:46:07 +1000 Subject: Postpone creation of attributes until needed References: <1181553891.447344.109390@g4g2000hsf.googlegroups.com> <1181559496.911368.219210@p77g2000hsh.googlegroups.com> <1181564855.890242.116840@m36g2000hse.googlegroups.com> Message-ID: On Mon, 11 Jun 2007 05:27:35 -0700, Frank Millman wrote: > I now have the following - > >>>> class A(object): > ... def __init__(self,x,y): > ... self.x = x > ... self.y = y > ... def __getattr__(self,name): > ... print 'getattr',name > ... self.compute() > ... return self.__dict__[name] > ... def compute(self): # compute all missing attributes > ... self.__dict__['z'] = self.x * self.y > [there could be many of these] > >>>> a = A(3,4) >>>> a.x > 3 >>>> a.y > 4 >>>> a.z > getattr z > 12 >>>> a.z > 12 >>>> a.q > KeyError: 'q' > > The only problem with this is that it raises KeyError instead of the > expected AttributeError. Yes, because you never assign __dict__['q']. >> You haven't told us what the 'compute' method is. >> >> Or if you have, I missed it. >> > > Sorry - I made it more explicit above. It is the method that sets up > all the missing attributes. No matter which attribute is referenced > first, 'compute' sets up all of them, so they are all available for > any future reference. If you're going to do that, why not call compute() from your __init__ code so that initializing an instance sets up all the attributes? That way you can remove all the __getattr__ code. Sometimes avoiding the problem is better than solving the problem. -- Steven. From martin at v.loewis.de Fri Jun 29 18:20:43 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sat, 30 Jun 2007 00:20:43 +0200 Subject: Vista 64 + Python2.5 + wxpython 28 issue In-Reply-To: <003201c7ba21$8c77ff70$a567fe50$@com> References: <4684150e$0$24850$9b622d9e@news.freenet.de> <000001c7b9c5$e70a0d40$b51e27c0$@com> <46842727.6070202@v.loewis.de> <003201c7ba21$8c77ff70$a567fe50$@com> Message-ID: <468585BB.8090800@v.loewis.de> > There was no need for me to use 64 so I have switched back to 32 and works > fine. > > Python is not ready for the 64 world yet ;) It's a matter of standpoint. 64 bit is not ready for the world, yet. Regards, Martin From rpleavitt at yahoo.com Mon Jun 18 20:26:38 2007 From: rpleavitt at yahoo.com (RichL) Date: Mon, 18 Jun 2007 20:26:38 -0400 Subject: Do U have anything to share with this students References: <1181926856.041008.258770@o11g2000prd.googlegroups.com> <1181999183.047568.44000@m36g2000hse.googlegroups.com> Message-ID: "Stephen Cowell" wrote in message news:f2Fdi.20332$C96.454 at newssvr23.news.prodigy.net... > > "Scott en Aztl?n" wrote in message > news:b08d73tdgmq6sdg81j8idi6gnukk8ec2b2 at 4ax.com... > > "Stephen Cowell" said in misc.transport.road: > > > >>> Hope you're protected against malware. > >> > >>Yes, the link probably did what it was supposed to, > >>just not what you thought it would do. Please, folks, > >>don't click tinyurls without knowing the person who > >>made them. > > > > And, since that is impossible, use TinyURL's "preview" function before > > you click. > > Are you a solipsist? I am what John Galt would call > a 'non-absolutist'... *never* say something's impossible, > there is a non-zero probability of *anything* happening. > > Big shout-out to all the folks in the other NG's... from > AGA. We tend to know each other, even though it's > 'impossible'. Oh yeah it's impossible! Someone in another thread "figured out" I was a "lib" just because I recommended a Fender Blues Jr. Pretty clever huh? LOLOLOLOL From wildemar at freakmail.de Sat Jun 2 11:53:40 2007 From: wildemar at freakmail.de (Wildemar Wildenburger) Date: Sat, 02 Jun 2007 17:53:40 +0200 Subject: Observer-Pattern by (simple) decorator In-Reply-To: <1180795187.420775.290710@g4g2000hsf.googlegroups.com> References: <1180781727.519949.172580@q75g2000hsh.googlegroups.com> <1180795187.420775.290710@g4g2000hsf.googlegroups.com> Message-ID: <46619284.9060302@freakmail.de> David Wahler wrote: > > Here's my attempt at an implementation that works as a decorator. It > stores the observers in a dictionary attribute of the instance, using > the method name as a key. For example: > > > [snip: another nice aproach] > Anyway, these are just my initial thoughts -- I don't have the time to > really think this through thoroughly. > > -- David > > Neither do I at the moment, but thats an interesting idea, still. I'll keep it in the back of me head. For now I'll keep testing Steven's version, see how far that gets me. Thanks for the list of possible problems as well; inheritance is something I hadn't thought about yet ... Argh! Considering that this is only the *first* step towards my awesome app ... /W From certo at comeno.it Wed Jun 6 18:17:25 2007 From: certo at comeno.it (imho) Date: Wed, 06 Jun 2007 22:17:25 GMT Subject: Accessing function in a module by name In-Reply-To: <466724f7$0$16372$88260bb3@free.teranews.com> References: <466724f7$0$16372$88260bb3@free.teranews.com> Message-ID: Tobiah ha scritto: > Is there a way to call function in an imported > module having only the name? > > > func_name = 'doit' > > real_func = foo.some_magic(func_name) > > #Now call it > real_func(args) > > > I'm trying to set up a function dispatcher for a > SOAP server. > > Thanks, > > Tobiah > What's wrong with real_func = getattr(foo, func_name) ? Maybe I misunderstood your question ? From rridge at caffeine.csclub.uwaterloo.ca Sun Jun 3 23:54:16 2007 From: rridge at caffeine.csclub.uwaterloo.ca (Ross Ridge) Date: Sun, 03 Jun 2007 23:54:16 -0400 Subject: Python, Dutch, English, Chinese, Japanese, etc. References: Message-ID: Steve Howell wrote: >about Japan: > major linguistic influences: Chinese, English, >Dutch English and Dutch are minor linguistic influences. > kanji = Chinese characters > hiragana and katakana -- syllabic scripts > Latin alphabet often used in modern Japanese (see >wikipedia) The Latin alphabet is generally only used for western or westernized names, like Sony. >Asia: > > Python should be *completely* internationalized for >Mandarin, Japanese, and possibly Hindi and Korean. >Not just identifiers. I'm talking the entire >language, keywords and all. This would be more convincing if it came from someone who spoke Mandarin, Japanese, Hindi or Korean. btw. Mandarin is a spoken dialect Chinese, what you're actually asking for is a Simplified-Chinese version of Python. Ross Ridge -- l/ // Ross Ridge -- The Great HTMU [oo][oo] rridge at csclub.uwaterloo.ca -()-/()/ http://www.csclub.uwaterloo.ca/~rridge/ db // From borud-news at borud.no Thu Jun 21 10:32:44 2007 From: borud-news at borud.no (Bjorn Borud) Date: 21 Jun 2007 16:32:44 +0200 Subject: The Modernization of Emacs References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182370894.001918.36590@k79g2000hse.googlegroups.com> <1182372821.298343.316860@g4g2000hsf.googlegroups.com> <1182375321.067664.190780@o61g2000hsh.googlegroups.com> Message-ID: [BartlebyScrivener ] | | http://www.debian-administration.org/polls/89 this is hardly surprising. I use both editors. for most sysadmin tasks I use vi(m). for programming i use Emacs. in part out of old habit (most UNIX systems had vi installed) and partly because vi(m) is faster (which makes it more suitable when you just need to change a couple of lines in a file). for programming I use Emacs since I have a gazillion extensions I use while programming that I don't even think about anymore. from various forms of automated text completion to syntax checking/highlighting, to enforcing style guides, look up symbol relationships, compile, debug etc. so if the context was system administration, I'd vote for vi as well. if the context was programming I'd vote Emacs. -Bj?rn From evan at yelp.com Tue Jun 19 01:23:29 2007 From: evan at yelp.com (Evan Klitzke) Date: Mon, 18 Jun 2007 22:23:29 -0700 Subject: Do U have anything to share with this students In-Reply-To: References: <1181926856.041008.258770@o11g2000prd.googlegroups.com> <1181999183.047568.44000@m36g2000hse.googlegroups.com> Message-ID: On 6/18/07, Stephen Cowell wrote: > Are you a solipsist? I am what John Galt would call > a 'non-absolutist'... *never* say something's impossible, > there is a non-zero probability of *anything* happening. Because it's impossible for something to be impossible, right? ;-) -- Evan Klitzke From tjreedy at udel.edu Sat Jun 9 13:26:44 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 9 Jun 2007 13:26:44 -0400 Subject: How Can I Increase the Speed of a Large Number of Date Conversions References: <1181266113.100863.174410@q19g2000prn.googlegroups.com> <1181403947.221140.8910@i38g2000prf.googlegroups.com> Message-ID: "vdicarlo" wrote in message news:1181403947.221140.8910 at i38g2000prf.googlegroups.com... | Many thanks for the lucid and helpful suggestions. Since my date range | was only a few years, I used Some Other Guy's suggestion above, which | the forum is saying will be deleted in five days, to make a dictionary | of the whole range of dates when the script starts. It was so fast it | wasn't even worth saving in a file. Made the script a LOT faster. I | guess two thousand function calls must be faster than 200 million? | Like maybe a hundred thousand times faster? Any function called repeatedly with the same input is a candidate for a lookup table. This is a fairly extreme example. || I also benefitted from studying the other suggestons. I had actually | implemented an on the fly dictionary caching scheme for one of my | other calculations. I don't know why it didn't occur to me to do it | with the dates, except I think I must be assuming, as a newbie | Pythonista, that the less I do and the more I let the libraries do the | better off I will be. | | Thanks for putting me straight. As someone I know said to me when I | told him I wanted to learn Python, "the power of Python is in the | dictionaries". | | Funny how long it's taking me to learn that. Well, look at how many of us also did not quite see the now obvious answer. Even Python's list.sort() only fairly recently gained the optional 'key' parameter, which implements the decorate-sort-undecorate pattern and which often obsoletes the original compare-function parameter because it saves time by calculating (and saving) the key only once per item instead of once each comparison. >>> import this The Zen of Python, by Tim Peters [snip] Namespaces are one honking great idea -- let's do more of those! I include lookup dictionaries in this admonition. tjr From python at jayloden.com Mon Jun 25 13:20:27 2007 From: python at jayloden.com (Jay Loden) Date: Mon, 25 Jun 2007 13:20:27 -0400 Subject: listing all property variables of a class instance In-Reply-To: References: <1182789455.818944.227660@g37g2000prf.googlegroups.com> Message-ID: <467FF95B.609@jayloden.com> Neil Cerutti wrote: >> Is there a way to write a method that would list automatically >> all the variables defined as a property (say by printing their >> docstring and/ or their value), and only those variables? > > This is off the cuff. There's likely a better way. > > for k, v in MyClass.__dict__.iteritems(): > if isinstance(v, property): > print k, v.__doc__ > The only way I could get this to work was to change the way the properties were defined/initalized: #!/usr/bin/python class MyClass(object): def __init__(self): self.some_variable = 42 self._a = None self._b = "pi" self.a = property(self.get_a, self.set_a, None, "a is a property") self.b = property(self.get_b, self.set_b, None, "b is a property") def get_a(self): return self._a def set_a(self, value): self._a = value def get_b(self): return self._b def set_b(self, value): self._b = value test = MyClass() for k,v in test.__dict__.iteritems(): if isinstance(v, property): print k, v.__doc__ From __peter__ at web.de Sat Jun 2 18:13:14 2007 From: __peter__ at web.de (Peter Otten) Date: Sun, 03 Jun 2007 00:13:14 +0200 Subject: Error message if there is a space in the source directory References: <1180807933.269404.208750@m36g2000hse.googlegroups.com> Message-ID: lukefrancomusic at gmail.com wrote: > I am trying to learn Python. I am working on a simple backup program > (code listed below). When using a source directory (the files to be > backed up) without spaces in the title, my program works fine [see > line 5]. If I try to access a directory with a space in the name the > program fails with this error message: > > zip error:Nothing to do! (try: zip -qr C:\Backup\ > \06.02.2007\BackUp at _10.03.57.zip . -i C:\test\test2\\) > Backup FAILED > > I've been trying to find the answer for a while now but am stumped and > don't know exactly what to look for. Any help would be greatly > appreciated! > > > 1. # C:\python25\programs\ > 2. # File name: backup3debug.py > 3. import os, time > 4. # 1. The files and directories to be backed up are specified in > a list. > 5. source = [r'C:\test\test2\\'] > 6. # 2. The backup must be stored in a main backup directory. > 7. target_directory = r'C:\Backup\\' > 8. # 3. The files are backed up into a zip file. > 9. # 4. The name of the directory is the current date. > 10. today = target_directory + time.strftime('%m.%d.%Y') > 11. # The current time is the name of the zip archive. > 12. now = time.strftime('BackUp at _%H.%M.%S') > 13. # Create the subdirectory if it does not exist already. > 14. if not os.path.exists(today): > 15. os.mkdir(today) > 16. print 'Successfully created directory', today > 17. # The name of the zip file. > 18. target = os.path.join(today, now + '.zip') > 19. # 5. We use the standard ''zip'' command to put the files in a > zip archive. > 20. zip_command = "zip -qr %s %s" % (target, ' '.join(source)) > 21. print zip_command > 22. # Run the backup > 23. if os.system(zip_command) == 0: > 24. print 'sucessful backup to', target > 25. else: > 26. print 'Backup FAILED' I realize that you have good intentions, but this script is commented to death. Make a guess which points a reader may stumble over and only comment these. > When using a source like this on line 5: > > source = [r'C:\test\test 2\\'] > > which has a space in the title, the program will not work. That's because in the line zip -qr C:\Backup\\06.07.2008\BackUp at _01.02.03.zip C:\test\test 2\\ the shell (or whatever split the above line into separate arguments) has no way of knowing that "C:\test\test" and "2\\" are intended to be one argument. Use subprocess.call() instead of os.system(). You can pass it a list an thus avoid the ambiguity: zip_command = ["zip", "-qr", target] + source subprocess.call(zip_command) Peter From kenicheema at gmail.com Tue Jun 12 20:04:05 2007 From: kenicheema at gmail.com (kenicheema at gmail.com) Date: Wed, 13 Jun 2007 00:04:05 -0000 Subject: MS Word parser Message-ID: <1181693045.105981.169500@q19g2000prn.googlegroups.com> Hi all, I'm currently using antiword to extract content from MS Word files. Is there another way to do this without relying on any command prompt application? From pinkfloydhomer at gmail.com Tue Jun 19 07:22:36 2007 From: pinkfloydhomer at gmail.com (pinkfloydhomer at gmail.com) Date: Tue, 19 Jun 2007 11:22:36 -0000 Subject: Python and (n)curses In-Reply-To: References: <1182211133.956524.160020@g4g2000hsf.googlegroups.com> Message-ID: <1182252156.178726.237800@n60g2000hse.googlegroups.com> On Jun 19, 2:17 am, Josiah Carlson wrote: > > This link offers a series of links for console IO...http://mail.python.org/pipermail/python-list/2005-January/303984.html > Thanks. > Among them is a link to the 'wcurses' module that has been relocated > here:http://adamv.com/dev/python/curses/ It doesn't actually work in > the console, but it seems as though you can program towards one API. > Yep. > There is always cygwin + Python + ncurses. > Of course, but I want to be able to distribute the resulting application easily. Can I do that with this solution? /David From pelonpelon at gmail.com Wed Jun 20 19:46:07 2007 From: pelonpelon at gmail.com (pelon) Date: Wed, 20 Jun 2007 23:46:07 -0000 Subject: WebThumb In-Reply-To: References: <1181901372.058925.322830@w5g2000hsg.googlegroups.com> <87bqfezfgu.fsf@pobox.com> Message-ID: <1182383167.506167.161530@n60g2000hse.googlegroups.com> On Jun 17, 8:57 pm, Jay Loden wrote: > John J. Lee wrote: > > Johny writes: > > >> How can I get a website thumbnail? > >> I would like to allow visitors to add their URLs to our pages with > >> the thumbnail of their website. > >> Can anyone suggest a solution for web thumbnails? > >> Thanks > >> L. > > Don't know if this really helps any but it does sort of reaffirm what John Lee said already: > > http://www.zubrag.com/articles/create-website-snapshot-thumbnail.php > > Seems like this is one are that could really use a nice open source library of some kind :-) > > -Jay This company offers screen captures for pay. I've not tried them, but I may one day for verification of my web designs. http://www.browsercam.com/default.aspx pelon From Leo.Kislov at gmail.com Wed Jun 27 06:14:47 2007 From: Leo.Kislov at gmail.com (Leo Kislov) Date: Wed, 27 Jun 2007 03:14:47 -0700 Subject: String formatting for complex writing systems In-Reply-To: <1182939000.080429.136180@x35g2000prf.googlegroups.com> References: <1182928852.730131.323210@a26g2000pre.googlegroups.com> <1182939000.080429.136180@x35g2000prf.googlegroups.com> Message-ID: <1182939287.897840.60490@m37g2000prh.googlegroups.com> On Jun 27, 3:10?am, Leo Kislov wrote: > On Jun 27, 12:20?am, Andy wrote: > > > Hi guys, > > > I'm writing a piece of software for some Thai friend. ?At the end it > > is supposed to print on paper some report with tables of text and > > numbers. ?When I test it in English, the columns are aligned nicely, > > but when he tests it with Thai data, the columns are all crooked. > > > The problem here is that in the Thai writing system some times two or > > more characters together might take one single space, for example ?? > > (u"\u0E07\u0E34"). ?This is why when I use something like u"%10s" > > % ..., it just doesn't work as expected. > > > Is anybody aware of an alternative string format function that can > > deal with this kind of writing properly? > > In general case it's impossible to write such a function for many > unicode characters without feedback from rendering library. > Assuming you use *fixed* font for English and Thai the following > function will return how many columns your text will use: > > from unicodedata import category > def columns(self, s): > ? ? return sum(1 for c in s if category(c) != 'Mn') That should of course be written as def columns(s). Need to learn to proofread before posting :) -- Leo From zaperaj at gmail.com Fri Jun 22 01:58:06 2007 From: zaperaj at gmail.com (zaperaj at gmail.com) Date: Thu, 21 Jun 2007 22:58:06 -0700 Subject: Error in following code Message-ID: <1182491886.184746.104640@x35g2000prf.googlegroups.com> Im working with python2.2 on red hat linux. The following program is supposed to print decreasing numbers from an entered number till 1, each decrement being = 1 : #! usr/bin/env/python def f(n=int(raw_input("enter number: "))): print 'n=',n if n>1: return n*f(n-1) else: print 'end' return 1 Though it works fine on the python interpretor, i dont get the required output when i write this code in gedit (text editor). The output that i get is (where t4.py is the name of the file): [root at localhost root]# python t4.py enter number: 6 [root at localhost root]# i.e it takes the input but doesn't print anything. If anybody can help... Thanx! From vasudevram at gmail.com Sat Jun 23 15:58:32 2007 From: vasudevram at gmail.com (vasudevram) Date: Sat, 23 Jun 2007 19:58:32 -0000 Subject: Do eval() and exec not accept a function definition? (like 'def foo: pass) ? Message-ID: <1182628712.254361.79530@i38g2000prf.googlegroups.com> Hi group, Question: Do eval() and exec not accept a function definition? (like 'def foo: pass) ? I wrote a function to generate other functions using something like eval("def foo: ....") but it gave a syntax error ("Invalid syntax") with caret pointing to the 'd' of the def keyword. Details (sorry for the slight long post but thought it better to give more details in this case - wording is pretty clear, though, I think, so shouldn't take long to read): While working on a personal project for creating a server for a certain protocol (which I may make into an open source project later if it turns out to be any good), I wrote some simple functions to generate HTML start and end tags like , , , , etc. - just to simplify/shorten my code a little. (I'm aware that there are HTML generation libraries out there, but don't think I need the overhead, since my needs are very simple, and anyway wanted to roll my own just for fun. For a bigger/more serious project I would probably use the existing libraries after doing a proper evaluation). So, this question is not about HTML generation but about Python's eval() function and exec statement. Started by writing functions like this: def start_html(): return '\r\n' def end_html(): return '\r\n' ... and similarly for the 'body', 'p', etc. HTML tags. (I used '\r\n' at the end because the server will send this output to the browser over HTTP, so that my code conforms to Internet protocols, and also so that while debugging, my output would have only one tag per line, for readability. Not showing the '\r\n in the rest of the code below) Then I realized that all these functions are very similar - only differ in the return value of the tag. So (being interested in metaprogramming of late), thought of writing a function that would generate these functions, when passed the appropriate tag name argument. [ Digression: I could of course have used another simple approach such as this: def start_tag(tag_name): return '<' + tag_name + '>' # called like this: # print start_tag('html') # print start_tag('body') # and def end_tag(tag_name): return '' # called like this: # print end_tag('body') # print end_tag('html') # and called similarly for the other HTML tags. While the above would work, it still would involve a bit more typing than I'd like to do, since I'[d have to pass in the tag name as an argument each time. I'd prefer having functions that I could call like this: print start_html() # which would print "" print start_body() # which would print "" # and so on ... just to make the code a little shorter and more readable. End of Digression] So, I wrote this code generation function: # AAAA import string def generate_html_tag_function(tag_name, start_or_end): start_or_end.lower() assert(start_or_end in ('start', 'end')) if start_or_end == 'start': func_def = "def start_" + tag_name + ":()\n" + \ "return '<' + tag_name + '>' else: func_def = "def end_" + tag_name + ":()\n" + \ "return '' function = eval(func_def) return function # meant to be called like this: start_html = generate_html_tag_function('html', 'start') start_body = generate_html_tag_function('body', 'start') end_html = generate_html_tag_function('html', 'end') end_body = generate_html_tag_function('body', 'end') # and the generated functions would be called like this: print start_html() print start_body() print end_body() print end_html() # BBBB # giving the output: But when I ran the above code (between the lines marked #AAAA and #BBBB), I got an error "Invalid syntax" with the caret pointing at the "d" of the def statement. I had used eval a few times earlier for somewhat similar uses, so thought this would work. I then looked up the Python Language Reference help, and saw that eval is used to evaluate Python expressions, not statements, and def is a statement. So looked up the exec statement of Python and saw that its syntax seemed to allow what I wanted. So replaced the line containing eval in the above with: exec(func_def) But that too gave the same error (I think so - I tried this yesterday and forgot to save the error messages, sorry about that, so can't be sure, but do think this was the case - if not, I'll save the exact code and output/errors later and repost here - not at my PC right now.) Thanks for any suggestions, Vasudev Ram Bize site: http://www.dancingbison.com PDF creation / conversion toolkit: http://sourceforge.net/projects/xtopdf Blog on software innovation: http://jugad.livejournal.com From simon at brunningonline.net Fri Jun 15 04:52:16 2007 From: simon at brunningonline.net (Simon Brunning) Date: Fri, 15 Jun 2007 09:52:16 +0100 Subject: Serialization across languages? In-Reply-To: <46719c90$0$10851$88260bb3@free.teranews.com> References: <46719c90$0$10851$88260bb3@free.teranews.com> Message-ID: <8c7f10c60706150152o62ec2e69yaafd0801709b9510@mail.gmail.com> On 6/14/07, Tobiah wrote: > I want to do SOAP like calls from a device who's libraries > don't include SOAP. I'm thinking of using simple HTTP posts, > but I'm going to want to send arrays and hashes. > > First, what do I need to be aware of when sending arbitrary > data by a POST, and Second, is there a universally supported > version of what python can do with pickle? I mostly need > python and PHP, but perl would be nice too. JSON might be worth a look. There are libraries available for loads of languages, and it's fairly human readable to boot. -- Cheers, Simon B. simon at brunningonline.net http://www.brunningonline.net/simon/blog/ GTalk: simon.brunning | MSN: small_values | Yahoo: smallvalues From gagsl-py2 at yahoo.com.ar Thu Jun 14 01:12:31 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 14 Jun 2007 02:12:31 -0300 Subject: Method much slower than function? References: <1181781612.939800.238890@q19g2000prn.googlegroups.com> <1181795969.141307.94140@i13g2000prf.googlegroups.com> Message-ID: En Thu, 14 Jun 2007 01:39:29 -0300, sjdevnull at yahoo.com escribi?: > Gabriel Genellina wrote: >> In addition, += is rather inefficient for strings; the usual idiom is >> using ''.join(items) > > Ehh. Python 2.5 (and probably some earlier versions) optimize += on > strings pretty well. > > a="" > for i in xrange(100000): > a+="a" > > and: > > a=[] > for i in xrange(100000): > a.append("a") > a="".join(a) > > take virtually the same amount of time on my machine (2.5), and the > non-join version is clearer, IMO. I'd still use join in case I wind > up running under an older Python, but it's probably not a big issue > here. Yes, for concatenating a lot of a's, sure... Try again using strings around the size of your expected lines - and make sure they are all different too. py> import timeit py> py> def f1(): ... a="" ... for i in xrange(100000): ... a+=str(i)*20 ... py> def f2(): ... a=[] ... for i in xrange(100000): ... a.append(str(i)*20) ... a="".join(a) ... py> print timeit.Timer("f2()", "from __main__ import f2").repeat(number=1) [0.42673663831576358, 0.42807591467630662, 0.44401481193838876] py> print timeit.Timer("f1()", "from __main__ import f1").repeat(number=1) ...after a few minutes I aborted the process... -- Gabriel Genellina From aleax at mac.com Sun Jun 3 15:47:56 2007 From: aleax at mac.com (Alex Martelli) Date: Sun, 3 Jun 2007 12:47:56 -0700 Subject: how can I get the name of a method inside it? References: <466315ba$0$980$426a74cc@news.free.fr> Message-ID: <1hz4u3h.1rll76983a54dN%aleax@mac.com> "S?bastien Vincent" wrote: > I would like to know if it's possible to retrieve the name of a method when > you're inside it. For example, in the following script, I would like to > assign _s so that it prints "you are in method1". > > > *************************************** > class Obj1: > def __init__(self): > ... > > def method1(self): > _s = ??? > print "you are in %s" % _s For debugging purposes, _s = sys._getframe(0).f_code.co_name should work (after you've done an "import sys" somewhere appropriate, of course;-). The _ in front of _getframe, as well as the klunkiness of it all, are all indications that this is _not_ recommended for "production use" -- like most of Python's introspection features, it IS chiefly meant for debugging purposes. Alex From gagsl-py2 at yahoo.com.ar Wed Jun 27 01:40:13 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 27 Jun 2007 02:40:13 -0300 Subject: New Thread- Supporting Multiline values in ConfigParser References: <1182780364.650693.10430@w5g2000hsg.googlegroups.com> <20070627043527.GB3539@gmail.com> Message-ID: En Wed, 27 Jun 2007 01:35:27 -0300, O.R.Senthil Kumaran escribi?: > * Gabriel Genellina [2007-06-25 22:26:47]: > >> And how would you detect a multiline value? >> Because it is not a section nor looks like a new option? >> >> I'd try using this: >> >> if not self.SECTCRE.match(line) and not self.OPTCRE.match(line) and >> cursect is not None and optname: > > Thanks Gabriel, this suggestion worked and helped me understand the > ConfigParser a bit better as well. Good to know it worked - I was not entirely sure it would :) -- Gabriel Genellina From keramida at ceid.upatras.gr Tue Jun 26 04:42:36 2007 From: keramida at ceid.upatras.gr (Giorgos Keramidas) Date: Tue, 26 Jun 2007 11:42:36 +0300 Subject: The Modernization of Emacs: terminology buffer and keybinding References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182272495.990807.99110@a26g2000pre.googlegroups.com> <87tzt3ihev.fsf@kobe.laptop> <1182370216.961241.6960@n60g2000hse.googlegroups.com> <85zm2ufjpb.fsf@lola.goethe.zz> <1182372592.803332.288260@u2g2000hsc.googlegroups.com> <1182549094.366282.286740@m37g2000prh.googlegroups.com> <87bqf7fwmg.fsf@telesippa.clsnet.nl> <1182553682.197778.138500@g37g2000prf.googlegroups.com> <873b0fhokz.fsf@kobe.laptop> <1182843655.378325.275610@q75g2000hsh.googlegroups.com> Message-ID: <87lke7w1hf.fsf@kobe.laptop> On Tue, 26 Jun 2007 07:40:55 -0000, Twisted wrote: >On Jun 25, 2:32 pm, Giorgos Keramidas >wrote: >>> So much for the "free" in "free software". If you can't actually use >>> it without paying money, whether for the software or for some book, >>> it isn't really free, is it? >> >> Please do not confuse the term 'free' in 'free software' with 'gratis'. >> >> 'Gratis', i.e. 'lacking a monetary price tag' is something *very* >> different from the meaning of 'free' in 'free software'. > > Having to pay for the documentation, presumably because it's > copyrighted, doesn't strike me as much more "free as in speech" than > it is "free as in beer". You don't have to "pay for the documentation because it is copyrighted". You can _download_ the Emacs manual in any format you are more comfortable with. See for example: http://www.gnu.org/manual/manual.html This page lists downloadable documentation in nicely formatted HTML or PDF formats, which is available without any sort of monetary charge. > Also being dependent on a particular publisher for access to required > documentation violates "free as in no vendor lock-in", to boot. So > anyone saying some "free" software is unusable without such-and-such > an O'Reilly book can go peddle the software and the book somewhere > where spammers are welcome. Being locked in to O'Reilly being just as > bad as being locked in to Microsoft or Adobe. Since you are not obliged to _pay_ for the O'Reilly version, this entire paragraph is both meaningless and moot. Feel free to grab an online copy of the manual, or install the documentation of Emacs using your favorite distribution's packaging tools. There is absolutely no "lock-in" anywhere near Emacs. - Giorgos From sla29970 at gmail.com Thu Jun 28 10:32:29 2007 From: sla29970 at gmail.com (sla29970 at gmail.com) Date: Thu, 28 Jun 2007 14:32:29 -0000 Subject: Portable general timestamp format, not 2038-limited In-Reply-To: <7x7ipoy6cf.fsf@ruckus.brouhaha.com> References: <1182544384.709759.235300@o11g2000prd.googlegroups.com> <20070625133843.9e25d0ab.steveo@eircom.net> <82b5l4-tvh.ln1@zoogz.gregorie.org> <7xbqf3lc7i.fsf@ruckus.brouhaha.com> <70c7l4-2gp.ln1@zoogz.gregorie.org> <7xlke6y6y1.fsf@ruckus.brouhaha.com> <7x645al8kc.fsf@ruckus.brouhaha.com> <1182894003.920335.317620@a26g2000pre.googlegroups.com> <7x7ipoy6cf.fsf@ruckus.brouhaha.com> Message-ID: <1183041149.275562.114490@o11g2000prd.googlegroups.com> On Jun 27, 10:51 pm, Paul Rubin wrote: > According to , UTC is derived from > TAI. According to , TAI is a proper time, but the very first section in the TAI discussion page cites a refereed paper by the person then in charge of TAI which asserts that is not true. As for the primacy of UTC vs. TAI, this is the classical chicken and egg problem. The bureaucratic reality is opposed to the physical reality. > it's always within 20 nsec. This seems like the kind of correction > that can be applied after the fact. It is the nature of horology that *all* clocks need corrections applied after the fact. The question is whether a given clock and its time distribution system is good enough for the given application. > The difficulty/impossibility of computing intervals on UTC because of leap seconds suggests TAI is a superior timestamp format. TAI is a superior time scale for processes on the surface of the earth which only care about nanosecond precision, but it is not practically available nor legal nor applicable off the surface of the earth. TAI is itself corrected after the fact by the issue of TT(BIPMxx). From usenet at eugenemorozov.name Thu Jun 21 12:01:19 2007 From: usenet at eugenemorozov.name (Eugene Morozov) Date: Thu, 21 Jun 2007 20:01:19 +0400 Subject: Indenting in Emacs In-Reply-To: References: <1182415666.423187.274240@u2g2000hsc.googlegroups.com> Message-ID: Steven W. Orr ?????: > Ok. I'm not stupid but I do not see a 4.78 anywhere even though I see refs > from google. I have 4.75 The SVN tree doesn't seem to even have that. > > I checked the latest copy out from sourceforge and that was 4.75 too. > > Can someone please tell me where to find the latest? > It's from Emacs 22. Eugene From google at gakman.com Sat Jun 16 23:14:40 2007 From: google at gakman.com (google at gakman.com) Date: Sun, 17 Jun 2007 03:14:40 -0000 Subject: Newbie question: how to get started? In-Reply-To: <2007061622483250073-user@superhoostcom> References: <2007061622483250073-user@superhoostcom> Message-ID: <1182050080.588992.313640@a26g2000pre.googlegroups.com> On Jun 17, 12:48 pm, ed wrote: > Hi, > > I'm interested in starting to learn python. I'm looking for any > reccomendations or advice that I can use to get started. Looking > forward to any help you can give! > > Thanks! > > -e There are some great tutorials online. Try this one if you're new to programming: http://docs.python.org/tut/tut.html Otherwise, this is more for experienced programmers: http://www.diveintopython.org/ -- Gerald Kaszuba http://geraldkaszuba.com From newsgroups at debain.org Wed Jun 6 08:08:55 2007 From: newsgroups at debain.org (Samuel) Date: Wed, 6 Jun 2007 12:08:55 +0000 (UTC) Subject: which "GUI module" you suggest me to use? References: <136bvigp2ps99bc@corp.supernews.com> Message-ID: On Wed, 06 Jun 2007 00:22:40 +0000, Grant Edwards wrote: >> I know that WxPython work only under Windows and PyGTK work only under >> Linux... > > You 'know' wrong. > > wxPython works fine under Windows, Linux and OSX. wxPython emulates Gtk (though using some native widgets, it also uses some of its own) and in many cases it looks non-native compared to Gtk. If your target platform includes Unix systems, you'll have to decide whether inconsistencies with the look and feel of the desktop are an issue for you. > PyGTK works under Linux and Windows, but doens't use native widgets > under Windows, so it won't look like a "normal" windows app. Gtk on Win32 can be themed to looked like Windows, AFAIK the Win32 installer does this by default since a couple of months. -Samuel From dborne at gmail.com Fri Jun 8 10:54:24 2007 From: dborne at gmail.com (Dave Borne) Date: Fri, 8 Jun 2007 09:54:24 -0500 Subject: FTP/SSL In-Reply-To: <846ee3740706060745r67eff604j770be015b3b37785@mail.gmail.com> References: <846ee3740706060745r67eff604j770be015b3b37785@mail.gmail.com> Message-ID: <6e42ec490706080754v79e6506fw47340876aba5fc1e@mail.gmail.com> > I'm trying to figure out how to use FTP/SSL (FTPS) - just as a client. Can I > do this in Python? Is everything I need in ftplib? Where else do I look? And > - any good newbie references on using FTPS? Hi, Nancy, I'm not sure if ftplib can handle ssh or not, but googling for "python sftp" turned up this link: http://www.lag.net/paramiko/ It looks like it might do what you want. -Dave From yucetekol at gmail.com Mon Jun 4 01:49:07 2007 From: yucetekol at gmail.com (yuce) Date: Mon, 04 Jun 2007 05:49:07 -0000 Subject: `yield` in a `try/finally` block, pre-Python 2.5 In-Reply-To: <1180934605.412073.138120@q75g2000hsh.googlegroups.com> References: <1180934605.412073.138120@q75g2000hsh.googlegroups.com> Message-ID: <1180936147.621280.33080@o5g2000hsb.googlegroups.com> I had the same problem, you can see: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/130004 for a solution. Happy hacking, Yuce On Jun 4, 8:23 am, Adam Atlas wrote: > I'm trying to emulate the Python 2.5 behaviour (PEP 342) of generator > functions where the `yield` statement is in a `try/finally` block. > Basically, where the `finally` block is guaranteed to run even if the > generator doesn't finish running: it simply runs when the generator is > garbage-collected. Does anyone know a good way of doing this? I'm > looking to see if there's a way to bring about an exception in another > frame in pure Python, but I haven't found anything yet. From len-l at telus.net Mon Jun 25 14:13:59 2007 From: len-l at telus.net (Lenard Lindstrom) Date: Mon, 25 Jun 2007 18:13:59 GMT Subject: Changing sound volume In-Reply-To: References: <1182727056.516883.241390@o61g2000hsh.googlegroups.com> Message-ID: simon kagwe wrote: >> And finally a way that might work using ctypes: >> >> http://mail.python.org/pipermail/python-win32/2006-March/004436.html >> >> Mike > > Hi, > > Thanks for your reply. > > I had already read about the Snack, but I can't use it since my program uses > wxPython for the GUI and Snack requires tk. The best option was the ctypes > method you told me about. I used the code in the sample, but I am getting the > following error: > > exceptions.WindowsError Error 11 while setting volume > > The author of the code claims it works. What could be causing the above error? > > [ I am using Python 2.4.4 and ctypes 1.0.1 ] > That module looks suspiciously like one I have laying around on my computer. That's okay since I had posted it somewhere. Try setting SPEAKER_LINE_FADER_ID to 0. Apparently my assumption that it is always 0 was wrong. If that works I have a more flexible version of the module which actually searches for the speak line fader id. It also has a GetSpeakerVolume function. --- Lenard Lindstrom From wiqd at codelounge.org Tue Jun 26 11:55:30 2007 From: wiqd at codelounge.org (Greg Armer) Date: Tue, 26 Jun 2007 17:55:30 +0200 Subject: Help needed with translating perl to python In-Reply-To: <1182871026.250669.296590@q69g2000hsb.googlegroups.com> References: <1182870250.890390.28970@g37g2000prf.googlegroups.com> <1182871026.250669.296590@q69g2000hsb.googlegroups.com> Message-ID: <20070626155530.GA82341@dev.codelounge.co.za> On Tue, Jun 26, 2007 at 08:17:06AM -0700, vj wrote: >I posted too soon: > >> Statement 1: >> my $today = sprintf("%4s%02s%02s", [localtime()]->[5]+1900, >> [localtime()]->[4]+1, [localtime()]->[3]) ; > >1. is localtime the same as time in python? You could use this instead - from time import localtime today = localtime() - 'today' would then contain a tuple: (2007, 6, 26, 17, 41, 27, 327829) which you could access in a similar way as above (eg: today[0] == 2007) obviously the order of the values is different from the perl counterpart. >2. What does -> ? do in perl? '->' references a hash (or dict in python) key. In python it would be localtime()[4] >3. What is 'my' 'my' declares local data structures (scalars, arrays or hashes) when 'use strict;' is defined in the perl script. > >> Statement 2: >> my $password = md5_hex("$today$username") ; > >is md5_hex the same as md5.new(key).hexdigest() in python? Yes it is. > >> $msglen = bcdlen(length($msg)) ; > >1. here the funciton is being called with the length of variable msg. >However the function def below does not have any args > >> sub bcdlen { >> my $strlen = sprintf("%04s", shift) ; >> my $firstval = substr($strlen, 2, 1)*16 + substr($strlen, 3, 1) ; >> my $lastval = substr($strlen, 0, 1)*16 + substr($strlen, 1, 1) ; >> return chr($firstval) . chr($lastval) ; >> >> } > >2. What does shift do above? 'shift' accesses the first argument passed to the function, in this case the value of length($msg) >3. is the '.' operator just + in python? In principle yes. -- Greg Armer wiqd at codelounge.org http://www.codelounge.org If it would be cheaper to repair the old one, the company will insist on the latest model. From steve at REMOVE.THIS.cybersource.com.au Wed Jun 6 20:48:55 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Thu, 07 Jun 2007 10:48:55 +1000 Subject: Determinant of Large Matrix References: Message-ID: On Wed, 06 Jun 2007 04:10:43 -0700, James Stroud wrote: > Hello All, > > I'm using numpy to calculate determinants of matrices that look like > this (13x13): [snip matrix] > For this matrix, I'm getting this with numpy: > > 2774532095.9999971 > > But I have a feeling I'm exceeding the capacity of floats here. Does > anyone have an idea for how to treat this? Is it absurd to think I could > get a determinant of this matrix? Is there a python package that could > help me? Is there a particular reason you think there is a problem? The determinant given is pretty close to the integer 2774532096. Assuming that is the correct value, the difference between: 2.7745320960000000e9 and 2.7745320959999971e9 gives a relative error of 1.0311731312618234e-13 percent. How much precision were you after? :-) I suspect that if there is a problem with the matrix, it is less likely to be because of the size of floats and more likely that the matrix is ill-conditioned. I don't know if numpy will calculate the condition number of the matrix, or estimate it. If it does, do so -- a large condition number == trouble. http://en.wikipedia.org/wiki/Condition_number Another way to see if the matrix is ill-conditioned is to make a small perturbation to it (say, change two or three of the entries by 0.0001 or so), then calculate the determinate. If the result is radically different, then the matrix is probably ill-conditioned and there is likely no help for you except numerical black magic and/or using a different matrix. -- Steven. From mcl.office at googlemail.com Fri Jun 1 10:49:54 2007 From: mcl.office at googlemail.com (mosscliffe) Date: Fri, 01 Jun 2007 07:49:54 -0700 Subject: Cookie: Not understanding again Message-ID: <1180709394.151350.103200@q69g2000hsb.googlegroups.com> I have the following code, which I thought would create a cookie, if one did not exist and on the html form being sent to the server, it would be availabe for interrogation, when the script is run a second time. It seems to me there is something basic missing in that I should need to tell the server I am sending a cookie, but all the docs I have read imply it is done automatically, if one creates a 'Cookie.SimpleCookie' I know my understanding is poor of web server logic, but if anyone can help, I will be most grateful. This may be more to do with Web Server behaviour than python programming, but surely there is a way of doing this in python. Richard #!/usr/bin/env python import Cookie, os import cgitb;cgitb.enable() def getCookie(): c = Cookie.SimpleCookie() if 'HTTP_COOKIE' in os.environ: c.load(os.environ['HTTP_COOKIE']) print "Found a Cookie", c, "
      " c['mysession'].value += 1 print "
      " return c else: c['mysession'] = 45 print "No Cookie Found so setting an initial value for a Cookie", c print "
      " return c if __name__ == '__main__': print "Content-type: text/html\n\n" myCookie = getCookie() #Print all Environment variables for k, v in os.environ.items(): print k, "=", v, "
      " print "
      " print """
      """ From gagsl-py2 at yahoo.com.ar Wed Jun 6 00:28:37 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 06 Jun 2007 01:28:37 -0300 Subject: Strange errors on exit References: Message-ID: En Tue, 05 Jun 2007 17:59:18 -0300, Thomas Dybdahl Ahle escribi?: > When I close my (gtk) program, I get errors like the below. > It seams that when the interpreter shuts down, it sets every variable to > None, but continues running the threads, (seems only in cases where > they've just been asleep) > I don't think this would be intended behavior? > > Exception in thread Thread-4 (most likely raised during interpreter > shutdown): > Traceback (most recent call last): > File "/usr/lib/python2.4/threading.py", line 442, in __bootstrap > File "/home/thomas/Programmering/python/skak/0.7/lib/pychess/System/ > ThreadPool.py", line 49, in run > File "/usr/lib/python2.4/Queue.py", line 89, in put > File "/usr/lib/python2.4/threading.py", line 237, in notify > exceptions.TypeError: exceptions must be classes, instances, or strings > (deprecated), not NoneType > Unhandled exception in thread started by > Error in sys.excepthook: > > Original exception was: Looks similar to this reported bug: http://sourceforge.net/tracker/index.php?func=detail&aid=1722344&group_id=5470&atid=105470 -- Gabriel Genellina From doug at alum.mit.edu Sat Jun 23 15:14:15 2007 From: doug at alum.mit.edu (Douglas Alan) Date: Sat, 23 Jun 2007 15:14:15 -0400 Subject: Python's "only one way to do it" philosophy isn't good? References: <1181368143.874341.273140@r19g2000prf.googlegroups.com> <7x3b0nmkk6.fsf@ruckus.brouhaha.com> Message-ID: Steven D'Aprano writes: > But if you really want declarations, you can have them. > >>>> import variables >>>> variables.declare(x=1, y=2.5, z=[1, 2, 4]) >>>> variables.x = None >>>> variables.w = 0 > Traceback (most recent call last): > File "", line 1, in > File "variables.py", line 15, in __setattr__ > raise self.DeclarationError("Variable '%s' not declared" % name) > variables.DeclarationError: Variable 'w' not declared Oh, I forgot to mention that I work a lot on preexisting code, which I am surely not going to go to all the effort to retype and then retest. With the "let" and "set" macros I can use "set" without a matching "let". "set" just checks to make sure that a variable already exists before assigning to it, and "let" just prevents against double-declarations. They can be used independently or together. With your "variables" class, they have to be used together. |>oug From S.Mientki-nospam at mailbox.kun.nl Sun Jun 10 12:37:40 2007 From: S.Mientki-nospam at mailbox.kun.nl (Stef Mientki) Date: Sun, 10 Jun 2007 18:37:40 +0200 Subject: Select one of 2 functions with the same name ? Message-ID: hello, For a simulation at different levels, I need different functions with the same name. Is that possible ? I can realize it with a simple switch within each function, but that makes the code much less readable: def Some_Function(): if simulation_level == 1: ... do things in a way elif simulation_level == 2: ... do things in another way elif simulation_level == 3: ... do things in yet another way thanks, Stef Mientki From bradfordh at gmail.com Wed Jun 13 15:24:59 2007 From: bradfordh at gmail.com (Tempo) Date: Wed, 13 Jun 2007 19:24:59 -0000 Subject: Build EXE on Mac OsX 10.4 Message-ID: <1181762699.145088.159500@j4g2000prf.googlegroups.com> Has anyone sucesfully built a *.exe file on a mac operating system before from a *.py file? I have been trying to do this with pyinstaller, but I keep getting errors and I don't know how to install UPX properly. I tried putting the linux UPX folder in my python 2.4 directory, but that didn't work. I am just generally confused right now. Ha. If anybody can lend me some insight I would really appreciate it. Thank you for taking the time to read this post. -b From cedb816 at yahoo.com Thu Jun 28 11:40:50 2007 From: cedb816 at yahoo.com (ce) Date: Thu, 28 Jun 2007 08:40:50 -0700 Subject: Face Recognition In-Reply-To: <5ec525F388c7bU1@mid.uni-berlin.de> References: <1182814191.138864.80450@w5g2000hsg.googlegroups.com> <5ec525F388c7bU1@mid.uni-berlin.de> Message-ID: <1183045250.849243.97680@g37g2000prf.googlegroups.com> On Jun 26, 5:37 pm, "Diez B. Roggisch" wrote: > Henrik Lied wrote: > > Hi there! > > > Has anyone made effort to try to create a python binding to a facial > >recognitionsoftware [1]? > > > For those of you with some experience - would this be very hard? > > OpenCV has a python-binding. And a ctypes-binding. > > Diez From hyugaricdeau at gmail.com Wed Jun 6 11:54:28 2007 From: hyugaricdeau at gmail.com (Hyuga) Date: Wed, 06 Jun 2007 15:54:28 -0000 Subject: otsu threshold in python In-Reply-To: <1181130568.840780.74850@p47g2000hsd.googlegroups.com> References: <1181053148.203548.199630@w5g2000hsg.googlegroups.com> <1181059357.248682.38980@p77g2000hsh.googlegroups.com> <1181130568.840780.74850@p47g2000hsd.googlegroups.com> Message-ID: <1181145268.281894.83090@w5g2000hsg.googlegroups.com> On Jun 6, 7:49 am, azrael wrote: > the otsu filter is a filter that takes a image and from its histogram > calculates the values at which the image should be thresholded to > acomplish an optimal seperation of a foregtround and background > object. So I learned from the PDF I linked you to. Take a good look at it. The equation is fairly simple to begin with, and the paper shows how to simplify the calculation quite a bit. Also, the Wikipedia article at http://en.wikipedia.org/wiki/Otsu's_method even gives a simple pseudo-code implementation. I've tried it myself in Python, and it seems give good results. > I didn't hear about, but I used it through the ImageJ tool. It gave me > optimal results. I'm working on a project for my clases, and the last > thing I need to accomplish my goal is this filter. Is there anyone who > implemented it. > > Thanks Hyuga > > On Jun 5, 6:02 pm, Hyuga wrote: > > > On Jun 5, 10:19 am, azrael wrote: > > > > Hy guys. > > > I'd like to ask you for a favour. > > > I tried several times to implement the otsu threshold filter in > > > python. but I failed every time. I found the soucre code i n Java from > > > the ImageJ project but I never worked in Java and there have been used > > > some built in Java functions which I don't know how they behave. I > > > also found the otsu threshold in the ia636 python module and would > > > like only this filter and don't want to import this library. > > > Is there anyone who wold like to help me. I need a function that takes > > > a list of 256 elements as an argument and returns the threshold values > > > for the threshold according to Otsu. > > > > In addvance, I don't expect someone to do my homework. I really tried > > > it, I have been googling and didn't find a standalone function. I > > > wasn't able write a standalone function because I don't understand the > > > Otsu method. I just know that it works well and that I need it. > > > > If there is no one that wants to help me with this problem, can > > > someone at least explain me in a detailed way how to implement it. > > > > Thanks > > > What is the whole assignment meant to accomplish? Is the assignment > > to implement the Otsu method? If so, you shouldn't be trying to find > > library functions. Or is it just something you need for some larger > > task? > > > I would ask exactly what problems you're running into, but: > > > > it, I have been googling and didn't find a standalone function. I > > > wasn't able write a standalone function because I don't understand the > > > Otsu method. I just know that it works well and that I need it. > > > How do you know you need it? Did you learn about this in class? And > > if so, are you expected to understand it? > > I've never even heard of it, but I googled it, and found the fourth > > hit pretty good:http://homepages.inf.ed.ac.uk/rbf/CVonline/LOCAL_COPIES/MORSE/thresho... > > This gives a reasonable explanation. I couldn't tell you *exactly* > > why it works, but it's understandable enough from that that I can see > > that it should work, and to see how to implement it. > > > Not to mention that the above PDF basically *gives* you the > > implementation for free (just make sure not to miss the recurrence > > relations at the end of the section on the Otsu method, or else you'll > > be screwing yourself). > > > So give that a look and see if it helps. > > > Hyuga From borud-news at borud.no Fri Jun 22 11:37:06 2007 From: borud-news at borud.no (Bjorn Borud) Date: 22 Jun 2007 17:37:06 +0200 Subject: The Modernization of Emacs: terminology buffer and keybinding References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182272495.990807.99110@a26g2000pre.googlegroups.com> <87tzt3ihev.fsf@kobe.laptop> <1182370216.961241.6960@n60g2000hse.googlegroups.com> <85zm2ufjpb.fsf@lola.goethe.zz> <1182372592.803332.288260@u2g2000hsc.googlegroups.com> <1182373919.262388.100740@c77g2000hse.googlegroups.com> <85r6o6fhkb.fsf@lola.goethe.zz> <1182375045.626510.188170@m36g2000hse.googlegroups.com> <1182453375.531950.141460@m36g2000hse.googlegroups.com> <1182456618.763414.219080@g4g2000hsf.googlegroups.com> <1182457914.940791.224080@n2g2000hse.googlegroups.com> Message-ID: [Falcolas ] | | I took a moment to look at the gui editor which has been made | available to me, and short of the "remove leading spaces" commands, I | do not need to remove my hands from the keyboard if I do not want | to. well, that depends on the editing features you use. I use a lot of features I am not consciously aware of, so if I were to list what I require from an editor, I would have trouble enumerating them. I can't even tell you what keys they are bound to because I just use them instinctively. the same goes for VI. (VI having the added benefit of a really systematic way to organize editing actions into a sort of a matrix (a useful metaphor I was made aware of by an "expert VI user" who showed me how to make some editing operations more efficiently)) having people who are good at efficient editing show you some tricks really pays off btw. I can't bear to watch other people edit text because they are doing so much manual labor that could have been avoided if they had just bothered to learn more effective editing habits. -Bj?rn From apatheticagnostic at gmail.com Thu Jun 21 01:21:31 2007 From: apatheticagnostic at gmail.com (kaens) Date: Thu, 21 Jun 2007 01:21:31 -0400 Subject: The Modernization of Emacs In-Reply-To: References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182344981.372713.298580@w5g2000hsg.googlegroups.com> <86y7ieoiv7.fsf@lola.quinscape.zz> <1182378809.880265.314150@o61g2000hsh.googlegroups.com> Message-ID: <163f0ce20706202221g7205431cya9ca3b10d878ca1@mail.gmail.com> On 6/20/07, Gabriel Genellina wrote: > En Wed, 20 Jun 2007 19:33:29 -0300, alguien escribi?: > > > Speaking of which, vi is a piece of wombat do. ;-) > > Would you all please stop posting (and crossposting) about something that > is mostly off topic for 80% of the groups involved? > Or is someone going for the Longest Off Topic Thread Of The Year Award? > > -- > Gabriel Genellina > > -- > http://mail.python.org/mailman/listinfo/python-list > I for one, am finding the thread interesting, and it can be argued that a discussion about text-editors is relevant in a group about any programming language - although this specific topic (Modernization of emacs) is certainly not VERY relevant to python, except in the sense that a lot of people are seeing python as their first programming language and need to figure out what editor to use (emacs being a very powerful one with a steep learning curve) Anyhow, the topic isn't a flamewar, and it's generating well-thought out discussion - is it that big of a deal? From gagsl-py2 at yahoo.com.ar Wed Jun 27 05:21:35 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 27 Jun 2007 06:21:35 -0300 Subject: XML from SQL result References: Message-ID: En Wed, 27 Jun 2007 04:25:16 -0300, Marcin St?pnicki escribi?: > I've skimmed through many Python&XML related books/articles but I am > unable to find anything that is similar to my problem - but it seems to > me that it should be common. > > Anyway: I've got the SQL query which returns: > > col1 | col2 | col3 > -----+------+----- > a | a10 | b20 > a | a10 | b30 > a | a20 | b30 > > I need to generate the following: > > > > > > > > > > > That looks like a conventional report with totals and subtotals: while col1 is still the same, keep accumulating col2. While col1 and col2 are still the same, keep accumulating col3. Here, accumulating means "append item to current element". If the number of columns is known in advance, you can nest some groupby calls: from itertools import groupby def generate(rows): root = Element("xml") for col1,rows in groupby(rows, lambda row: row[0]): tag1 = SubElement(root, "tag1", col1=col1) for col2,rows in groupby(rows, lambda row: row[1]): tag2 = SubElement(tag1, "tag2", col2=col2) for col3,rows in groupby(rows, lambda row: row[2]): tag3 = SubElement(tag2, "tag3", col3=col3) return root print tostring(generate(rows)) > Using Elementree it's not a problem when returned data is "flat", not > hierarchical. However, that's not the case. Uhm - ElementTree is designed precisely for a hierarchical structure (a "tree" :) ) -- Gabriel Genellina From grante at visi.com Fri Jun 1 01:10:33 2007 From: grante at visi.com (Grant Edwards) Date: Fri, 01 Jun 2007 05:10:33 -0000 Subject: c[:]() References: <1180504190.055427.173610@h2g2000hsg.googlegroups.com> <1180554872.3356.30.camel@dot.uniqsys.com> <465DF3DE.40404@cc.umanitoba.ca> <1180566831.239580.199300@m36g2000hse.googlegroups.com> <005401c7a31a$136f7fe0$240110ac@Muse> <135tobve86qj808@corp.supernews.com> <135tru124pie2b3@corp.supernews.com> <135tv1bjqgbmsc9@corp.supernews.com> <002801c7a3fb$56cc8030$240110ac@Muse> Message-ID: <135vai9213s3k75@corp.supernews.com> On 2007-06-01, Warren Stringer wrote: >> python-ideas lists are the correct forum for those issues, >> though you will of course get all sorts of opinions on c.l.py. > > Oh well. Perhaps I can relax and actually write functioning > code ;-) What do you mean by 'c.l.py'? comp.lang.python: the Usenet news group in which this discussion is taking place. -- Grant Edwards grante Yow! Is it clean in other at dimensions? visi.com From aisaac at american.edu Tue Jun 19 09:38:59 2007 From: aisaac at american.edu (Alan Isaac) Date: Tue, 19 Jun 2007 13:38:59 GMT Subject: File processing - is Python suitable? In-Reply-To: <1182255317.327241.196330@n2g2000hse.googlegroups.com> References: <1182255317.327241.196330@n2g2000hse.googlegroups.com> Message-ID: ferrad wrote: > I have large text files containing text, numbers, and junk. I want to > delete large chunks process other bits, etc, much like I'd do in an > editor, but want to do it automatically. > Question: can I translate these types of rules into programmatical > constructs that Python can use to process these files? Someone can. ;-) However if the file is structured, awk may be faster, since this sounds like the kind of report generation it was designed for. Alan Isaac From peter.mosley at talk21.com Tue Jun 19 05:56:55 2007 From: peter.mosley at talk21.com (peter) Date: Tue, 19 Jun 2007 02:56:55 -0700 Subject: PIL cutting off letters In-Reply-To: <46740d88$0$21149$7a628cd7@news.club-internet.fr> References: <1181934049.401650.115360@q19g2000prn.googlegroups.com> <46740d88$0$21149$7a628cd7@news.club-internet.fr> Message-ID: <1182247015.021702.264080@q69g2000hsb.googlegroups.com> On 16 Jun, 17:20, Pierre Hanser wrote: > Matt Haggard a ?crit : > > > I'm using PIL (Python Imaging Library) to generate button images. > > They consist of a left end image, a middle, repeating image and a > > right side image.... anyway, that's not important > > > I'm using a TTF font for the text of the button (Verdana.TTF) and it > > keeps cutting the bottom part of the the g's q's and y's off. > > hello > > may be the problem is in your code, but it is also possibly > in PIL which clips caracters at the top and bottom line; > that's not the typographic names, but these are *font* values, > not characters ones. > There are fonts with caracters far higher than these > conventionnal lines (try Liorah.ttf or any swashed font for > exemple)! > I don't remember for sure but may be there is the same problem > horizontally. > -- > Pierre I've had this problem horizontally, and solved it by the high tech method of adding a leading and trailing space!!! Peter From phus at live.com Sat Jun 16 13:28:18 2007 From: phus at live.com (jigloo) Date: Sat, 16 Jun 2007 10:28:18 -0700 Subject: retrieve / find out an image's dimensions In-Reply-To: <1181989666.584877.308920@i13g2000prf.googlegroups.com> References: <1181989666.584877.308920@i13g2000prf.googlegroups.com> Message-ID: <1182014898.491908.235870@a26g2000pre.googlegroups.com> On 6 16 , 6 27 , Adam Teale wrote: > hey guys > > Is there a builtin/standard install method in python for retrieving or > finding out an image's dimensions? Sorry, after i review these code in http://www.pycode.com/modules/?id=32, i found some(not just a few) *BUGS* in it. I must apologize to you for this. I have rewrite the moudle. please have a try. """Recognize image file formats and size based on their first few bytes.""" # Perl Image::Size module clone # see more http://search.cpan.org/author/RJRAY/Image-Size-3.01/lib/Image/Size.pm # rewrited by jigloo(phus at live.com) # GPL-2 license __all__ = ["what", "imgsz", "size"] import os # for os.path os.error sys.stderr import StringIO # for StringIO.StringIO import struct # for unpack import re # for regex # jpegsize: gets the width and height (in pixels) of a jpeg file # def jpegsize(stream): (x, y, error) = (None, None, "could not determine JPEG size") # Dummy read to skip header ID stream.read(2) while True: # Extract the segment header. (marker, code, length) = struct.unpack("!BBH", stream.read(4)) # Verify that it's a valid segment. if marker != 0xFF: # Was it there? error = "JPEG marker not found" break elif code >= 0xC0 and code <= 0xC3: # Segments that contain size info (y, x) = struct.unpack("!xHH", stream.read(5)) error = "no error" break else: # Dummy read to skip over data stream.read(length - 2) return ("JPEG", x, y, error) # bmpsize: size a Windows-ish BitMaP image # def bmpsize(stream): (x, y, error) = (None, None, "Unable to determine size of BMP data") # Dummy read to skip header data stream.read(18) (x, y) = struct.unpack(" 0 and y > 0: error = "no error" return ("BMP", x, y, error) # pngsize : gets the width & height (in pixels) of a png file # cor this program is on the cutting edge of technology! (pity it's blunt!) # def pngsize(stream): (x, y, error) = (None, None, "could not determine PNG size") # Dummy read to skip header data stream.read(12) if stream.read(4) == "IHDR": (x, y) = struct.unpack("!LL", stream.read(8)) error = "no error" return ("PNG", x, y, error) # gifsize : Subroutine gets the size of the specified GIF # # Default behavior for GIFs is to return the "screen" size GIF_BEHAVIOR = 0 # def gifsize(stream): if GIF_BEHAVIOR > 2: return ("GIF", 0, 0, "Out-of-range value for GIF_BEHAVIOR: %d" % GIF_BEHAVIOR) # Skip over the identifying string, since we already know this is a GIF type = stream.read(6) buf = stream.read(5) if len(buf) != 5: return ("GIF", 0, 0, "Invalid/Corrupted GIF (bad header)") (sw, sh, x) = struct.unpack(" num_dirent: break tag = struct.unpack(be+"H", ifd[:2])[0] # ...and decode its tag type = struct.unpack(be+"H", ifd[2:2+2])[0] # ...and the data type # Check the type for sanity. if type > len(packspec) or packspec[type] is None: continue if tag == 0x0100: # ImageWidth (x) # Decode the value x = struct.unpack(packspec[type], ifd[8:4+8])[0] elif tag == 0x0101: # ImageLength (y) # Decode the value y = struct.unpack(packspec[type], ifd[8:4+8])[0] # Decide if we were successful or not if x and y: error = "no error" else: error = "" if x is None: error = "ImageWidth " if y is None: if error != "": error = error + "and " error = error + "ImageWidth " error = error + "tag(s) could not be found" return ("TIFF", x, y, error) # psdsize : determine the size of a PhotoShop save-file (*.PSD) # def psdsize(stream): (x, y, error) = (None, None, "could not determine PSD size") stream.read(14) (y, x) = struct.unpack("!LL", stream.read(8)) if x > 0 and y > 0: error = "no error" return ("PSD", x, y, error) # pcdsize : # Kodak photo-CDs are weird. Don't ask me why, you really don't want details. PCD_MAP = { "base/16" : [ 192, 128 ], "base/4" : [ 384, 256 ], "base" : [ 768, 512 ], "base4" : [ 1536, 1024 ], "base16" : [ 3072, 2048 ], "base64" : [ 6144, 4096 ]} # Default scale for PCD images PCD_SCALE = "base"; # def pcdsize(stream): (x, y, error) = (None, None, "Unable to determine size of PCD data") buff = strean.read(0xf00) if buff[0x800:3+0x800] != "PCD": error = "Invalid/Corrupted PCD (bad header)" return ("PCD", x, y, error) orient = ord(buff[0x0e02:1+0x0e02]) & 1 # Clear down to one bit if orient: (x, y) = PCD_MAP[PCD_SCALE] else: (y, x) = PCD_MAP[PCD_SCALE] error = "no error" return ("PCD", x, y, error) # swfsize : # def swfsize(stream): (x, y, error) = (None, None, "not implemented. --I hate swf :(") return ("SWF", x, y, error) # swfmxsize : # def swfmxsize(stream): (x, y, error) = (None, None, "not implemented. --I hate swf :(") return ("SWF", x, y, error) # mngsize : gets the width and height (in pixels) of an MNG file. # # Basically a copy of pngsize. def mngsize(stream): (x, y, error) = (None, None, "could not determine MNG size") stream.read(12) if stream.read(4) == "MHDR": # MHDR = Image Header (x, y) = struct.unpack("!LL", stream.read(8)) error = "MNG" else: error = "Invalid/Corrupted MNG (bad header)" return ("MNG", x, y, error) # type_map used in function type_map_match type_map = { re.compile(r"^\xFF\xD8") : ["JPEG", jpegsize], re.compile(r"^BM") : ["BMP", bmpsize], re.compile(r"^\x89PNG\x0d\x0a\x1a\x0a") : ["PNG", pngsize], re.compile(r"^P[1-7]") : ["PPM", ppmsize], # also XVpics re.compile(r"\#define\s+\S+\s+\d+") : ["XBM", xbmsize], re.compile(r"\/\* XPM \*\/") : ["XPM", xpmsize], re.compile(r"^MM\x00\x2a") : ["TIFF", tiffsize], re.compile(r"^II\x2a\x00") : ["TIFF", tiffsize], re.compile(r"^8BPS") : ["PSD", psdsize], re.compile(r"^PCD_OPA") : ["PCD", pcdsize], re.compile(r"^FWS") : ["SWF", swfsize], re.compile(r"^CWS") : ["SWF", swfmxsize], re.compile(r"^\x8aMNG\x0d\x0a\x1a\x0a") : ["MNG", mngsize], re.compile(r"^GIF8[7,9]a") : ["GIF", gifsize]} # type_map_match to get MIME-TYPE and callback function def type_map_match(buffer): for rx in type_map.keys(): if rx.match(buffer): return type_map[rx] else: return None # Recognize image headers # def what(filename): try: f = open(filename, "rb") h = f.read(512) except IOError: print "IOError %s\n" % os.error finally: if f: f.close() m = type_map_match(h) if m: return m[0] return None # size: size a image from buffer # def size(buffer): m = type_map_match(buffer) if m: return (m[1])(StringIO.StringIO(buffer)) else: return (None, None, None, "Unable to Recognize image file format") # imgsz: size a image by file name # def imgsz(path): (type, x, y, error) = (None, None, None, "Unable to Recognize image file format") f = None try: f = open(path, "rb") header = f.read(256) f.seek(0) m = type_map_match(header) if m: (type, x, y, error) = (m[1])(f) except: print "IOError %s\n" % os.error return None finally: if f: f.close() return (type, x, y, error) if __name__ == "__main__": for filename in [f for f in os.listdir(".") if os.path.isfile(f)]: print filename, imgsz(filename) > > A quick google found me this:http://www.pythonware.com/library/pil/handbook/introduction.htm > > but it looks like it is something I will need to install - I'd like to > be able to pass my script around to people without them needing any > additional modules > > Any help would be fantastic! > > Cheers > > Adam > python 2.3.5 > osx 10.4.9 From s.mientki at id.umcn.nl Fri Jun 22 04:24:19 2007 From: s.mientki at id.umcn.nl (stef) Date: Fri, 22 Jun 2007 10:24:19 +0200 Subject: configparser shuffles all sections ? In-Reply-To: References: Message-ID: <759a$467b8733$83aef404$27613@news2.tudelft.nl> Marc 'BlackJack' Rintsch wrote: > In , stef wrote: > > >> I just used configparser for the first time and discovered that it >> shuffled all my sections, and the contents of the sections too. >> > > The data is stored in dictionaries. > So there should be some way to sort it ? > >> This makes human manipulation of the file impossible. >> > > Why so? > I've about 1000 sections ;-) > Ciao, > Marc 'BlackJack' Rintsch > thanks, Stef Mientki From tjreedy at udel.edu Sat Jun 9 12:12:53 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 9 Jun 2007 12:12:53 -0400 Subject: Python's "only one way to do it" philosophy isn't good? References: <1181368143.874341.273140@r19g2000prf.googlegroups.com> Message-ID: "James Stroud" wrote in message news:E5vai.858$TC1.722 at newssvr17.news.prodigy.net... | Terry Reedy wrote: | > In Python, you have a choice of recursion (normal or tail) | | Please explain this. I am working on a paper for Python Papers that will. It was inspired by the question 'why doesn't Python do tail-recursion optimization'. tjr From joe at incomps.com Mon Jun 4 18:01:26 2007 From: joe at incomps.com (Joe) Date: Mon, 4 Jun 2007 16:01:26 -0600 Subject: MySQL InterfaceError Message-ID: <001e01c7a6f3$e687ed40$0f01a8c0@desktop9> I still consider myself a newbie, and being new to the list I request that you take it easy on me. ;) We're running a RHEL LAMP server with the mod_python publisher interpreter. The MySQLdb module seems to be giving me more problems than I had hoped for. With a fresh restart of apache, all programs run flawlessly for an average of 7-8 executions, but then will return an InterfaceError. The last few lines of the traceback are as follows: File "build/bdist.linux-i686/egg/MySQLdb/cursors.py", line 147, in execute charset = db.character_set_name() InterfaceError: (0, '') This InterfaceError will continue sporadically about half of the time the programs are run. We are running mysql version 4.1.2 so I was assuming it may be caused by the mysql_character_set_name() bug (as shown in the comments here: http://dev.mysql.com/doc/refman/5.0/en/mysql-character-set-name.html), but this was ruled out when the error continued after hard coding the charset as utf8. As you can see, without any error description this is very hard to debug. I have spent several days researching this and have come up empty handed. I would appreciate any help anyone can give. If this is the wrong list to ask, please let me know and I will repost elsewhere. Versions: Python: 2.5.1 MySQL: 4.1.2 MySQLdb: 1.2.2 Thanks! Jough -------------- next part -------------- An HTML attachment was scrubbed... URL: From durumdara at gmail.com Fri Jun 8 03:18:00 2007 From: durumdara at gmail.com (durumdara) Date: Fri, 08 Jun 2007 07:18:00 -0000 Subject: Where can I suggest an enchantment for Python Zip lib? In-Reply-To: <46684DB8.6080900@websafe.com> References: <46684DB8.6080900@websafe.com> Message-ID: <1181287080.398800.194140@q75g2000hsh.googlegroups.com> Hi Larry! > durumdara wrote: > You can easily find out roughly how many bytes are in your .ZIP archive > by using following: > > zipbytes=Zobj.fp.tell() > The main problem is not this. I want to write a backup software, and I want to: - see the progress in the processing of the actual file - abort the progress if I need it If I compress small files, I don't have problems. But with larger files (10-20 MB) I get problems, because the zipfile's method is uninterruptable. Only one way I have to control this: if I modify the ZipFile module. dd On Jun 7, 8:26 pm, Larry Bates wrote: > Where Zobj is your zipfile instance. You don't need a callback. > > Problem is ill defined for a better solution. You don't know how much > the "next" file will compress. It may compress a lot, not at all or > in some situations actually grow. So it is difficult (impossible?) to > know how many bytes are remaining. I have a rough calculation where > I limit the files to 2Gb, but you must set aside some space for the > table of contents that gets added at the end (whose size you don't > actually know either). So I use: > > maxzipbytesupperlimit=int((1L<<31)-(8*(1<<20))) > > That is 2Gb-8Mb maximum TOC limit of a zip file. > > I look at zipbytes add the uncompressed size of the next file, if it > exceeds maxzipbytesupperlimit, I close the file and move to the next > zip archive. If it is smaller, I add the file to the archive. > > Hope this helps. > > -Larry From carsten at uniqsys.com Tue Jun 12 07:50:41 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Tue, 12 Jun 2007 07:50:41 -0400 Subject: Multiline lamba implementation in python. In-Reply-To: <1181640571.992908.324090@r19g2000prf.googlegroups.com> References: <1b0ce1b60706112002i761dc295x9ba9c4f589c41db1@mail.gmail.com> <1181640571.992908.324090@r19g2000prf.googlegroups.com> Message-ID: <20070612114740.M2188@uniqsys.com> On Tue, 12 Jun 2007 02:29:31 -0700, exhuma.twn wrote > lambdas are to be removed in Py3k IIRC. No. From http://www.python.org/dev/peps/pep-3099/, "At one point lambda was slated for removal in Python 3000. Unfortunately no one was able to come up with a better way of providing anonymous functions. And so lambda is here to stay." -- Carsten Haese http://informixdb.sourceforge.net From Leo.Kislov at gmail.com Fri Jun 8 05:33:45 2007 From: Leo.Kislov at gmail.com (Leo Kislov) Date: Fri, 08 Jun 2007 02:33:45 -0700 Subject: How to wrap a Japanese text in Python In-Reply-To: <1181294682.827135.306850@n15g2000prd.googlegroups.com> References: <1181218336.318399.59910@w5g2000hsg.googlegroups.com> <1181294682.827135.306850@n15g2000prd.googlegroups.com> Message-ID: <1181295225.424266.4360@n15g2000prd.googlegroups.com> On Jun 8, 2:24 am, Leo Kislov wrote: > On Jun 7, 5:12 am, prashantkisanpa... at gmail.com wrote: > > > Hi All, > > > I am trying to wrap a japanese text in Python, by the following code. > > > if len(message) > 54: > > message = message.decode("UTF8") > > strlist = textwrap.wrap(message,54) > > > After this I am wirting it to you a CAD Software window. While > > displaying in this window some Japanese characters at the end of the > > line & some at the begining of the line are not displayed at all. > > Meaning the text wrapping is not happening correctly. > > > Can any body please help me out in resolving this problem. > > First of all you should move message.decode('utf-8') call out of "if" > and you don't need "if" anyway because if the line is less than 54 > textwrap won't touch it: > > message = message.decode('utf-8') > strlist = textwrap.wrap(message, 54) > > I don't know Japanese but the following example *seems* to work fine > for me: > > # -*- coding: utf-8 -*- > sample=u""" > """ > > import textwrap > for line in textwrap.wrap(sample, 6): > print line > -------------------------------- > Result: Oh, my. IE7 and/or Google groups ate my Japanese text :( But I hope you've got the idea: try to work on a small example python program in a unicode-friendly IDE like for example IDLE. > Can you post a short example that clearly demonstrates the problem? This question is still valid. -- Leo. From gagsl-py2 at yahoo.com.ar Mon Jun 4 19:32:32 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 04 Jun 2007 20:32:32 -0300 Subject: Embedding Python in C References: <1180969118.795850.15160@w5g2000hsg.googlegroups.com> Message-ID: En Mon, 04 Jun 2007 11:58:38 -0300, escribi?: > Onwards to the problem, I have been having difficulty embedding a > python module into my C/C++ program. (just a test program before > moving on into the real thing). I have been making test runs using the > codes from http://docs.python.org/ext/pure-embedding.html as a basic, > but modifiying it now as a function inside my C/C++ code. > > Problem started when I started passing an array as an argument. The > module also need an array as an argument, but somehow I can't make > them to go pass the "input-error checking" of the module. > > The code for argument building and calling are as follows: > > void CallSnake(char ModName[], char FuncName[], double result[]) > { > ... > /*Some operations to import modname, and preping FuncName, all is > ok*/ > ... > /*Processing the result array and calling the function, problem > time*/ > pArgs = PyTuple_New(MAX_ELEMENT); Should check for a NULL return value. > pArg = PyList_New(1); Same here. > for (i = 0; i < MAX_ELEMENT; ++i) > { > pValue = Py_BuildValue("d", result[i]); I'd use PyFloat_FromDouble here. > PyTuple_SetItem(pArgs, i, pValue); > > if (!(*pArgs).ob_refcnt) What do you expect from this? pArgs is a newly created tuple - unless you DECREF it explicitely, ob_refcnt should never be 0. (Also, the -> operator exists for exactly this usage). > PyList_SetItem(pArg, 0, pArgs); > pValue = PyObject_CallFunctionObjArgs(pFunc,pArg,NULL); You didn't show us how you got pFunc here. Just to make it clear, you are calling pFunc with a single argument, which is a list that contains a single element, which is a tuple containing exactly MAX_ELEMENT float objects. > Traceback > if x.ndim != 1; /*x is the input array, checking if it's a 1D*/ > AttributeError: 'list' object has no attribute 'ndim' Python lists don't have a ndim attribute. Perhaps you want some kind of Numeric array? (ndarray?) > I have been trying many call variations, but alas, I think the problem > lies in the list building process. I have no problems calling a non- > arrayed (albeit,still single) argument. Yes, it appears that you are building a plain list but your code is expecting another kind of object. I'm unfamiliar with Numeric arrays, if that is what you need; perhaps someone else can help, or ask again in a Numeric-specific list. -- Gabriel Genellina From ivoras at __fer.hr__ Sat Jun 23 10:43:39 2007 From: ivoras at __fer.hr__ (Ivan Voras) Date: Sat, 23 Jun 2007 16:43:39 +0200 Subject: high performance/threaded applications in Python - your experiences? In-Reply-To: References: Message-ID: Jay Loden wrote: > I was hoping for some experiences that some of you on the list may have had in dealing with Python in a high performance and/or threaded environment. In essence, I'm wondering how big of a deal the GIL can be in a real-world scenario where you need to take advantage of multiple processor machines, thread pools, etc. How much does it get in the way (or not), and how difficult have you found it to architect applications for high performance? I have read a number of articles and opinions on whether or not the GIL is a good thing, and how it affects threaded performance on multiple processor machines, but what I haven't seen is experiences of people who have actually done it and reported back "it was a nightmare" or "it's no big deal" ;) The theory: If your threads mostly do IO, you can get decent CPU usage even with Python. If the threads are CPU-bound (e.g. you do a lot of computational work), you'll effectively only make use of one processor. In practice, I've noticed that Python applications don't scale very much across CPUs even if they're doing mostly IO. I blame cache trashing or similar effect caused by too many global synchronization events. I didn't measure but the speedup may even be negative with large-ish number of CPUs (>=4). OTOH, if you can get by with using forking instead of threads (given enough effort) you can achieve very good scaling. -- (\__/) (O.o) (> < ) This is Bunny. Copy Bunny into your signature to help him on his way to world domination! -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 258 bytes Desc: OpenPGP digital signature URL: From martin at v.loewis.de Mon Jun 25 17:17:38 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Mon, 25 Jun 2007 23:17:38 +0200 Subject: Chroot Jail Not Secure for Sandboxing Python? In-Reply-To: <1182782910.811850.284350@u2g2000hsc.googlegroups.com> References: <1182748892.916068.146780@p77g2000hsh.googlegroups.com> <467f55f7$0$20850$9b622d9e@news.freenet.de> <1182782910.811850.284350@u2g2000hsc.googlegroups.com> Message-ID: <468030f2$0$22933$9b622d9e@news.freenet.de> > The os.exec call prepends the chroot directory to the absolute path, > but does NOT provide chroot for the child process. However, as long > as the environment is maintained, which contains an LD_PRELOAD, the > "chroot" will also be maintained. If LD_PRELOAD is removed or > ignored, then the chroot is ineffective. As others have mentioned (which I just repeat for additional support): Your ISP is probably thinking of fakeroot, which is entirely unlike chroot(2), with the latter being a proper kernel mechanism, not dynamic library trickery (which would indeed be easy to break out of). Regards, Martin From bdesth.quelquechose at free.quelquepart.fr Sat Jun 30 00:04:01 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sat, 30 Jun 2007 06:04:01 +0200 Subject: PEP 3107 and stronger typing (note: probably a newbie question) In-Reply-To: <7xps3e3g9x.fsf@ruckus.brouhaha.com> References: <1182369568.941307.316260@p77g2000hsh.googlegroups.com> <5dveb4F360un0U1@mid.individual.net> <467a9209$0$22165$426a74cc@news.free.fr> <1182858785.886469.93060@n60g2000hse.googlegroups.com> <46824d8d$0$2324$426a74cc@news.free.fr> <4682eddc$0$23164$426a74cc@news.free.fr> <5ehokpF38ov3jU2@mid.individual.net> <4683d5cd$0$8993$426a74cc@news.free.fr> <7xps3e3g9x.fsf@ruckus.brouhaha.com> Message-ID: <468565a0$0$3686$426a74cc@news.free.fr> Paul Rubin a ?crit : > Bruno Desthuilliers writes: > >>Nope, he just asserted something wrong. Static typing is for compiler >>optimization. Type checking is at most a side effect, and in some >>languages (at least C, C++ and Java) can be totally defeated (usually >>using typecasting). > > > "Definitions of type system vary, but the following one due to > Benjamin C. Pierce roughly corresponds to the current consensus in > the programming language theory community: > > [A type system is a] tractable syntactic method for proving the > absence of certain program behaviors by classifying phrases > according to the kinds of values they compute. (Pierce 2002)." Is this supposed to contradict my assertion that *static* typing is for compilers ? C (and C++) are statically typed. It's usually agreed that C is weakly typed, and that C++ is somewhat more strongly typed. In both cases, you can totally defeat compile-time type-checking, with possibly some very unpredictable results. Python is dynamically typed, but doesn't allow the kind of results you can get from a C typecast. > -- http://en.wikipedia.org/wiki/Type_theory#Type_system > C and C++ are basically untyped languages. Hem... This assertion is at least debatable. Care to post this on c.l.c or c.l.c++, so we get some feedback ? > Java casts can only > partially defeat its type system, In Java, an erroneous typecast will result in a runtime error. Where's the benefit of static typechecking if you can get type errors at runtime? From kw at codebykevin.com Thu Jun 7 11:45:47 2007 From: kw at codebykevin.com (Kevin Walzer) Date: Thu, 07 Jun 2007 11:45:47 -0400 Subject: Tkinter custom drawing In-Reply-To: <1181224696.484887.29980@q66g2000hsg.googlegroups.com> References: <1181224696.484887.29980@q66g2000hsg.googlegroups.com> Message-ID: <18ffa$4668282d$4275d90a$7087@FUSE.NET> Xavier B?rard wrote: > > Now, the problem, is that I have already plenty of widgets on my > screen. I just want to draw over them, which is a bit difficult in my > comprehension of things. > What are you trying to achieve by "drawing over" widgets? -- Kevin Walzer Code by Kevin http://www.codebykevin.com From michele.simionato at gmail.com Tue Jun 5 00:21:30 2007 From: michele.simionato at gmail.com (Michele Simionato) Date: Tue, 05 Jun 2007 04:21:30 -0000 Subject: Python rocks In-Reply-To: <4661da4f$0$19227$fa0fcedb@news.zen.co.uk> References: <4661adda$0$19256$da0feed9@news.zen.co.uk> <4661da4f$0$19227$fa0fcedb@news.zen.co.uk> Message-ID: <1181017290.927175.141260@p47g2000hsd.googlegroups.com> On Jun 2, 10:59 pm, Mark Carter wrote: > Josiah Carlson wrote: > > Mark Carter wrote: > >> Not that I'm particularly knowledgeable about language design issues, > >> but maybe closures and slightly different scoping rules would be nice. > > > Python has had closures for years. > > I just looked uphttp://www.secnetix.de/~olli/Python/lambda_functions.hawk > and was amazed to discover that you were right. Nice one. I am not sure why you posted that link. Closures have nothing to do with lambda functions (if lambdas were removed, Python would have closures still) and it is shows idioms which are now deprecated or that have better alternative using list or generator-expressions, generators, and the itertools module. So my advice is to forget about that link and to read the standard library more ;) Michele Simionato From anno4000 at radom.zrz.tu-berlin.de Thu Jun 21 05:51:52 2007 From: anno4000 at radom.zrz.tu-berlin.de (anno4000 at radom.zrz.tu-berlin.de) Date: 21 Jun 2007 09:51:52 GMT Subject: The Modernization of Emacs References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182344981.372713.298580@w5g2000hsg.googlegroups.com> <86y7ieoiv7.fsf@lola.quinscape.zz> <1182378809.880265.314150@o61g2000hsh.googlegroups.com> Message-ID: <5dv01oF36ms9vU1@mid.dfncis.de> Dave Hansen wrote in comp.lang.perl.misc: > Speaking of which, vi is a piece of wombat do. ;-) You can have Emacs when you pry it from my cold hypertrophied escape-pressing pinky! Anno From montyphyton at gmail.com Sun Jun 3 15:47:02 2007 From: montyphyton at gmail.com (montyphyton at gmail.com) Date: Sun, 03 Jun 2007 12:47:02 -0700 Subject: how can I get the name of a method inside it? In-Reply-To: <466315ba$0$980$426a74cc@news.free.fr> References: <466315ba$0$980$426a74cc@news.free.fr> Message-ID: <1180900022.438501.197540@q69g2000hsb.googlegroups.com> > I would like to know if it's possible to retrieve the name of a method when > you're inside it. For example, in the following script, I would like to > assign _s so that it prints "you are in method1". > > > *************************************** > class Obj1: > def __init__(self): > ... > > def method1(self): > _s = ??? > print "you are in %s" % _s > > x = Obj1() > x.method1() i'm no expert on the subject, but AFAIK, there's no way to do this. why not just print "you are in method1"? what are you exactly trying to do? From showell30 at yahoo.com Tue Jun 12 19:42:23 2007 From: showell30 at yahoo.com (Steve Howell) Date: Tue, 12 Jun 2007 16:42:23 -0700 (PDT) Subject: SimplePrograms challenge In-Reply-To: <_cednbcKePXYt_LbnZ2dnUVZ_u3inZ2d@comcast.com> Message-ID: <21060.3276.qm@web33505.mail.mud.yahoo.com> --- Steven Bethard wrote: > # print the first 100 primes > for prime in itertools.islice(iter_primes(), > 100): > print prime > Sure. FWIW, in the example I posted, I kept the output loop a little more pedestrian (using an if/break idiom), and I printed primes less than 100, not the first 100 primes. I still find itertools a little magical at times, so I want to keep it limited to places where it really simplifies an algorithm. ____________________________________________________________________________________ Building a website is a piece of cake. Yahoo! Small Business gives you all the tools to get online. http://smallbusiness.yahoo.com/webhosting From ping.nsr.yeh at gmail.com Fri Jun 15 10:15:37 2007 From: ping.nsr.yeh at gmail.com (Ping) Date: Fri, 15 Jun 2007 14:15:37 -0000 Subject: a_list.count(a_callable) ? In-Reply-To: References: <1181850818.567840.251090@x35g2000prf.googlegroups.com> <1181853479.914070.217270@i13g2000prf.googlegroups.com> <1181855184.511137.100870@z28g2000prd.googlegroups.com> Message-ID: <1181916937.648267.163070@z28g2000prd.googlegroups.com> > > sum(1 for i in a_list if a_callable(i)) > > -- > Carsten Haesehttp://informixdb.sourceforge.net This works nicely but not very intuitive or readable to me. First of all, the generator expression makes sense only to trained eyes. Secondly, using sum(1 ...) to mean count() isn't very intuitive either. I would still prefer an expression like a_list.count(a_callable), which is short, clean, and easy to understand. :) However, it does produce ambiguities if a_list is a list of callables. Should the count() method match values or check return values of a_callable? There are several possible designs but I'm not sure which is better. Ping From goon12 at gmail.com Sat Jun 9 10:56:39 2007 From: goon12 at gmail.com (Joe Riopel) Date: Sat, 9 Jun 2007 10:56:39 -0400 Subject: VIM editor question In-Reply-To: <1181393067.068779.265610@g4g2000hsf.googlegroups.com> References: <1181393067.068779.265610@g4g2000hsf.googlegroups.com> Message-ID: <6a2ccd190706090756y48c308b3l450162f41d107b0a@mail.gmail.com> I use vim on both Windows and UNIX/Linux, and found this vimrc file. http://darksmile.net/software/.vimrc.html It's pretty good and has good comments. You might want to take a look at that and customize it. Plus this is great: http://www.usf.uni-osnabrueck.de/infoservice/doc/localhtml/vim/if_python.html From facundo at taniquetil.com.ar Fri Jun 8 08:32:16 2007 From: facundo at taniquetil.com.ar (Facundo Batista) Date: Fri, 8 Jun 2007 12:32:16 +0000 (UTC) Subject: ftplib error- Large file References: <1181147997.268014.50550@i38g2000prf.googlegroups.com> <1181207449.968884.158930@n15g2000prd.googlegroups.com> <1181241364.556715.303890@q19g2000prn.googlegroups.com> Message-ID: half.italian at gmail.com wrote: > Ok. I guess that makes sense. But what about the other > questions...mainly: Why would it throw an exception even though the > file was properly transferred? Je, well, I answered the one I knew about, :) Regarding the error... es hard to say. What happens if you transmit the file using a standard ftp program? Or better, could you sniff your network to see what is the TCP dialog? > I guess this could be blamed on the FTP server. Maybe. Maybe not... -- . Facundo . Blog: http://www.taniquetil.com.ar/plog/ PyAr: http://www.python.org/ar/ From gkkvishnu at gmail.com Mon Jun 4 14:19:08 2007 From: gkkvishnu at gmail.com (vishnu) Date: Mon, 4 Jun 2007 23:49:08 +0530 Subject: Python for embedded systems with memory constraints Message-ID: Hi there, I am embedding python 2.5 on embedded system running on RTOS where I had strict memory constraints. As python is a huge malloc intensive application, I observed huge memory fragmentation in my system which is leading to out of memory after running few scripts. So I decided to re-initialise the python with out restarting the whole python. I tried to use Py_Finalise() after completion of each script , then call Py_Initialise as is done in below link. http://mail.python.org/pipermail/python-list/2001-November/114253.html Which in every loop it causes a leak of 10K and after some iterations it leaks of 200K etc. After few more runs this crashes. I read some where this leak was solved in 2.5, but with 2.5 also I am having problems.... And also I found Py_Finalise does not completely cleanup the memory, So how do I re-initialise my memory pool? Does anybody faced this problem earlier and got any solution hack to run the python for a embedded system within own managed memory pool of say 10MB? Any help/ideas are greatly appreciated!. Thanks in advance. From paddy3118 at googlemail.com Sat Jun 23 16:52:22 2007 From: paddy3118 at googlemail.com (Paddy) Date: Sat, 23 Jun 2007 20:52:22 -0000 Subject: Collections of non-arbitrary objects ? In-Reply-To: <1182620734.940718.196520@e16g2000pri.googlegroups.com> References: <1182449993.223262.229500@z28g2000prd.googlegroups.com> <87k5twx4hf.fsf@benfinney.id.au> <1182559502.069773.321620@i38g2000prf.googlegroups.com> <87wsxvrzsj.fsf@benfinney.id.au> <1182620734.940718.196520@e16g2000pri.googlegroups.com> Message-ID: <1182631942.876809.262930@n60g2000hse.googlegroups.com> On Jun 23, 6:45 pm, walterbyrd wrote: > On Jun 22, 11:43 pm, Ben Finney > wrote: > > > Can you help us understand, by showing a use case that would in your > > estimation be improved by the feature you're describing? > > Suppose you are sequentially processing a list with a routine that > expects every item to be of a certain type. Something in the list that > doesn't conform to the type could give you unexpected results, maybe > crash your application. > > In python, as far as I know, there is nothing built into the language > to keep any type of item from being included in a list - or any such > structure. To me, that seems like a potentially vulnerability. > Especially since variables in python do not have to be explicitly > assigned - another variable that points to the same thing, could > change the data that a variable points to. Reminds me a bit of that (awful) sketch: Patient: Doctor doctor it hurts if I do that. Doctor: Well don't do that then. The data for the list should have been checked when it entered your program. It is up to you to then only stuff the list with data expected by the routine. If you don't then Python will most likely throw a runtime exception, but it is up to you to trust your co-workers on the project. - Paddy From mark.martinez2 at gmail.com Tue Jun 19 20:28:57 2007 From: mark.martinez2 at gmail.com (mark.martinez2 at gmail.com) Date: Wed, 20 Jun 2007 00:28:57 -0000 Subject: wxPython - embed separate script in panel? Message-ID: <1182299337.772470.229160@w5g2000hsg.googlegroups.com> This is a wxPython question.. the wxPython group is pretty much inactive. I have an MDI parent frame and child frame set up. In the child frame, I want to use part of the frame to display the output from a .py that is mainly matplotlib (a graph) in a section of the frame. How can I get it to automatically run that script and place the resultant graph in a panel? Thanks From lists at asd-group.com Sat Jun 2 00:47:46 2007 From: lists at asd-group.com (NeBlackCat) Date: Sat, 02 Jun 2007 12:47:46 +0800 Subject: Detecting an active exception In-Reply-To: References: Message-ID: <4660F672.3090600@asd-group.com> I've now also looked at this from a traceback and stack frame walking perspective as well and it seems impossible, ie. it see,s impossible to create a function AmIHandlingAnException() which would behave as follows: try: a=a+1 except: pass try: AmIHandlingAnException() # returns FALSE b = b + 1 except: AmIHandlingAnException() # returns TRUE try: AmIHandlingAnException() # returns TRUE except: pass AmIHandlingAnException() # returns FALSE The only way I can see to do it is to use something like the 'inspect' module to walk up the stack and, for each frame, walk lines of code backwards to determine whether or not you're in an except: block. Of course that would be horribly inefficient. I'm rather stunned by this (this was the 'easy' bit that I left to last!). I can't see a solution unless a) a traceback object is provided for the exception handling path as well as (per sys.exc_info()) the exception creating path, or b) exception handlers are internally treated as new frames (ie. internally, entering an except: clause creates a pseudo-function call to the first handling line). - John Duncan Booth wrote: > "NeBlackCat (lists)" wrote: > > >> Depending on what you read, sys.exc_info() is supposed to return >> (None,None,None) when there is no active exception, but it seems that >> it returns info about the last exception when there isn't one >> currently active. >> >> For example: >> >> try: >> a = a + 1 >> except: >> pass >> >> print sys.exc_info() >> >> produces: >> , > instance at 0x00B5E508>, >> >> Where the traceback object identifies the offending a=a+1 line (of >> course). >> >> Is there another way of doing this? Note that I can't rely on using >> sys.exc_clear() in any solution, unfortunately. >> > > I think you have misunderstood the definition of when an exception is > 'currently active'. When an exception is caught, it remains currently > active so long as you are in the same function, or in a function which it > calls (i.e. so long as the current scope is still active). When you return > from that function the exception is no longer active and the previous > exception becomes active (or None if there has not been one or you have > used sys.exc_clear()). > > Try this: > --------- t.py ------------- > import sys > > def f(): > try: > a = a + 1 > except: > pass > > g() > print "f", sys.exc_info() > > def g(): > print "g", sys.exc_info() > > def h(): > f() > print "h", sys.exc_info() > > h() > ---------------------------- > The output is: > > g (, UnboundLocalError("local variable > 'a' referenced before assignment",), ) > f (, UnboundLocalError("local variable > 'a' referenced before assignment",), ) > h (None, None, None) > > As you can see the exception remains 'currently active' only until the > function in which it was caught returns. > From TimG at sopriswest.com Mon Jun 18 13:29:14 2007 From: TimG at sopriswest.com (Tim Graber) Date: Mon, 18 Jun 2007 11:29:14 -0600 Subject: IPV6 Fatal Error Message-ID: Hello. I am trying to install version 2.5.1 for the first time on our Solaris 10 server (64 bit). When I execute #./config as root user, I get the following error: checking gettaddrinfo bug... buggy Fatal: You must get wroking getaddrinfo() function. or you can specify "--disable-ipv6". My question is, are we to disable ipv6 in some setup file prior to running ./configure? ifconfig -a6 does not return any output. Any information on getting this setup would be greatly appreciated. Thanks. -- Tim -------------- next part -------------- An HTML attachment was scrubbed... URL: From steven.bethard at gmail.com Tue Jun 12 18:06:38 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 12 Jun 2007 16:06:38 -0600 Subject: SimplePrograms challenge In-Reply-To: <87vedsua4o.fsf@merkury.smsnet.pl> References: <1181649968.097585.131780@g37g2000prf.googlegroups.com> <87vedsua4o.fsf@merkury.smsnet.pl> Message-ID: Rob Wolfe wrote: > Steven Bethard writes: >> I'd hate to steer a potential new Python developer to a clumsier > > "clumsier"??? > Try to parse this with your program: > > page2 = ''' > URLs > >
        >
      • some page1
      • >
      • some page2
      • > > ''' If you want to parse invalid HTML, I strongly encourage you to look into BeautifulSoup. Here's the updated code: import ElementSoup # http://effbot.org/zone/element-soup.htm import cStringIO tree = ElementSoup.parse(cStringIO.StringIO(page2)) for a_node in tree.getiterator('a'): url = a_node.get('href') if url is not None: print url >> I know that the wiki page is supposed to be Python 2.4 only, but I'd >> rather have no example than an outdated one. > > This example is by no means "outdated". Given the simplicity of the ElementSoup code above, I'd still contend that using HTMLParser here shows too complex an answer to too simple a problem. STeVe From http Tue Jun 19 22:22:33 2007 From: http (Paul Rubin) Date: 19 Jun 2007 19:22:33 -0700 Subject: Python's "only one way to do it" philosophy isn't good? References: <1181368143.874341.273140@r19g2000prf.googlegroups.com> Message-ID: <7x3b0nmkk6.fsf@ruckus.brouhaha.com> Steven D'Aprano writes: > So, once you've succeeded in your campaign to make Python more like > Scheme, what language will you use for getting real work done? > > And how long will it take before Schemers start agitating for it to become > more like Scheme? While you've dutifully searched the horizon for such intrusion, the rot has been quietly happening from within ;-). Nested scopes, first-class functions and closures, internal lambdas, and lazy evaluation streams (iterators) are all Schemish incursions into Python. List comprehensions and genexps come from even further in the functional-programming "beyond". Soon Python will implement a type system based on the Lambda Cube, well maybe not. :) From adam at hupp.org Thu Jun 21 23:49:38 2007 From: adam at hupp.org (Adam Hupp) Date: Thu, 21 Jun 2007 20:49:38 -0700 Subject: Type of __builtins__ changes from module import to execution? Message-ID: <1182484178.103707.252760@q19g2000prn.googlegroups.com> I've noticed some unexpected behavior with __builtins__ during module import. It seems that during module import __builtins__ is a dict but at all other times it is a module. For example, if the file testmod.py has these contents: print type(__builtins__) print "has str attr", hasattr(__builtins__, 'str') The output differs depending on how it is run: $ python ~/testmod.py has str True vs. $ python -c 'import testmod' has str False Anyone know if there a reason for this behavior? Is it a bug? I've seen this in 2.4 and 3.0. -Adam From michele.simionato at gmail.com Sat Jun 23 10:45:42 2007 From: michele.simionato at gmail.com (Michele Simionato) Date: Sat, 23 Jun 2007 14:45:42 -0000 Subject: Python's "only one way to do it" philosophy isn't good? In-Reply-To: References: <1181368143.874341.273140@r19g2000prf.googlegroups.com> <7x3b0nmkk6.fsf@ruckus.brouhaha.com> Message-ID: <1182609942.245001.274630@q69g2000hsb.googlegroups.com> On Jun 23, 6:11 am, Lenard Lindstrom wrote: > When this thread turned to the topic of macros I did an Internet search > for information on macros relevant to Python. Dylan's macros look > promising. The Python-inspired language Converge has macros (http://convergepl.org/). Michael Hudson's Bytecodehacks package > supports limited Python macros (http://bytecodehacks.sourceforge.net/bch-docs/bch/module-bytecodehack... > ). There is also the __macro__ package, which I still have on my > computer, but I cannot find its home page. > > The __macro__ package simply allows text substitution of source code at > module import time. The bytecodehack.macro module lets one define what > amounts to inlined functions. IMO neither package represents a > productive macro system. And I could find no other attempts to take > Python macros beyond wishful thinking. So until some solid proposal for > Python macros is put on the table any discussion of their merits is > unproductive. I can suggest though that procedural macros are a natural > starting point given the runtime nature of class and function creation. > > -- > Lenard Lindstrom > I would add to your list http://livelogix.net/logix/ and http://www.fiber-space.de/EasyExtend/doc/main/EasyExtend.html Michele Simionato From dave at boost-consulting.com Mon Jun 25 20:30:49 2007 From: dave at boost-consulting.com (David Abrahams) Date: Mon, 25 Jun 2007 20:30:49 -0400 Subject: distutils/setuptools de-installation? Message-ID: <87y7i7zhdy.fsf@grogan.peloton> I've been googling myself silly trying to find an answer to this; my system's package manager is broken until I can solve it. I installed some packages using python setup.py install and I need to remove them. For some packages, python setup.py develop --uninstall is good enough, because it cleans the package out of Python's egg database (wherever that is), although it doesn't delete the eggs themselves. For other packages, PyPgSQL among them, the above command isn't even recognized. This _has_ to be a FAQ, doesn't it? Please help! Thanks, -- Dave Abrahams Boost Consulting http://www.boost-consulting.com The Astoria Seminar ==> http://www.astoriaseminar.com From jimxu at google.com Sun Jun 3 20:35:04 2007 From: jimxu at google.com (Yongjian Xu) Date: Sun, 3 Jun 2007 17:35:04 -0700 Subject: example: 40286 -> 68204 In-Reply-To: <1180916590.000664.249810@z28g2000prd.googlegroups.com> References: <1180916590.000664.249810@z28g2000prd.googlegroups.com> Message-ID: <9c09a1210706031735y66591bd4s75efce33f8c1ed86@mail.gmail.com> Don't think there is one in builtin for that and might have to convert str <-> int to do that too, such as int(str(i)[::-1]) ... Jim On 6/3/07, Shihpin wrote: > > Hi all, > > Is there a fuction that reverse the digits of a number? > > Many thanks, > > Shihpin Lin > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From stefan.behnel-n05pAM at web.de Mon Jun 25 04:47:05 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Mon, 25 Jun 2007 10:47:05 +0200 Subject: Which XML? In-Reply-To: <1182733291.251144.211760@k79g2000hse.googlegroups.com> References: <1182733291.251144.211760@k79g2000hse.googlegroups.com> Message-ID: <467F8109.2000900@web.de> kyosohma at gmail.com wrote: > On Jun 24, 7:04 pm, Bruno Barberi Gnecco > wrote: >> I've found a lot of XML libraries for Python. Any advices on which >> one to use (or *not* to use)? My requirements are: support for XPath, >> stability (a must, segfaults are not an option), with DOM API and good >> performance desirable. > > I use the minidom module for most of my XML work, but I don't think it > has much in the way of XPath. I think lxml might work better for that > sort of thing and I think it's part of ElementTree: > > http://codespeak.net/lxml/dev/objectify.html lxml is not part of ElementTree (only mostly compatible), but it's a must if you want to have a simple API *and* XPath *and* good performance. http://codespeak.net/lxml/ The API is not W3C-DOM compatible, but that's rather a plus IMHO. Stefan From simon at brunningonline.net Fri Jun 8 09:18:05 2007 From: simon at brunningonline.net (Simon Brunning) Date: Fri, 8 Jun 2007 14:18:05 +0100 Subject: Case-Insensitive Sorting of Multi-Dimensional Lists In-Reply-To: <020e01c7a94c$a7970750$0f01a8c0@desktop9> References: <020e01c7a94c$a7970750$0f01a8c0@desktop9> Message-ID: <8c7f10c60706080618m2fabe683i5cf4d9659471c1e1@mail.gmail.com> On 6/7/07, Joe wrote: > > I have a list of lists that I would like to sort utilizing a certain index > of the nested list. I am able to successfully use: > > Import operator > list = [["Apple", 1], ["airplane", 2]] > list.sort(key=operator.itemgetter(0)) > > But, unfortunately, this will be case sensitive (Apple will come before > airplane because the A is capital) and I need it to be insensitive. Try: list.sort(key=lambda el: el[0].lower()) BUT - it's not a good idea to use list as a name, 'cos list is a built-in, and you're obscuring it. -- Cheers, Simon B. simon at brunningonline.net http://www.brunningonline.net/simon/blog/ GTalk: simon.brunning | MSN: small_values | Yahoo: smallvalues From zaperaj at gmail.com Fri Jun 22 23:14:52 2007 From: zaperaj at gmail.com (zaperaj at gmail.com) Date: Fri, 22 Jun 2007 20:14:52 -0700 Subject: Error while installing Python2.5.1 In-Reply-To: <467B65AD.9070108@v.loewis.de> References: <1182413023.924197.302390@o11g2000prd.googlegroups.com> <1182479927.467515.216720@g37g2000prf.googlegroups.com> <1182491487.062013.92940@x35g2000prf.googlegroups.com> <467B65AD.9070108@v.loewis.de> Message-ID: <1182568492.706832.175420@g37g2000prf.googlegroups.com> In the Red Hat installation cd, i saw that there are four rpms for gcc. Now what do i need to do? From andre.roberge at gmail.com Sat Jun 9 16:03:09 2007 From: andre.roberge at gmail.com (=?iso-8859-1?B?QW5kcuk=?=) Date: Sat, 09 Jun 2007 20:03:09 -0000 Subject: Multiple python interpreters within the same process In-Reply-To: References: Message-ID: <1181419389.412390.322680@n4g2000hsb.googlegroups.com> On Jun 9, 5:00 pm, "Marcin Kalicinski" wrote: > How do I use multiple Python interpreters within the same process? > > I know there's a function Py_NewInterpreter. However, how do I use functions > like Py_RunString etc. with it? They don't take any arguments that would > tell on which interpreter to run the string...? > > Marcin You may want to look at the code module http://docs.python.org/lib/module-code.html Andr? From mkb at incubus.de Tue Jun 26 10:16:46 2007 From: mkb at incubus.de (Matthias Buelow) Date: Tue, 26 Jun 2007 16:16:46 +0200 Subject: The Modernization of Emacs: terminology buffer and keybinding In-Reply-To: <1182838964.721578.196400@p77g2000hsh.googlegroups.com> References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182547318.325617.16370@o11g2000prd.googlegroups.com> <1182657564.912472.55570@g4g2000hsf.googlegroups.com> <5eaptcF378d21U3@mid.individual.net> <1182811109.258156.306150@k79g2000hse.googlegroups.com> <1182837690.585067.165060@p77g2000hsh.googlegroups.com> <1182838964.721578.196400@p77g2000hsh.googlegroups.com> Message-ID: <5eclebF37uh5mU1@mid.dfncis.de> Twisted wrote: [...] Hey dude, get back to selling used cars and leave us computer geeks alone, will ya? Thanks. From itsanushshetty at gmail.com Mon Jun 11 17:47:05 2007 From: itsanushshetty at gmail.com (anush shetty) Date: Mon, 11 Jun 2007 21:47:05 -0000 Subject: Link Dictionary In-Reply-To: <1181597543.841494.174920@q69g2000hsb.googlegroups.com> References: <1181593466.934730.299660@i38g2000prf.googlegroups.com> <1181596764.090231.137820@x35g2000prf.googlegroups.com> <1181596912.645709.263270@q75g2000hsh.googlegroups.com> <1181597543.841494.174920@q69g2000hsb.googlegroups.com> Message-ID: <1181598425.966363.56530@g37g2000prf.googlegroups.com> > > Working from your original dict1: > > dout = [[dict2[i], [dict2[k] for k in setvalue]] > for i,setvalue in dict1.iteritems()] > > - Paddy I dont think this works. From s.mientki at id.umcn.nl Fri Jun 8 10:01:16 2007 From: s.mientki at id.umcn.nl (stef) Date: Fri, 08 Jun 2007 16:01:16 +0200 Subject: wxPython / Dabo demo shell ? In-Reply-To: References: <4646a$466901e6$83aef404$30670@news2.tudelft.nl> <4866bea60706080559m55a80f50he95c910eb90f90ed@mail.gmail.com> Message-ID: <65129$4669612c$83aef404$15874@news1.tudelft.nl> Ed Leafe wrote: > On Jun 8, 2007, at 8:59 AM, Chris Mellon wrote: > >> The shell in the wxPython demo (but apparently not in the dabo demo, >> as per Ed's email) is from the wx.py package. It's quite trivial to >> add to your own applications, documentation is at >> http://www.wxpython.org/PyManual.html > > I may be wrong, but I believe that the OP was interested in the > overall frame, contents, and inner workings of the wxPython demo > application (and DaboDemo), not the PyShell interpreter. Yes you're right Ed, I'm interested in the overall demo setup, really beautiful and powerful, just one thing missing (user configurable tree). And if you can copy it, I'm allowed to do so also ;-) thanks, Stef > > -- Ed Leafe > -- http://leafe.com > -- http://dabodev.com > > From half.italian at gmail.com Tue Jun 26 03:53:35 2007 From: half.italian at gmail.com (half.italian at gmail.com) Date: Tue, 26 Jun 2007 07:53:35 -0000 Subject: can't start Apache on Mac OS X--no listening sockets available? In-Reply-To: <1182838193.195172.206160@u2g2000hsc.googlegroups.com> References: <1182824632.015853.317970@g4g2000hsf.googlegroups.com> <1182826067.067254.247940@j4g2000prf.googlegroups.com> <1182838193.195172.206160@u2g2000hsc.googlegroups.com> Message-ID: <1182844415.398825.306380@o11g2000prd.googlegroups.com> On Jun 25, 11:09 pm, 7stud wrote: > > On Jun 25, 7:23 pm, 7stud wrote: > > > > I'm trying to get Apache set up on my system so I can use mod_python. > > > I installed Apache 2.2.4 according to the following instructions: > > > >http://switch.richard5.net/isp-in-a-box-v2/installing-apache-on-mac-o... > > > > and everything seemed to install correctly, but I can't start Apache. > > > I typed in the following command: > > > > $ sudo /Library/Apache2/bin/apachectl start > > > Password: > > > > and I got this error message: > > > > httpd: Could not reliably determine the server's fully qualified > > > domain name, using tms-computer.local for ServerName > > > (48)Address already in use: make_sock: could not bind to address > > > 0.0.0.0:80 > > > no listening sockets available, shutting down > > > Unable to open logs > > > > Any ideas? > > > Do you have "Web Sharing" in the prefs on as well? > > I checked and to my surprise Personal Web Sharing was turned on. I > was messing around with it yesterday because I thought that might have > something to do with my problems, but I couldn't get Personal Web > Sharing to start--it just said "Web Sharing starting up...", and it > never did. > > Anyway, I turned Personal Web Sharing off, and then the error message > changed to this: > > $ sudo /Library/Apache2/bin/apachectl start > Password: > httpd: Could not reliably determine the server's fully qualified > domain name, using tms-computer.local for ServerName > > However, I checked the All Processes page in the Activity Monitor, and > it said httpd was running. So I tested my apache installation by > typing http:/localhost in Safari's address bar, and a page displayed > saying "It works!". But I wondered if that page was being served up > by the pre-installed version of Apache or my new installation. So, I > went into my new installation's directory and looked at the file: > > /Library/Apache2/htdocs/index.html > > and changed the text from "It works!" to "Apache 2.2.4", but when I > retyped http:/localhost in Safari's address bar, I still got a page > saying "It works!", so that page is not being served by my new > installation. Console and the system logs are an invaluable debugging tool on Macs. Bet you have some errors there saying why apache couldnt stop/start. Glad you got it working. ~Sean From bbxx789_05ss at yahoo.com Sat Jun 16 12:24:38 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: Sat, 16 Jun 2007 09:24:38 -0700 Subject: Want to learn Python In-Reply-To: References: <1181907696.878873.214760@i13g2000prf.googlegroups.com> <1181950960.793735.304570@c77g2000hse.googlegroups.com> <1hzrppt.1i3pamvoxog4rN%aleax@mac.com> Message-ID: <1182011078.358795.151590@c77g2000hse.googlegroups.com> > I'm curious, have you tried _Python for Dummies_? No, I haven't. Unfortunately, I don't ever consider Dummies books. That type of marketing appeals to certain people and not others. I'm one of the others. I'll definitely take a look at it the next time I'm in the bookstore. >We didn't wait for Wiley to offer, we simply insisted on providing a >list of index terms. It's nice to hear about an author who cares enough about the end product that bears their name to insist on quality. I'm so tired of hearing authors whine that the publisher screwed up the book. From rw at smsnet.pl Wed Jun 13 07:56:03 2007 From: rw at smsnet.pl (Rob Wolfe) Date: Wed, 13 Jun 2007 04:56:03 -0700 Subject: SimplePrograms challenge In-Reply-To: References: <466F9329.2020306@gmail.com> Message-ID: <1181735763.199492.164760@q19g2000prn.googlegroups.com> Steve Howell wrote: > I suggested earlier that maybe we post multiple > solutions. That makes me a little nervous, to the > extent that it shows that the Python community has a > hard time coming to consensus on tools sometimes. We agree that BeautifulSoup is the best for parsing HTML. :) > This is not a completely unfair knock on Python, > although I think the reason multiple solutions tend to > emerge for this type of thing is precisely due to the > simplicity and power of the language itself. > > So I don't know. What about trying to agree on an XML > parsing example instead? > > Thoughts? I vote for example with ElementTree (without xpath) with a mention of using ElementSoup for invalid HTML. -- Regards, Rob From nagle at animats.com Sun Jun 24 12:58:17 2007 From: nagle at animats.com (John Nagle) Date: Sun, 24 Jun 2007 16:58:17 GMT Subject: automatical pdf generating In-Reply-To: <1182700820.325024.107040@g4g2000hsf.googlegroups.com> References: <1182700820.325024.107040@g4g2000hsf.googlegroups.com> Message-ID: Jackie wrote: > Hi, all, > > There are 50 folders in my hard driver C: > C:\01.c:\02,...,c:\50 > > There are 4 pictures in each folder: > 1.jpg,2.jpg,3.jpg,4.jpg > > For each folder, I want to print the 4 pictures into a single-paged > pdf file (letter sized; print horizontally). All together, I want to > get 50 pdf files with names: 01.pdf,02.pdf,...,50.pdf. > > Is it possible to use Python to realized the above process? I know > there is a module named "reportlab". Is there any easy command in the > module to do my job? > > Thanks > > Jackie > Generate HTML for such pages, open them with OpenOffice, and have OpenOffice generate the PDF file. John Nagle From mukundjha at gmail.com Tue Jun 12 13:32:38 2007 From: mukundjha at gmail.com (reverse_gear) Date: Tue, 12 Jun 2007 17:32:38 -0000 Subject: Tamil/Indian Languages Support in Tkinter Message-ID: <1181669558.321094.111440@d30g2000prg.googlegroups.com> hi, Does Tkinter has support for tamil/Indian Languages?? I tried this code it is able to print both tamil and german text on console.. but on Tkinter Label it is printing only the german code Plz help from Tkinter import * import codecs german_ae = unicode('\xc3\xa4','utf-8') tamil_text = unicode('\xe0\xae\xb9\xe0\xae\xbf \xe0\xae\xae\xe0\xaf \x81\xe0\xae\x95\xe0\xaf\x81\xe0\xae\xa9\xe0\xaf\x8d\xe0\xae\x9f \xe0\xaf\x8d','utf-8') root = Tk() print tamil_text print german_ae label = Label(root, text = german_ae) label2= Label(root, text = tamil_text) label.pack() label2.pack() mainloop() Thanks From kyosohma at gmail.com Sun Jun 3 23:53:43 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Mon, 04 Jun 2007 03:53:43 -0000 Subject: excel library without COM In-Reply-To: <1180918791.467050.186520@r19g2000prf.googlegroups.com> References: <1180918791.467050.186520@r19g2000prf.googlegroups.com> Message-ID: <1180929223.344737.267860@q69g2000hsb.googlegroups.com> On Jun 3, 7:59 pm, james_027 wrote: > Hi, > > is there any library to help me write excel files without using win > com? because i'll be working on linux platform. At the same time I > could want to perform some formatting, merging of cells. adding sheets > and etc ... > > Thanks > james I'm not aware of any modules. However, this thread is on the same topic and it mentions using html or txt files as possibilities: http://mail.python.org/pipermail/python-list/2002-April/138748.html I would also think that you could write some kind of custom XML parser/ creator that you could use to create the Excel sheet's structure and then interface with COM later. Mike From simon at brunningonline.net Mon Jun 25 15:26:22 2007 From: simon at brunningonline.net (Simon Brunning) Date: Mon, 25 Jun 2007 20:26:22 +0100 Subject: getting the size of an object In-Reply-To: References: Message-ID: <8c7f10c60706251226v1fcd38fen8d21de058088bb63@mail.gmail.com> On 6/18/07, filox wrote: > is there a way to find out the size of an object in Python? e.g., how could > i get the size of a list or a tuple? mxTools includes a sizeof() function. Never used it myself, but MAL isn't notorious for getting things wrong, so I'm sure it does what it says on the tin. http://tinyurl.com/3ybdb3 Cheers, Simon B. simon at brunningonline.net http://www.brunningonline.net/simon/blog/ GTalk: simon.brunning | MSN: small_values | Yahoo: smallvalues From tutufan at gmail.com Thu Jun 28 18:40:39 2007 From: tutufan at gmail.com (tutufan at gmail.com) Date: Thu, 28 Jun 2007 22:40:39 -0000 Subject: Getting some element from sets.Set In-Reply-To: References: <1178258913.095438.173020@h2g2000hsg.googlegroups.com> <1178267029.258868.219800@h2g2000hsg.googlegroups.com> <1178316417.371855.63170@p77g2000hsh.googlegroups.com> <1178725344.400736.210280@n59g2000hsh.googlegroups.com> Message-ID: <1183070439.122407.46670@m36g2000hse.googlegroups.com> On May 9, 11:41 am, Steven Bethard wrote: > $ python -m timeit -s "s = set('abcdef')" "x = s.pop(); s.add(x)" It's interesting that that's faster. I'd be hesitant to use that in a real program because it's so unattractive (as is the '.next()' approach). To me a builtin method would be worthwhile in this case. From edudobay at gmail.com Sat Jun 23 11:13:24 2007 From: edudobay at gmail.com (Eduardo Dobay) Date: Sat, 23 Jun 2007 15:13:24 -0000 Subject: Using PSE under Win32 Message-ID: <1182611604.696515.143930@k79g2000hse.googlegroups.com> Hello, I've been playing around with mod_python these days (using Publisher and PSP), and it has been working smoothly under Windows XP (using Apache 2.2). But when I installed PSE and went to use it with mod_python, it didn't work. The error I get whenever I try to load a PSE page is: Traceback (most recent call last): File "C:\Python25\lib\site-packages\mod_python\importer.py", line 1537, in HandlerDispatch default=default_handler, arg=req, silent=hlist.silent) File "C:\Python25\lib\site-packages\mod_python\importer.py", line 1229, in _process_target result = _execute_target(config, req, object, arg) File "C:\Python25\lib\site-packages\mod_python\importer.py", line 1128, in _execute_target result = object(arg) TypeError: 'module' object is not callable I thought it could be some incompatibility issue between PSE and mod_python, but I tried both installing the PSE binary and building the sources, and it didn't make a difference. Has anyone out there had success using PSE under Windows? (Just for the record, I did install matching versions, at least for Apache (2.2.3), Python (2.5) and mod_python (3.3.1). PSE doesn't seem to have a strict version requirement.) From bruno.42.desthuilliers at wtf.websiteburo.oops.com Fri Jun 15 11:50:36 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Fri, 15 Jun 2007 17:50:36 +0200 Subject: global destructor not called? In-Reply-To: References: Message-ID: <4672b53f$0$31597$426a74cc@news.free.fr> Neal Becker a ?crit : > To implement logging, I'm using a class: If I may ask : any reason not to use the logging module in the stdlib ? > class logger (object): > def __init__ (self, name): > self.name = name > self.f = open (self.name, 'w') > def write (self, stuff): > self.f.write (stuff) > def close (self): > self.f.close() > def flush (self): > self.f.flush() > def reopen (self): > self.f.flush() > self.f.close() > os.rename (self.name, self.name + '.old') > self.f = open (self.name, 'w') > def __del__ (self): > try: > os.remove (self.name + '.old') > except: > pass > > And setting: > sys.stderr = logger(...) > > It seems my cleanup (__del__) is never called, What makes you think so ? > even though I believe my > program exits normally. What's wrong? Not enough data... From john at datavoiceint.com Mon Jun 11 13:05:20 2007 From: john at datavoiceint.com (HMS Surprise) Date: Mon, 11 Jun 2007 10:05:20 -0700 Subject: Repository - file scanner In-Reply-To: <1181515276.379978.136400@z28g2000prd.googlegroups.com> References: <1181331239.609059.320740@g4g2000hsf.googlegroups.com> <1181515276.379978.136400@z28g2000prd.googlegroups.com> Message-ID: <1181581520.733087.253380@q66g2000hsg.googlegroups.com> > > Why not use grep? With Windows XP? jh From nagle at animats.com Tue Jun 12 23:12:04 2007 From: nagle at animats.com (John Nagle) Date: Tue, 12 Jun 2007 20:12:04 -0700 Subject: Python's "only one way to do it" philosophy isn't good? In-Reply-To: References: <1181368143.874341.273140@r19g2000prf.googlegroups.com> Message-ID: Alexander Schmolck wrote: > Steven D'Aprano writes: >>On Mon, 11 Jun 2007 01:28:09 +0100, Alexander Schmolck wrote: >>>Steven D'Aprano writes: >>Don't keep us in suspense. What do you believe is the true reason? > > > It's easier to spot that some rationalization is bogus than to unconver the > true underlying causes; I'm pretty sure it's more a Gestalt thing than a > compelling technical reason. There's a real reason. Remember, functions are dynamically replaceable. The compiler would have to detect that the function doesn't modify or replace itself while recursing for this optimization to be valid. Worst case, another thread could replace the function while it was recursing, invalidating the tail recursion optimization. John Nagle From sebastien_nimp73 Sun Jun 3 15:26:40 2007 From: sebastien_nimp73 (Sébastien Vincent) Date: Sun, 3 Jun 2007 21:26:40 +0200 Subject: how can I get the name of a method inside it? Message-ID: <466315ba$0$980$426a74cc@news.free.fr> I would like to know if it's possible to retrieve the name of a method when you're inside it. For example, in the following script, I would like to assign _s so that it prints "you are in method1". *************************************** class Obj1: def __init__(self): ... def method1(self): _s = ??? print "you are in %s" % _s x = Obj1() x.method1() From aleax at mac.com Thu Jun 28 02:01:59 2007 From: aleax at mac.com (Alex Martelli) Date: Wed, 27 Jun 2007 23:01:59 -0700 Subject: Too many 'self' in python.That's a big flaw in this language. References: <1182942154.185461.89620@e9g2000prf.googlegroups.com> <5efe34F37shinU1@mid.individual.net> Message-ID: <1i0e2aq.1db0o2mbi0je1N%aleax@mac.com> Bjoern Schliessmann wrote: ... > Mh, strange, I personally like to use "this.a" in C++, to make clear > I use an instance variable. That would be nice, unfortunately your C++ compiler will refuse that, and force you to use this->a instead;-). Many programming shops use naming conventions instead, such as my_a or a_ (trailing underscore for member-variables) -- I've even seen the convention this_a which IMHO is silly (at that point you might as well use this->a and avoid the 'convention'!-). Anyway, I essentially agree with you (except for the C++ bit: since this is a pointer, it needs ->). However, full disclosure, Smalltalk/XP superstar Kent Beck disagrees -- in his good book "Test Driven Design by Example", in the chapter where he gives the Python example, he DOES whine against the need to explicitly say self (the one bad bit in the book:-). For the curious: the explicit-self idea is essentially taken from Modula-3, a sadly now forgotten language which still had an impact on the history of programming. Alex From steven.bethard at gmail.com Wed Jun 13 23:42:36 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 13 Jun 2007 21:42:36 -0600 Subject: one-time initialization of class members In-Reply-To: <1181785384.380731.224550@n15g2000prd.googlegroups.com> References: <1181772494.803499.266690@o11g2000prd.googlegroups.com> <1181778902.547599.147960@q19g2000prn.googlegroups.com> <1181785384.380731.224550@n15g2000prd.googlegroups.com> Message-ID: James Turk wrote: > It actually occured to me that I could use a @classmethod to do the > loading and take that out of the BaseClass constructor. What I have > makes more sense and eliminates the unecessary constructors. > > ie. > > class BaseClass: > @classmethod > def loadData(params): > #expensive load here > > class ChildClass1(BaseClass): > dataset = BaseClass.loadData(params) > > This is pretty much along the lines of what you suggested, thank you > for the hint in the right direction. > > I realized that this still doesn't meet my needs exactly as I only > want the expensive dataset to be loaded if/when a class is actually > used (there are potentially many of these and only a few will be > used). Seems like you want a lazy class attribute. How about something like:: >>> class LazyClassAttribute(object): ... def __init__(self, func): ... self.func = func ... def __get__(self, obj, cls=None): ... value = self.func(cls) ... setattr(cls, self.func.__name__, value) ... return value ... >>> class Base(object): ... @LazyClassAttribute ... def dataset(cls): ... print 'calculating dataset' ... return 'dataset(%s)' % cls.params ... >>> class Child1(Base): ... params = 'foo' ... >>> class Child2(Base): ... params = 'bar' ... >>> Child1.dataset calculating dataset 'dataset(foo)' >>> Child1.dataset 'dataset(foo)' >>> Child2.dataset calculating dataset 'dataset(bar)' >>> Child2.dataset 'dataset(bar)' The idea is basically similar to the @classmethod approach except that instead of @classmethod, we use a custom descriptor that calls the method the first time it's accessed and then stores that value afterwards. This means that instead of explicitly calling the @classmethod, the method will be called whenever the attribute is first accessed. STeVe From showell30 at yahoo.com Tue Jun 19 21:40:27 2007 From: showell30 at yahoo.com (Steve Howell) Date: Tue, 19 Jun 2007 18:40:27 -0700 (PDT) Subject: Python's "only one way to do it" philosophy isn't good? In-Reply-To: Message-ID: <339664.96175.qm@web33505.mail.mud.yahoo.com> --- Douglas Alan wrote: > > For the record, I have a huge problem with > NIH-syndrome, and think > that every programming language in the world could > learn a thing or > two from what other languages have gotten right. > Which should includes natural languages in my opinion. As somebody who has long abandoned Perl, I do think the following has some elegance: die if # ... ____________________________________________________________________________________ Boardwalk for $500? In 2007? Ha! Play Monopoly Here and Now (it's updated for today's economy) at Yahoo! Games. http://get.games.yahoo.com/proddesc?gamekey=monopolyherenow From gagsl-py2 at yahoo.com.ar Sun Jun 24 22:42:11 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 24 Jun 2007 23:42:11 -0300 Subject: Help needed to solve this "NameError" References: <1ef9860e0706241917y7d1ee8b0o9da2d4e5ad1c1581@mail.gmail.com> Message-ID: En Sun, 24 Jun 2007 23:17:25 -0300, senthil arasu escribi?: > Hi, > Iam new tp python programming. > > Iam getting compiler error when declaring frame instance as local > variable. > please find the code In Python, indentation (number of spaces at start of lines) is important. Verify your code against the original source (book, tutorial, wherever you got it). Both "def" lines should be indented 1 level (let's say, 4 spaces). All lines between those two, should be indented 2 levels (8 spaces), same indentation for the "hi there!" line. All other lines should be at the left margin. -- Gabriel Genellina From steven.bethard at gmail.com Tue Jun 12 00:03:22 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Mon, 11 Jun 2007 22:03:22 -0600 Subject: Feature request: New string conversion type to ignore list item In-Reply-To: <1181610672.246608.191270@n15g2000prd.googlegroups.com> References: <1181040836.014198.223080@h2g2000hsg.googlegroups.com> <1181042863.724725.128250@p77g2000hsh.googlegroups.com> <1181610672.246608.191270@n15g2000prd.googlegroups.com> Message-ID: <466E1B0A.1080507@gmail.com> pelon wrote: > On Jun 5, 6:27 am, thomas.p... at gmail.com wrote: >> On 5 Jun., 13:12, Peter Otten <__pete... at web.de> wrote: >> >>> or like this: >>>>>> "%s %.s %s" % ("first", "second", "third") >>> 'first third' >> Hey, that's great, thanks Peter! >> >> Tom > > Why not be consistent with other aspects of the language: > > "%s %!s %s" % ("first", "second", "third") You may be interested in the Python 3000 plans, where this is written:: '{0} {2}'.format('first', 'second', 'third') http://www.python.org/dev/peps/pep-3101/ STeVe From head.nancy at gmail.com Wed Jun 6 10:45:28 2007 From: head.nancy at gmail.com (Nancy Head) Date: Wed, 6 Jun 2007 10:45:28 -0400 Subject: FTP/SSL Message-ID: <846ee3740706060745r67eff604j770be015b3b37785@mail.gmail.com> I know basic Python, have basic experience using FTP... but haven't really used the ftplib before. Am trying to read the 18.8 and 7.2 docs but struggling. I'm trying to figure out how to use FTP/SSL (FTPS) - just as a client. Can I do this in Python? Is everything I need in ftplib? Where else do I look? And - any good newbie references on using FTPS? Thanks for any help... Nancy -------------- next part -------------- An HTML attachment was scrubbed... URL: From deets at nospam.web.de Sun Jun 10 07:42:51 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 10 Jun 2007 13:42:51 +0200 Subject: matching objects by a tuple field criterion In-Reply-To: <5d25b6F3215liU1@mid.uni-berlin.de> References: <1181473124.790391.293120@r19g2000prf.googlegroups.com> <5d25b6F3215liU1@mid.uni-berlin.de> Message-ID: <5d26e3F337ov1U1@mid.uni-berlin.de> Diez B. Roggisch schrieb: > bullockbefriending bard schrieb: >> i have a large collection of python objects, each of which contains an >> integer 6-tuple as part of its data payload. what i need to be able to >> do is select only those objects which meet a simple tuple element >> wildcard matching criterion. e.g. given the following python objects: >> >> object A includes tuple (1,2,3,4,5,6) >> object B includes tuple (1,4,4,4,11,1) >> object C includes tuple (1,3,9,1,1,1) >> >> all tuples are unique. for what it's worth, the values in each field >> are independent of the other fields and range from 1 to 14. although >> 'large', my collection is sparse cf. the 14^6 possible tuples. >> >> i want to search on *one only* tuple field/value. if my search >> criterion is (*,*,*,4,*,*), then i want to find object A and object B. >> if (1,*,*,*,*,*), i want to find objects A, B, and C, etc. i will only >> ever specify an integer match for one tuple field. >> >> i can think of some naive approaches, but is there an elegant way to >> do this? > > Depends on what you find elegant. Are the criteria runtime-specified, > and is anything other than the * allowerd, e.g. [1,3,8]? IMHO the best > thing is to create a filter-function that you then use to... filter :) > > Like this: > > def create_filter_predicate(criteria): > """ > criteria is an iterable containing either > an '*' or a list of comma-separated > integers > """ > sub_preds = [] > for i, sub_crit in enumerate(criteria): > if sub_crit == "*": > continue > matching_set = set(int(n) for n in sub_crit.split(",")) > sub_preds.append((i, matching_set)) > def predicate(o): > t = o.my_tuple > for i, ms in sub_preds: > if not t[i] in ms: > return False > return True > return predicate Obviously the docs are faulty - the criteria looks like this: ['*', '1,2,3'] But I think you can get the gist of it - regardless on how the actual criteria are entered. Diez From sergey at fidoman.ru Fri Jun 1 03:51:36 2007 From: sergey at fidoman.ru (Sergey Dorofeev) Date: Fri, 1 Jun 2007 11:51:36 +0400 Subject: subexpressions Message-ID: Hello all! Please help, is there way to use sub-expressions in lambda? For example, if I want to calculate sin(x^2)+cos(x^2) I must code: lambda x: sin(x*x)+cos(x*x) How to make x*x to be evaluated once? From george.sakkis at gmail.com Sun Jun 17 13:02:37 2007 From: george.sakkis at gmail.com (George Sakkis) Date: Sun, 17 Jun 2007 17:02:37 -0000 Subject: Alternative logging packages Message-ID: <1182099757.758015.35110@c77g2000hse.googlegroups.com> I've been growing increasingly weary of the javaesque awkwardness* of the standard library logging package at the point of being willing to give a chance to alternatives. Before I go and try whatever related package there is on PyPI, could anyone that has used them (or is currently using one) comment on how they compare to the standard logging ? George * among other shortcomings, such as unpickleable handlers, absurdly verbose config files, etc. From kinch1967 at gmail.com Sun Jun 10 08:32:57 2007 From: kinch1967 at gmail.com (bullockbefriending bard) Date: Sun, 10 Jun 2007 05:32:57 -0700 Subject: matching objects by a tuple field criterion In-Reply-To: <5d26e3F337ov1U1@mid.uni-berlin.de> References: <1181473124.790391.293120@r19g2000prf.googlegroups.com> <5d25b6F3215liU1@mid.uni-berlin.de> <5d26e3F337ov1U1@mid.uni-berlin.de> Message-ID: <1181478777.274329.276020@g37g2000prf.googlegroups.com> quite so, i rephrased docstring to be: """criteria is an iterable containing either '*' instances or strings of comma-separated integers. e.g. ['*','1,2,3', '11,12']""" thanks very much for the idea! upon further reflection, this seems to be a more elegant solution for my case than the ad-hoc generator or list comprehension approach. this is because i *do* have to filter data based on multiple single field criteria and i know all of these criteria at the same time - so it makes a lot of sense to do as you have done and then only do one filter operation to pull out all the objects i am interested in. From bj_666 at gmx.net Wed Jun 6 03:30:06 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Wed, 06 Jun 2007 09:30:06 +0200 Subject: c[:]() References: <00b301c7a690$25af37d0$240110ac@Muse> <015701c7a7a4$584fac00$240110ac@Muse> Message-ID: In , Steven D'Aprano wrote: > Is there a general Pythonic idiom for efficiently walking over part of a > sequence without copying it first? Should there be? What about using `itertools.islice()`: for e in islice(a, 4): pass Ciao, Marc 'BlackJack' Rintsch From gagsl-py2 at yahoo.com.ar Tue Jun 19 00:54:05 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 19 Jun 2007 01:54:05 -0300 Subject: sizeof() in python References: <7a01f6c00706182020m1c6c58eel334bfcc22ec5566f@mail.gmail.com> Message-ID: En Tue, 19 Jun 2007 00:20:02 -0300, Alvin Delagon escribi?: > Is there a way to know the size of data in python? Like a sizeof feature > in > C? I need this because I have to make a python application that will send > packets at 1-2 kilobytes/sec via UDP. Thank you in advance guys. So you don't need the size of arbitrary data, only the size of your packets. Assuming you use strings (perhaps built using struct.pack) just use len(a_string). -- Gabriel Genellina From sebzzz at gmail.com Mon Jun 18 14:45:46 2007 From: sebzzz at gmail.com (sebzzz at gmail.com) Date: Mon, 18 Jun 2007 11:45:46 -0700 Subject: Parsing HTML, extracting text and changing attributes. In-Reply-To: <4676B809.2010307@web.de> References: <1182175239.122827.4150@g4g2000hsf.googlegroups.com> <4676B809.2010307@web.de> Message-ID: <1182192346.120414.58090@n60g2000hse.googlegroups.com> I see there is a couple of tools I could use, and I also heard of sgmllib and htmllib. So now there is lxml, Beautiful soup, sgmllib, htmllib ... Is there any of those tools that does the job I need to do more easily and what should I use? Maybe a combination of those tools, which one is better for what part of the work? From josiah.carlson at sbcglobal.net Thu Jun 14 02:30:07 2007 From: josiah.carlson at sbcglobal.net (Josiah Carlson) Date: Wed, 13 Jun 2007 23:30:07 -0700 Subject: dynamically generated runtime methods & reflection In-Reply-To: References: Message-ID: Jay Loden wrote: > Hi all, > > First, apologies if anyone gets this twice, but it took me quite a > while to figure out that Python.org is evidently rejecting all mail > from my mail server because I don't have reverse DNS configured. > Anyway: > > I'm not even sure how to phrase this question properly or the right > terminology on this so bear with me. What I'm looking to find out is > > a) is there a functionality in Python where I can call a method I have > not defined ahead of time, and based on the method name, change the > functionality of the method at runtime? Yes. Implement a __getattr__ method on your class (which you mention). > b) if not, what is the "Pythonic" approach to the problem outlined > below? Any recommendations on how to approach the problem differently > are welcome. > > I've googled and read my Python reference pretty extensively and I've > found some hints but nothing that really answered my questions, so > here I am :-) I did figure out that you can overload __getattr__ in > a clas to define a new method at runtime, but I got stuck when I > couldn't figure out how to have a method know what name it was > originally called with. That's the basic question, see below for the > context I'm asking the question in and *why* I want to do the above > :-) Ahh, so you want to pass the method name to the method that you are returning to be called. No problem. >>> import functools >>> >>> class foo: ... def __getattr__(self, name): ... return functools.partial(self.ActualMethod, name) ... ... def ActualMethod(self, name, *args, **kwargs): ... #handle *args and **kwargs based on name! ... print name, args, kwargs ... >>> foo().bar('hello', world=1) bar ('hello',) {'world': 1} >>> - Josiah From kvs at acm.org Tue Jun 26 12:17:53 2007 From: kvs at acm.org (Kathryn Van Stone) Date: Tue, 26 Jun 2007 12:17:53 -0400 Subject: bicycle repair man help Message-ID: On Jun 23, 2007, at 2:24 PM, Rustom Mody wrote: > Does someone know that when using bicycle repair man to refactor > python code what exactly extract local variable means? I don't know about bicycle repair main, but in general 'extract local variable' means to make a change like this: self.method_call(1, ) to value = self.method_call(1, value) i.e, it takes an expression, assigns it to a variable name (which is specified by the user) and then uses that variable name in place of the expression. I would expect that you need to select the expression to be substituted for the refactoring to work. I hope this helps, Kathy Van Stone kvs at acm.org From david.golden at oceanfree.net Sun Jun 24 05:36:35 2007 From: david.golden at oceanfree.net (David Golden) Date: Sun, 24 Jun 2007 10:36:35 +0100 Subject: The Modernization of Emacs: terminology buffer and keybinding References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182272495.990807.99110@a26g2000pre.googlegroups.com> <87tzt3ihev.fsf@kobe.laptop> <1182370216.961241.6960@n60g2000hse.googlegroups.com> <85zm2ufjpb.fsf@lola.goethe.zz> <1182372592.803332.288260@u2g2000hsc.googlegroups.com> <1182373919.262388.100740@c77g2000hse.googlegroups.com> <85r6o6fhkb.fsf@lola.goethe.zz> <1182375045.626510.188170@m36g2000hse.googlegroups.com> <85myyufgwj.fsf@lola.goethe.zz> <1182375528.985142.293900@q69g2000hsb.googlegroups.com> <1182545268.055596.228700@i38g2000prf.googlegroups.com> <1182661040.286559.150880@q75g2000hsh.googlegroups.com> <467e27f1.6428764@news.readfreenews.net> Message-ID: <_Wqfi.20503$j7.378099@news.indigo.ie> Timofei Shatrov wrote: > What an idiot. At least get yourt facts straight before posting such > bullshit. I think at this stage it's quite reasonable to assume he's trolling, and recycling old trolls, too. Certainly looks like someone very like him used to haunt rec.games.roguelike.development as "Neo" and "Twisted One", in the 2005 era. Of course, by bothering to point this out, I'm giving him more attention, the recognition he presumably craves, my bad. http://groups.google.com/group/rec.games.roguelike.development/msg/6f0fac979ef1d117 """ Message-ID: Date: Tue, 22 Mar 2005 19:00:06 -0500 From: Twisted One Emacs doesn't let you do that either. It lets you have exactly two panes. """ http://groups.google.com/group/rec.games.roguelike.development/msg/cfd723fbdc4a93f8 """ From: David Damerell Date: 23 Mar 2005 13:22:00 +0000 (GMT) Message-ID: <4Vw*ETfKq at news.chiark.greenend.org.uk> Quoting Twisted One >Emacs doesn't let you do that either. It lets you have exactly two >panes. No, this is completely false. """ ... So, probably deliberately trolling, or just maybe a learning difficulty - literally (corrected on multiple occasions, still failed to learn). From arkanes at gmail.com Tue Jun 26 11:55:11 2007 From: arkanes at gmail.com (Chris Mellon) Date: Tue, 26 Jun 2007 10:55:11 -0500 Subject: PEP 3107 and stronger typing (note: probably a newbie question) In-Reply-To: References: <1182369568.941307.316260@p77g2000hsh.googlegroups.com> <467a22d0$0$28538$426a74cc@news.free.fr> Message-ID: <4866bea60706260855l7a1153e5t9fd4f63d6df554e7@mail.gmail.com> On 6/26/07, paul wrote: > Bruno Desthuilliers schrieb: > > Stephen R Laniel a ?crit : > >> On Wed, Jun 20, 2007 at 09:41:09PM +0100, Michael Hoffman wrote: > >>> If you asked Java programmers why you couldn't turn *off* Java's static > >>> type checking if you wanted to, you'd probably get a similar response. > >> Perhaps it would help for me to explain what I'd like. > >> > >> Under both Perl and Python, I've found myself > >> having/wanting to write things like so: > >> > >> def my_func( int_arg, str_arg ): > >> try: > >> int_arg = int( int_arg ) > >> str_arg = str( str_arg ) > >> except ValueError: > >> sys.stderr.write( "Args are not of the right type\n" ) > >> sys.exit(1) > >> > > > > Just a question : what will happen if you get rid of the try/except > > block ?-) > > > The error will remain unnoticed and the argument might survive another > few function calls but eventually fails deep down somewhere with: > > TypeError: cannot concatenate 'str' and 'list' objects > > then you have to examine the traceback and hope the real error is > visible somewhere (an argument not conforming to the specification of > the function prototype, or the lack thereof). > In the example given, not catching the example will provide *more* information than the terrible exception handling performed. If you're going to write thick boilerplate to log the values of your locals and arguments around all your functions, I suggest that you not do that and instead make use of the ehanced tracebacks in the cgitb module, which will give you a stack trace with the values of the locals in each stack frame. The only reason to trap an exception is either to redirect the exception (for example, I have a call in a thread which can't be permitted to throw, so exceptions are caught and transfered elsewhere for logging), or to correct the error that caused the exception. Boilerplate like this is at best useless, and in the case of the example given actively worse than simply not catching it at all. From jamesthiele.usenet at gmail.com Sat Jun 9 23:35:04 2007 From: jamesthiele.usenet at gmail.com (James Thiele) Date: Sun, 10 Jun 2007 03:35:04 -0000 Subject: Seattle Python Interest Group meeting 7 PM Thursday Message-ID: <1181446504.432337.310250@z28g2000prd.googlegroups.com> Seattle Python Interest Group meeting 7 PM Thursday 14 June 2007. See http://www,seapig.org for location and directions. From NoSpam at Hccnet.nl Thu Jun 28 18:15:40 2007 From: NoSpam at Hccnet.nl (Hans) Date: Fri, 29 Jun 2007 00:15:40 +0200 Subject: win32event.WaitForInputIdle() returns too soon Message-ID: <4684330c$0$742$3a628fcd@textreader.nntp.hccnet.nl> Hi all, I'm sending keyboard and mouse events to a seperate windows application. I use win32event.WaitForInputIdle() before calling e.g. win32api.keybd_event() However it seems that WaitForInputIdle() returns too soon because some of my events get lost. Now I'v created my own WaitForInputIdle() which calls the one in win32event() and adds an extra sleep(0.1). As expected, this isn't robust. Is this a known issue of win32event.WaitForInputIdle() ? Is it a Windows issue? Is more involved (but not documented in the Python docs)? Any ideas? Thanks Hans From garrickp at gmail.com Fri Jun 22 18:42:52 2007 From: garrickp at gmail.com (Falcolas) Date: Fri, 22 Jun 2007 15:42:52 -0700 Subject: The Modernization of Emacs: terminology buffer and keybinding In-Reply-To: <87wsxviqol.fsf@thalassa.lan.informatimago.com> References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182272495.990807.99110@a26g2000pre.googlegroups.com> <87tzt3ihev.fsf@kobe.laptop> <1182370216.961241.6960@n60g2000hse.googlegroups.com> <85zm2ufjpb.fsf@lola.goethe.zz> <1182372592.803332.288260@u2g2000hsc.googlegroups.com> <1182373919.262388.100740@c77g2000hse.googlegroups.com> <85r6o6fhkb.fsf@lola.goethe.zz> <1182375045.626510.188170@m36g2000hse.googlegroups.com> <1182546050.465987.115740@q19g2000prn.googlegroups.com> <871wg3k8c8.fsf@thalassa.lan.informatimago.com> <1182546979.295368.146110@q19g2000prn.googlegroups.com> <87wsxviqol.fsf@thalassa.lan.informatimago.com> Message-ID: <1182552172.406571.116390@i38g2000prf.googlegroups.com> On Jun 22, 4:12 pm, Pascal Bourguignon wrote: > Anything that the user have to do repeatitively with the GUI, like > copy-and-paste, or reformating of a lot of paragraphs or table > entries, and which is done automatically by writting a one-liner > program in emacs or shell. So the tool they were using did not support macros? You're right, that would suck. I'm guessing this is before you could expose the Unix underpinnings on the mac. I will agree that I do miss much of the standard shell utility when working in windows. Fortunately, I am able to replace a lot of that with well written python or perl scripts. > And they tried to put graphical user interfaces on scripting, it > doesn't work either. Programming is working with text, with verbs. Recording macros could be considered a form of programming, which can have nothing to do with any text. Granted, they're pretty dumb if you don't manually modify them, but really, nothing is stopping you from modifying them either. I can't count the number of times I've created a macro to do repeated modification of a text file. I guess ultimately I'm trying to argue the point that just because a tool was written with a GUI or on Windows does not automatically make it any less a productive tool than a text based terminal tool. Even in windows, you can use the keyboard to do all of your work, if you learn how (thanks to the magic of the alt key). From deets at nospam.web.de Sat Jun 30 12:52:30 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sat, 30 Jun 2007 18:52:30 +0200 Subject: Building a Python app with Mozilla In-Reply-To: References: <5emhodF380g5gU2@mid.uni-berlin.de> Message-ID: <5eng2eF3943nhU1@mid.uni-berlin.de> Sebastian Wiesner schrieb: > [ "Diez B. Roggisch" ] >> And as it has been said in this thread already, Qt has an excellent free >> GUI-builder. > > Free as long as you develop free software. Development of proprietary, > non-gpl software with Qt requires a commercial licence from Trolltech. The OP did debuke Qt because of a lack of a gui-builder, not because of it's licensing. Diez From aleax at mac.com Sat Jun 16 20:14:37 2007 From: aleax at mac.com (Alex Martelli) Date: Sat, 16 Jun 2007 17:14:37 -0700 Subject: Python's "only one way to do it" philosophy isn't good? References: <1181368143.874341.273140@r19g2000prf.googlegroups.com> <1hzrsp4.7vjuav1aegg0tN%aleax@mac.com> <1hzsdrr.wxcx771jwicv5N%aleax@mac.com> <1182007539_10897@sp12lax.superfeed.net> Message-ID: <1hzt8l3.1npcm8u1jroax1N%aleax@mac.com> Cousin Stanley wrote: ... > > I think the Original Sin in that regard was PL/I: it tried to have all ... > > tended to have two or more ways to perform any given task, typically > > inspired by some of the existing languages, often with the addition of > > new ones made out of whole cloth. ... > Cousin Alex .... > > With regards to PL/I a phrase from an old ( 1969 ) song > named "The Night They Drove Old Dixie Down" comes to mind .... > > Ya take what you need and ya leave the rest .... > > I really liked programming in pl/1 I didn't -- been there, hated that. Each project group ended up defining (formally or informally) the subset of PL/I it was using -- and when one had to work with multiple groups, it became yet one more nightmare to recall which features were in the subset of which group(s). If there are just 30 "operations", for each of which the language offers two ways to perform it, that one language becomes over a billion languages when "subsetted" by picking just one choice for each of the operations. Absolutely crazy -- total and utter waste of effort on the part of every programmer, every group, every compiler author. PL/1 is basically gone, but its legacy of "take what you need and leave the rest" is unfortunately alive in other languages that are blind to the enormous advantages of simplicity and uniformity. Alex From usenet at solar-empire.de Fri Jun 22 07:43:37 2007 From: usenet at solar-empire.de (Marc Christiansen) Date: 22 Jun 2007 11:43:37 GMT Subject: Type of __builtins__ changes from module import to execution? References: <1182484178.103707.252760@q19g2000prn.googlegroups.com> Message-ID: <467bb5e9$0$23138$9b4e6d93@newsspool1.arcor-online.net> Adam Hupp wrote: > I've noticed some unexpected behavior with __builtins__ during module > import. It seems that during module import __builtins__ is a dict > but at all other times it is a module. > > For example, if the file testmod.py has these contents: > > print type(__builtins__) > print "has str attr", hasattr(__builtins__, 'str') > > The output differs depending on how it is run: > > $ python ~/testmod.py > > has str True > > vs. > > $ python -c 'import testmod' > > has str False > > Anyone know if there a reason for this behavior? Is it a bug? I've > seen this in 2.4 and 3.0. > > -Adam No, it's not a bug. __builtins__ is an implementation detail. You want __builtin__. See Ciao Marc From bruno.42.desthuilliers at wtf.websiteburo.oops.com Thu Jun 28 11:38:09 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Thu, 28 Jun 2007 17:38:09 +0200 Subject: PEP 3107 and stronger typing (note: probably a newbie question) In-Reply-To: <5ehokpF38ov3jU2@mid.individual.net> References: <1182369568.941307.316260@p77g2000hsh.googlegroups.com> <5dveb4F360un0U1@mid.individual.net> <467a9209$0$22165$426a74cc@news.free.fr> <1182858785.886469.93060@n60g2000hse.googlegroups.com> <46824d8d$0$2324$426a74cc@news.free.fr> <4682eddc$0$23164$426a74cc@news.free.fr> <5ehokpF38ov3jU2@mid.individual.net> Message-ID: <4683d5cd$0$8993$426a74cc@news.free.fr> Bjoern Schliessmann a ?crit : > Bruno Desthuilliers wrote: >> John Nagle a ?crit : > >>> Actually, static typing is for detecting errors before the >>> program is run. >> bruno at bibi ~ $ gcc -ototo toto.c >> bruno at bibi ~ $ ./toto >> Erreur de segmentation >> bruno at bibi ~ $ >> >> You said ? > > Did he say that static typing detects all errors? Nope, he just asserted something wrong. Static typing is for compiler optimization. Type checking is at most a side effect, and in some languages (at least C, C++ and Java) can be totally defeated (usually using typecasting). From half.italian at gmail.com Tue Jun 19 02:45:19 2007 From: half.italian at gmail.com (half.italian at gmail.com) Date: Mon, 18 Jun 2007 23:45:19 -0700 Subject: Windows XMLRPC Service In-Reply-To: References: <1182137125.879556.319030@g37g2000prf.googlegroups.com> Message-ID: <1182235519.964013.146800@a26g2000pre.googlegroups.com> On Jun 18, 2:16 am, "Gabriel Genellina" wrote: > En Mon, 18 Jun 2007 00:25:25 -0300, escribi?: > > > > > > > I'm trying to serve up a simple XMLRPC server as a windows service. I > > got it to run properly, I'm just not sure how to stop it properly. > > Most of the documentation/examples I found for this was from forums, > > so I'd love some links to relevant info also. Here's what I > > have...taken from the cookbook with the xmlrpc server added: > > > def __init__(self, args): > > win32serviceutil.ServiceFramework.__init__(self, args) > > # Create an event which we will use to wait on. > > # The "service stop" request will set this event. > > self.hWaitStop = win32event.CreateEvent(None, 0, 0, None) > > > def SvcStop(self): > > # Before we do anything, tell the SCM we are starting the stop > > process. > > self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) > > > # quit the xmlrpc sever > > self.server.quit() > > What is quit()? As the server may be processing a request I'd move any > finalization code below, after exiting the while loop. > > > > > # And set my event. > > win32event.SetEvent(self.hWaitStop) > > > def SvcDoRun(self): > > # Serve up the XMLRPC forever > > self.server = > > SimpleXMLRPCServer.SimpleXMLRPCServer(("10.0.1.6", 8000)) > > self.server.register_instance(MyClass()) > > self.server.serve_forever() > > > win32event.WaitForSingleObject(self.hWaitStop) > > The simplest solution is to replace serve_forever with a loop waiting on > hWaitStop: > > while WaitForSingleObject(self.hWaitStop, 0)==WAIT_TIMEOUT: > self.server.handle_request() > > Set the socket timeout to a reasonable value (you'll have to wait that > time before exiting). Also, a ThreadingTCPServer may be better if you > expect more than a request at a time. If you search past messages you may > find other ways. > > -- > Gabriel Genellina- Hide quoted text - > > - Show quoted text - I can't quite figure out where to set the "socket timeout". I tried setting win32event.WAIT_TIMEOUT, but I'm pretty sure that's not the variable you were talking about. I did manage to make it multi- threaded by incorporating a different recipe, and I'm beginning to understand the control flow a bit better, but it doesn't seem to be doing what I expect. When SvcStop() is executed and calls win32event.SetEvent(self.hWaitStop), the while loop should break as win32event.WaitForSingleObject(self.hWaitStop, 0) returns zero at this point. But it doesn't do that. What am I missing? import win32serviceutil import win32service import win32event import SocketServer from SimpleXMLRPCServer import SimpleXMLRPCServer,SimpleXMLRPCRequestHandler # Threaded mix-in class AsyncXMLRPCServer(SocketServer.ThreadingMixIn,SimpleXMLRPCServer): pass class MyClass(object): def hello(self): return "Hello World" class SmallestPythonService(win32serviceutil.ServiceFramework): _svc_name_ = "PythonXMLRPC" _svc_display_name_ = "PythonXMLRPC" def __init__(self, args): win32serviceutil.ServiceFramework.__init__(self, args) # Create an event which we will use to wait on. self.hWaitStop = win32event.CreateEvent(None, 0, 0, None) import socket localhost = socket.gethostbyname(socket.gethostname()) self.server = AsyncXMLRPCServer((localhost, 8000), SimpleXMLRPCRequestHandler) def SvcStop(self): self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) win32event.SetEvent(self.hWaitStop) #print "EVENT:", win32event.WaitForSingleObject(self.hWaitStop, 0) # returns 0 here def SvcDoRun(self): self.server.register_instance(MyClass()) #win32event.WAIT_TIMEOUT = 2 --- This just makes the loop never execute because # the WaitFor... part always returns 258 while win32event.WaitForSingleObject(self.hWaitStop, 0) == win32event.WAIT_TIMEOUT: self.server.handle_request() if __name__ == '__main__': win32serviceutil.HandleCommandLine(SmallestPythonService) Thanks for any help! ~Sean From bdesth.quelquechose at free.quelquepart.fr Thu Jun 28 01:00:23 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 28 Jun 2007 07:00:23 +0200 Subject: Too many 'self' in python.That's a big flaw in this language. In-Reply-To: References: <1182942154.185461.89620@e9g2000prf.googlegroups.com> Message-ID: <4682cfde$0$22416$426a74cc@news.free.fr> Jorgen Bodde a ?crit : > I had the same feeling when I started, coming from a C++ background, I > forgot about self a lot, creating local copies of what should be an > assign to a class instance, or methods that could not be found because > I forgot 'self' . > > Now I am 'kinda' used to it, as every language has some draw backs > (you can't please all). But, what about something in between like only > using the dot (.) for a shorter notation? > > self.some_var = True > > Could become: > > .some_var = True > > Which basically shows about the same thing, but you leave 'self' out > of the syntax. Ofcourse it should not be allowed to break a line > between the dot and the keywords, else Python would never know what to > do; > > my_class() > .my_var = True > > Should not be parsed the same as; > > my_class().my_var = True > > Just a suggestion. I am pretty happy with self, but I could settle for > a shorter version if possible. > What is nice with the required, explicit reference to the instance - which BTW and so far is not required to be *named* 'self' - is that it avoids the need for distinct rules (and different implementations) for functions and methods. The different 'method' types are just very thin wrappers around function objects. Which in turn allow to use 'ordinary' functions (defined outside a class) as methods - IOW, to dynamically extend classes (and instances) with plain functions. Uniformity can also have very practical virtues... From james.p.turk at gmail.com Wed Jun 13 20:12:48 2007 From: james.p.turk at gmail.com (James Turk) Date: Thu, 14 Jun 2007 00:12:48 -0000 Subject: one-time initialization of class members In-Reply-To: References: <1181772494.803499.266690@o11g2000prd.googlegroups.com> Message-ID: <1181779968.826315.237740@e9g2000prf.googlegroups.com> On Jun 13, 8:00 pm, Larry Bates wrote: > James Turk wrote: > > Hi, > > > I have a situation where I have some class members that should only be > > done once. Essentially my problem looks like this: > > > class Base(object): > > dataset = None > > > def __init__(self, param): > > if type(self).dataset is None: > > # code to load dataset based on param, expensive > > > class ChildClass1(Base): > > def __init__(self): > > Base.__init__(self, data_params) > > > class AnotherChildClass(Base): > > def __init__(self): > > Base.__init__(self, other_data_params) > > > This seems to work, initialization is only done at the first creation > > of either class. I was just wondering if this is the 'pythonic' way > > to do this as my solution does feel a bit hackish. > > I could be missing something but dataset is shared among all the class > instances. If you reset it based on param it will be reset every time > you create a new instance of the Base class with a different param. Is > that really what you want to do? If so just use: > > class Base(object): > dataset = None > > def __init__(self, param): > if self.dataset is None: > # code to load dataset based on param, expensive > > -Larry I'm sorry, I somehow omitted the fact that the dataset does indeed need to vary based on the child class, actually this is the main difference between child classes. From dfabrizio51 at gmail.com Mon Jun 4 09:35:04 2007 From: dfabrizio51 at gmail.com (chewie54) Date: Mon, 04 Jun 2007 13:35:04 -0000 Subject: python for EE CAD program Message-ID: <1180964104.685598.21330@n4g2000hsb.googlegroups.com> Hi All, I have read some posts on this subject but I haven't been able to make a decision whether to use Python or not. I'm considering converting a Java CAD program to Python/C with wxWdigets for the GUI. I don't have good answers for: 1) Can I use py2exe or pyinstaller to produce an executable for Linux, Windows, and Mac? If not, is there a way it can be done? 2) Is there any way to protect the source code, like obfuscation? 3) Memory footprint of application seems large for python demo. Is this typical for large python applications? I guess the best thing to do is convert a little portion of the Java program and see how it works out with respect to the concerns above. Suggestions and comments appreciated. From martin at v.loewis.de Mon Jun 25 01:43:18 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Mon, 25 Jun 2007 07:43:18 +0200 Subject: Chroot Jail Not Secure for Sandboxing Python? In-Reply-To: <1182748892.916068.146780@p77g2000hsh.googlegroups.com> References: <1182748892.916068.146780@p77g2000hsh.googlegroups.com> Message-ID: <467f55f7$0$20850$9b622d9e@news.freenet.de> gregpinero at gmail.com schrieb: > This wiki page suggests using a chroot jail to sandbox Python, but > wouldn't running something like this in your sandboxed Python instance > still break you out of the chroot jail: > > os.execle ('/usr/bin/python','-c','import os; os.execlp("/bin/sh")', > {}) Depending on how the chroot jail is set up, this command might not work - in the jail, /bin/sh might not exist. > or maybe: > > del os.environ['LD_PRELOAD'] > os.execl ('/usr/bin/python','-c','import os; os.execlp("/bin/sh")') How could deleting LD_PRELOAD help? chroot is not a library trick. It's a mechanism implemented in the operating system. > So is a chroot jail not adequate for sandboxing Python? You have to define your threat model. If the threat to prevent is a malicious user getting at your data, or spreading a virus through your files, then chroot is perfectly adequate. Regards, Martin From marcoberi at gmail.com Wed Jun 6 08:26:12 2007 From: marcoberi at gmail.com (marcoberi at gmail.com) Date: Wed, 06 Jun 2007 12:26:12 -0000 Subject: Tkinter, tkMessagebox and overrideredirect In-Reply-To: References: <1181060331.167762.19180@q69g2000hsb.googlegroups.com> Message-ID: <1181132772.551848.192400@o5g2000hsb.googlegroups.com> On Jun 6, 8:55 am, "Eric Brunel" wrote: > Apparently: Eric, first of all, thanks! > def hello(self): > self.root.after_idle(self.root.lower) > tkMessageBox.showinfo("Popup", "Hello!") Well, this lowers the background frame but I want to keep it visible under the popup. > As an aside, having a window with overrideredirect(1) creating "normal" > windows such as the one created via tkMessageBox.showinfo is asking for > problems. What are you trying to do here? I just need a window without the titlebar as my main window (think of it as a kiosk application). No titlebar is mandatory :-( I place controls on it and I open popup dialog windows. If there is a better way to do it, I would be happy to know it. Thanks again. Ciao. Marcio. From kw at codebykevin.com Thu Jun 14 13:31:08 2007 From: kw at codebykevin.com (Kevin Walzer) Date: Thu, 14 Jun 2007 13:31:08 -0400 Subject: OS X install confusion In-Reply-To: <1hzp0kw.4i0y5i1cqnlwoN%johnmfisher@comcast.net> References: <1hzp0kw.4i0y5i1cqnlwoN%johnmfisher@comcast.net> Message-ID: <6b03b$46717b5e$4275d90a$18801@FUSE.NET> John Fisher wrote: > Hi Groupies, > > I have an Intel Macbook running OS X 10.4. > > It came installed with Python 2.3.5. I have since installed MacPython > with version 2.4.4, cool. > > When I open a bash terminal session and type python, it brings up > version 2.3.5. If I type IDLE it brings up version 2.4.4. > > My question: what do I have to do to get it to bring up 2.4.4 with the > "python" command? > > Thanks for bringing light to my ignorance. > > JF Sounds like a path problem. Apple's system Python is installed in /usr/bin. Your installation is probably in /usr/local/bin. Edit your profile or use the full path. -- Kevin Walzer Code by Kevin http://www.codebykevin.com From deets at nospam.web.de Wed Jun 20 08:57:10 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 20 Jun 2007 14:57:10 +0200 Subject: DFW Pythoneers Meeting THIS Saturday References: <1182325553.232470.205970@q75g2000hsh.googlegroups.com> <1182337167.504241.131530@m36g2000hse.googlegroups.com> Message-ID: <5dsmh6F35u7ubU1@mid.uni-berlin.de> Joe Riopel wrote: >> Precisely what? You complained that the OP didn't provide the location >> of the event, which he did. > > Well, where is DFW? Google, first hit: The Dallas Ft. Worth Pythoneers They even have their own website. So - what's the fuss about? The BayPIGgies also announce their meetings here. I don't mind, even though Berlin is about 10-12 hours away on a jet-plane. diez From garrickp at gmail.com Fri Jun 22 17:16:19 2007 From: garrickp at gmail.com (Falcolas) Date: Fri, 22 Jun 2007 14:16:19 -0700 Subject: The Modernization of Emacs: terminology buffer and keybinding In-Reply-To: <871wg3k8c8.fsf@thalassa.lan.informatimago.com> References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182272495.990807.99110@a26g2000pre.googlegroups.com> <87tzt3ihev.fsf@kobe.laptop> <1182370216.961241.6960@n60g2000hse.googlegroups.com> <85zm2ufjpb.fsf@lola.goethe.zz> <1182372592.803332.288260@u2g2000hsc.googlegroups.com> <1182373919.262388.100740@c77g2000hse.googlegroups.com> <85r6o6fhkb.fsf@lola.goethe.zz> <1182375045.626510.188170@m36g2000hse.googlegroups.com> <1182546050.465987.115740@q19g2000prn.googlegroups.com> <871wg3k8c8.fsf@thalassa.lan.informatimago.com> Message-ID: <1182546979.295368.146110@q19g2000prn.googlegroups.com> On Jun 22, 3:06 pm, Pascal Bourguignon wrote: > How do you call a Mac user interface that let a user work during 3 > hours to do a simple modification to a MS-Word file that takes 15 > seconds to do with emacs or a simple unix script? Would you mind elaborating on *what* took 3 hours to do, as opposed to just throwing around unquantified numbers? Would you also mind explaining the user's familiarity with the tools they were using on the mac? It's just as easy for me to say that it took me 30 minutes to simply exit emacs, and use that to justify that emacs, and by extension Linux, is a terrible tool. From mal at egenix.com Mon Jun 25 12:07:02 2007 From: mal at egenix.com (M.-A. Lemburg) Date: Mon, 25 Jun 2007 18:07:02 +0200 Subject: Talks & presentations online Message-ID: <467FE826.9070400@egenix.com> Hello, just wanted to let you know that we've put up a few of our conference talks and presentations on the web-site: http://www.egenix.com/library/presentations/ At EuroPython this year, we'll be giving talks on relational databases with Zope and show how mxTextTools can be put to good use for parsing languages. Regards, -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Jun 25 2007) >>> Python/Zope Consulting and Support ... http://www.egenix.com/ >>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ >>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ ________________________________________________________________________ 2007-07-09: EuroPython 2007, Vilnius, Lithuania 13 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 kyosohma at gmail.com Wed Jun 20 10:08:26 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Wed, 20 Jun 2007 07:08:26 -0700 Subject: wxPython - embed separate script in panel? In-Reply-To: <1182299337.772470.229160@w5g2000hsg.googlegroups.com> References: <1182299337.772470.229160@w5g2000hsg.googlegroups.com> Message-ID: <1182348506.720218.165300@w5g2000hsg.googlegroups.com> On Jun 19, 7:28 pm, mark.martin... at gmail.com wrote: > This is a wxPython question.. the wxPython group is pretty much > inactive. > > I have an MDI parent frame and child frame set up. In the child frame, > I want to use part of the frame to display the output from a .py that > is mainly matplotlib (a graph) in a section of the frame. How can I > get it to automatically run that script and place the resultant graph > in a panel? > > Thanks I'm not sure what you're talking about. I get a digest email from the wxPython user's group at least twice a day. Try going here and posting to it: http://www.wxpython.org/maillist.php Are you signed up to the dev group or something? Mike From johnjsal at NOSPAMgmail.com Wed Jun 20 16:24:27 2007 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Wed, 20 Jun 2007 16:24:27 -0400 Subject: need help with re module In-Reply-To: References: <46795CBA.9040807@gmail.com> Message-ID: <46798620$0$30507$c3e8da3@news.astraweb.com> Gabriel Genellina wrote: > py> from BeautifulSoup import BeautifulSoup > py> chaine = """helloworldok""" > py> soup = BeautifulSoup(chaine) > py> soup.findAll(text=True) > [u'hello', u'world', u'ok'] Wow. That *is* beautiful. :) From fsckedagain at gmail.com Tue Jun 12 17:45:31 2007 From: fsckedagain at gmail.com (fscked) Date: Tue, 12 Jun 2007 14:45:31 -0700 Subject: set IP in linux with python In-Reply-To: <1181679795.639380.163380@z28g2000prd.googlegroups.com> References: <1181679795.639380.163380@z28g2000prd.googlegroups.com> Message-ID: <1181684731.687900.91680@i38g2000prf.googlegroups.com> On Jun 12, 1:23 pm, fscked wrote: > I have a text file with some network info like IP, mask, gateway, etc, > that I want to set on a linux box. This script will run on the host > that will be getting the new info. I can parse the data in the text > file and get my data in a list, but I can't figure out how to put it > in the right place of the config file. Any ideas? Nevermind. I ended up recreating thte files required rather than appending them. From NunezD at gmail.com Fri Jun 22 02:16:59 2007 From: NunezD at gmail.com (hiro) Date: Fri, 22 Jun 2007 06:16:59 -0000 Subject: comparing two lists and returning "position" In-Reply-To: <467b624e$0$16271$c30e37c6@lon-reader.news.telstra.net> References: <1182481876.028589.71710@x35g2000prf.googlegroups.com> <7xvedg4n2d.fsf@ruckus.brouhaha.com> <467b624e$0$16271$c30e37c6@lon-reader.news.telstra.net> Message-ID: <1182493019.795629.108860@w5g2000hsg.googlegroups.com> On Jun 22, 1:46 am, Charles Sanders wrote: > Paul Rubin wrote: > > > from itertools import izip > > pos = map(dict(izip(l2, count())).__getitem__, l1) > > or probably less efficiently ... > > >>> l1 = [ 'abc', 'ghi', 'mno' ] > >>> l2 = [ 'abc', 'def', 'ghi', 'jkl', 'mno', 'pqr'] > >>> pos = [ l2.index(i) for i in l1 ] > >>> print pos > [0, 2, 4] > > Charles Hey Guys thanks for the feedback and the suggestions. Charles I got your implementation to work so many thanks for this. this is what I had so far for spam in l1: for eggs in l2: if spam == eggs: print "kaka", spam, eggs so its almost working just need the index, I'll continue playing with the nested loop approach for a bit more. Thanks once again guys From sureshkk at gmail.com Tue Jun 5 06:21:39 2007 From: sureshkk at gmail.com (Suresh Kumar) Date: Tue, 5 Jun 2007 15:51:39 +0530 Subject: Memory Leak in Python 2.5.1? Message-ID: <999a7d7b0706050321x1441a1f6ve8444f9ead8974bd@mail.gmail.com> Hi, I am currently investigating what seems to be a memory leak in python. (version 2.5.1). I have made python work with a custom memory sub-allocator (pool). The idea is to preallocate a pool of memory during initialization of my application and ensure that Python doesn't make any system mallocs (similar to max heap setting in java VM). With this arrangement, python seems to run out of preallocated memory after few iterations of the following code: int main(int argc, char *argv[]){ int i; mem_init(3000000);//Initialize the memory pool with 3M for (i=0;i<2000,i++){ Py_Initialize(); Sleep(1000); Py_Finalize(); } } The above code runs out of memory after 1000 + iterations. To me this looks like a memory leak, Does anyone out there have any idea whats happening here? Regards, Suresh -- "Everything of value that people get from religion can be had more honestly, without presuming anything on insufficient evidence. The rest is self-deception, set to music." -------------- next part -------------- An HTML attachment was scrubbed... URL: From DustanGroups at gmail.com Thu Jun 7 13:07:48 2007 From: DustanGroups at gmail.com (Dustan) Date: Thu, 07 Jun 2007 17:07:48 -0000 Subject: running a random function In-Reply-To: <1654405.LVbK4P6cM3@teancum> References: <1654405.LVbK4P6cM3@teancum> Message-ID: <1181236068.322974.205150@p77g2000hsh.googlegroups.com> On Jun 7, 10:56 am, David Bear wrote: > I would like to write some code that would randomly select a function from a > list of functions and call it. I was looking in the globals names space and > randomly selecting items that were of type function.. Careful!!! You don't want to destroy your computer by accident. > but I didn't see a > way of actually running the function. What do you mean? foo is a function; here's how you run it: foo() > Any pointers? Given a list of functions, it would simply be, given the list of functions bar (untested): import random random.choice(bar)() From devicerandom at gmail.com Thu Jun 28 12:41:44 2007 From: devicerandom at gmail.com (massimo s.) Date: Thu, 28 Jun 2007 09:41:44 -0700 Subject: problem with hack using multiple inheritance for plugins In-Reply-To: References: <1183026288.857294.91620@q69g2000hsb.googlegroups.com> <1183028051.940679.145680@q69g2000hsb.googlegroups.com> <46839f4c$0$22380$426a74cc@news.free.fr> <1183034478.587345.214570@w5g2000hsg.googlegroups.com> <1183036068.348031.240690@n60g2000hse.googlegroups.com> Message-ID: <1183048904.186219.253320@q69g2000hsb.googlegroups.com> On 28 Giu, 15:37, Peter Otten <__pete... at web.de> wrote: > Post a self-contained example. Now I'm even more confused. The self-contained example is below... and it works, using only old-style declarations. #!/usr/bin/env python import wx import cmd global CLI_PLUGINS global GUI_PLUGINS class MyCmd(cmd.Cmd): def do_hello(self,args): print 'hello' class PlugCmd: def _plug_init(self): print 'init plugcmd' def do_wow(self,args): print 'wow' #---------------------- class MyFrame(wx.Frame): def __init__(self,parent,id,title): ID_FRAME=-1 wx.Frame.__init__(self,parent,ID_FRAME,title,size=(800,600),style=wx.DEFAULT_FRAME_STYLE| wx.NO_FULL_REPAINT_ON_RESIZE) print dir(self) for item in GUI_PLUGINS: item._plug_init(self) class PlugFrame: def _plug_init(self): print 'init plugframe' CLI_PLUGINS=[PlugCmd] GUI_PLUGINS=[PlugFrame] def main(): app=wx.PySimpleApp() def make_cli_class(*bases): #return type(MainWindow)("MainWindowPlugged", bases + (MainWindow,), {}) return type(MyCmd)("CliPlugged", bases + (MyCmd,), {}) def make_gui_class(*bases): #return type(MainWindow)("MainWindowPlugged", bases + (MainWindow,), {}) return type(MyFrame)("MainWindowPlugged", bases + (MyFrame,), {}) my_cli=make_cli_class(*CLI_PLUGINS)() main_frame = make_gui_class(*GUI_PLUGINS)(None, -1, ('Test')) main_frame.Show() #run one loop or the other when testing #app.MainLoop() my_cli.cmdloop() main() From jeremy at omba.demon.co.uk Fri Jun 8 14:26:50 2007 From: jeremy at omba.demon.co.uk (Jeremy C B Nicoll) Date: Fri, 8 Jun 2007 19:26:50 +0100 Subject: Working with fixed format text db's References: Message-ID: Neil Cerutti wrote: > Luckily, the output format has not changed yet, so issues with > maintaining the above haven't arisen. The problem surely is that when you want to change the format you have to do so in all files (and what about the backups then?) and all programs simultaneously. Maintaining the code is the least of your the problems, I'd say. You could change the data layout so that eg each field was terminated by a marker character, then read/write delimited values. But unless you also review all the other parts of your programs, you need to be sure that you don't have any other code anywhere that implicitly relies on a particular field being a known fixed length. > > However, I'd like something better. What precisely do you want to achieve? -- Jeremy C B Nicoll - my opinions are my own. From claird at lairds.us Tue Jun 5 23:34:10 2007 From: claird at lairds.us (Cameron Laird) Date: Wed, 6 Jun 2007 03:34:10 +0000 Subject: which "GUI module" you suggest me to use? References: <1181082196.630888.161620@w5g2000hsg.googlegroups.com> Message-ID: In article <1181082196.630888.161620 at w5g2000hsg.googlegroups.com>, wrote: > >ZioMiP je napisao/la: >> Hi to all... >> >> I'm actually using Tkinter for my GUI... but I need to "put a piece of a >> web-page in a widget" how can I do? >> >> which GUI module do you suggest me to use for do that? >> >> or which GUI module do you suggest me to use at all? >> >> I'm acutally using Windows Xp but I also use Linux... >> >> I know that WxPython work only under Windows and PyGTK work only under >> Linux... there's some other modules? > >have you considered using qt, i.e., pyqt, pyqwt? unlike wx, qt draws >its own icons... > This completely loses me; what do you mean by "draw its own icon", and what does that have to do with rendering Web pages? From sjdevnull at yahoo.com Thu Jun 14 00:39:29 2007 From: sjdevnull at yahoo.com (sjdevnull at yahoo.com) Date: Wed, 13 Jun 2007 21:39:29 -0700 Subject: Method much slower than function? In-Reply-To: References: <1181781612.939800.238890@q19g2000prn.googlegroups.com> Message-ID: <1181795969.141307.94140@i13g2000prf.googlegroups.com> Gabriel Genellina wrote: > In the function above, s is a local variable, and accessing local > variables is very efficient (using an array of local variables, the > compiler assigns statically an index for each one). > Using self.s, on the other hand, requires a name lookup for each access. > The most obvious change would be to use a local variable s, and assign > self.s = s only at the end. This should make both methods almost identical > in performance. Yeah, that's a big deal and makes a significant difference on my machine. > In addition, += is rather inefficient for strings; the usual idiom is > using ''.join(items) Ehh. Python 2.5 (and probably some earlier versions) optimize += on strings pretty well. a="" for i in xrange(100000): a+="a" and: a=[] for i in xrange(100000): a.append("a") a="".join(a) take virtually the same amount of time on my machine (2.5), and the non-join version is clearer, IMO. I'd still use join in case I wind up running under an older Python, but it's probably not a big issue here. > And since you have Python 2.5, you can use the file as its own iterator; > combining all this: > > return ''.join(line.strip() for line in filehandle if '>' not in line) That's probably pretty good. From claird at lairds.us Sun Jun 3 16:41:43 2007 From: claird at lairds.us (Cameron Laird) Date: Sun, 3 Jun 2007 20:41:43 +0000 Subject: subexpressions (OT: math) References: <4662675b$1_5@news.bluewin.ch> Message-ID: <7llbj4-i9c.ln1@lairds.us> In article <4662675b$1_5 at news.bluewin.ch>, Leonhard Vogt wrote: >>> Yes, I understand that, but what is the geometrical >>> meaning of the square root of an arc length? >> >> That's a different question to your original question, which was asking >> about the square root of an angle. >> >>> And what would the units be? >> >> Angles are a ratio of two lengths, and are therefore dimensionless units. >> So the square root of an angle is just another angle, in the same units, >> and it requires no special geometric interpretation: the square root of 25 >> degrees (just an angle) is 5 degrees (just another angle). > >But sqrt(25?) = sqrt(25/180*pi) = 5*sqrt(180/pi) != 5? > >Leonhard Yes it is; that is, if you're willing to countenance the square root of an angle at all, then there should be no problem swallowing sqrt(pi radians / 180) = 1 sqrt(degree) so that sqrt(25 degrees) = sqrt(25) * sqrt(pi radians / 180) = 5 * sqrt(degree) If it helps, we can call zilth := sqrt(pi radians / 180) Measured in square-roots of a degree, a zilth is numerically 1. From deets at nospam.web.de Fri Jun 1 06:27:17 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 01 Jun 2007 12:27:17 +0200 Subject: execute a function after each source code line ? References: <3b4f5$465fe3fc$83aef404$23254@news1.tudelft.nl> Message-ID: <5caak5F2un8tqU1@mid.uni-berlin.de> stef wrote: > hello, > > doing a simulation of another language (JAL), > I translate the other language into Python code, > then I execute this converted Python code. > > Now I need todo some checks and give visual feedback to the user, > each time a line of code is executed. > > One way of realizing this, is to add a function call at each source code > line under investigation. > > Are there any other (simple) ways of achieving this ? > (btw the whole program is running as an graphical (wxPython) application) use the python trace facilities. http://docs.python.org/lib/module-trace.html Diez From jstroud at mbi.ucla.edu Fri Jun 8 18:51:13 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Fri, 08 Jun 2007 15:51:13 -0700 Subject: Tkinter custom drawing In-Reply-To: <1181311587.317955.28650@q69g2000hsb.googlegroups.com> References: <1181224696.484887.29980@q66g2000hsg.googlegroups.com> <18ffa$4668282d$4275d90a$7087@FUSE.NET> <1181311587.317955.28650@q69g2000hsb.googlegroups.com> Message-ID: Xavier B?rard wrote: >>>Now, the problem, is that I have already plenty of widgets on my >>>screen. I just want to draw over them, which is a bit difficult in my >>>comprehension of things. >> >>What are you trying to achieve by "drawing over" widgets? > > > > Want I want to do is a sort of GUI builder for Tkinter. I already > finished a rough version, but for now I'm making a lighter version of > this project. So, my intent, is to create a widget under the widget. > While dragging the mouse, I want to see this rectangle that defines > the boundaries of the new widget I'm creating. > > Sorry for being unclear. > You may want to look into the place() method. The python mega widgets (PMW) has a PanedWidget that implements this smoothly. You may want to emulate that approach: #! /usr/bin/env python from Tkinter import * def button_pressed(e): moved = e.widget moved.move_pending = True moved['cursor'] = 'hand1' moved.press_x = e.x moved.press_y = e.y def button_moved(e): moved = e.widget if moved.move_pending: moved.after_idle(lambda e=e: _button_moved(e)) moved.move_pending = False def _button_moved(e): moved = e.widget delta_x = e.x - moved.press_x delta_y = e.y - moved.press_y size, wx, wy = moved.winfo_geometry().split('+') new_x = int(wx) + delta_x new_y = int(wy) + delta_y moved.place(x=new_x, y=new_y) moved.update_idletasks() moved.move_pending = True def button_up(e): e.widget['cursor'] = '' def register(widget): widget.bind('', button_pressed) widget.bind('', button_moved) widget.bind('', button_up) widget.update_idletasks() def test(): tk = Tk() b = Button(tk, text='Button') b.pack() c = Button(tk, text='Another Button') c.pack() x = Label(tk, text='Drag Me', relief=RIDGE, border=1) register(x) x.pack() tk.geometry('200x200') tk.mainloop() if __name__ == "__main__": test() James From rampeters at gmail.com Fri Jun 22 18:53:54 2007 From: rampeters at gmail.com (johnny) Date: Fri, 22 Jun 2007 15:53:54 -0700 Subject: newb: Scope Question Message-ID: <1182552834.987916.293260@a26g2000pre.googlegroups.com> Scope of ids: When I print "ids", it's always empty string '', as I have intialized before. That's not what I want. I want the ids to have str(r['id']).join(',') if res: ids = '' for r in res['key']: ids = str(r['id']).join(',') print("ids: %s" %(ids)) From steve at holdenweb.com Fri Jun 29 12:22:04 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 29 Jun 2007 12:22:04 -0400 Subject: Python's "only one way to do it" philosophy isn't good? In-Reply-To: References: <7xejjzmk7u.fsf@ruckus.brouhaha.com> <7xy7i7xjl5.fsf@ruckus.brouhaha.com> <1183098228.517915.12140@q75g2000hsh.googlegroups.com> Message-ID: Douglas Alan wrote: > Michele Simionato writes: > >>> I've written plenty of Python code that relied on destructors to >>> deallocate resources, and the code always worked. > >> You have been lucky: > > No I haven't been lucky -- I just know what I'm doing. > >> $ cat deallocating.py >> import logging >> >> class C(object): >> def __init__(self): >> logging.warn('Allocating resource ...') >> >> def __del__(self): >> logging.warn('De-allocating resource ...') >> print 'THIS IS NEVER REACHED!' >> >> if __name__ == '__main__': >> c = C() >> >> $ python deallocating.py >> WARNING:root:Allocating resource ... >> Exception exceptions.AttributeError: "'NoneType' object has no >> attribute 'warn'" in > 0xb7b9436c>> ignored > > Right. So? I understand this issue completely and I code > accordingly. > >> Just because your experience has been positive, you should not >> dismiss the opinion who have clearly more experience than you on >> the subtilities of Python. > > I don't dismiss their opinion at all. All I've stated is that for my > purposes I find that the refcounting semantics of Python to be useful, > expressive, and dependable, and that I wouldn't like it one bit if > they were removed from Python. > > Those who claim that the refcounting semantics are not useful are the > ones who are dismissing my experience. (And the experience of > zillions of other Python programmers who have happily been relying on > them.) > > |>oug "Python" doesn't *have* any refcounting semantics. If you rely on the behavior of CPython's memory allocation and garbage collection you run the risk of producing programs that won't port tp Jython, or IronPython, or PyPy, or ... This is a trade-off that many users *are* willing to make. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From evan at yelp.com Mon Jun 18 14:41:11 2007 From: evan at yelp.com (Evan Klitzke) Date: Mon, 18 Jun 2007 11:41:11 -0700 Subject: Line Wrapping In-Reply-To: <4676cec6$0$1435$39db0f71@news.song.fi> References: <4676cec6$0$1435$39db0f71@news.song.fi> Message-ID: On 6/18/07, TeroV wrote: > Evan Klitzke wrote: > > All, > > > > Mail messages should be wrapped at 78 characters (as suggested in RFC > > 2822). I want my python batch scripts/cron jobs to enforce this > > behavior, and format the mail that is sent out so that newline > > characters are inserted as appropriate to keep line lengths at 78 > > characters or less. I wrote a function to take a string and format it > > in this manner, but it seemed a bit awkward and un-Python like (my > > background is mostly C, and the function looks very much like C code). > > I'd imagine that there's probably a short, succinct, more elegant > > solution using regular expressions or some module that is unknown to > > me. Does anyone have any clean, short solutions to this problem? > > > > Does textwrap module has what you need? > > >>> import textwrap > >>> > textwrap.wrap('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', > 78) > ['aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', > 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'] > >>> textwrap.wrap('This is a very long String. A linewrap module has > couple functions which might help you to accoplish your goal. HTH', 78) > ['This is a very long String. A linewrap module has couple functions > which might', 'help you to accoplish your goal. HTH'] This sounds like exactly what I was looking for -- thanks! -- Evan Klitzke From gregpinero at gmail.com Mon Jun 25 23:19:30 2007 From: gregpinero at gmail.com (gregpinero at gmail.com) Date: Tue, 26 Jun 2007 03:19:30 -0000 Subject: Chroot Jail Not Secure for Sandboxing Python? In-Reply-To: <5ealtkF37mjlvU2@mid.individual.net> References: <1182748892.916068.146780@p77g2000hsh.googlegroups.com> <467f55f7$0$20850$9b622d9e@news.freenet.de> <1182782910.811850.284350@u2g2000hsc.googlegroups.com> <5ealtkF37mjlvU2@mid.individual.net> Message-ID: <1182827970.263367.306790@w5g2000hsg.googlegroups.com> On Jun 25, 4:12 pm, Bjoern Schliessmann wrote: > gregpin... at gmail.com wrote: > > I followed up with my ISP. Here's the answer I got: > > > The os.exec call prepends the chroot directory to the absolute > > path, but does NOT provide chroot for the child process. > > That sounds like rubbish to me. If it worked like that, chrooting > servers would be virtually useless. You're right. It turns out he was referring to fakechroot. Chroot shouldn't have this problem. -Greg From showell30 at yahoo.com Fri Jun 1 12:59:11 2007 From: showell30 at yahoo.com (Steve Howell) Date: Fri, 1 Jun 2007 09:59:11 -0700 (PDT) Subject: subexpressions In-Reply-To: <5cajqnF2viccfU1@mid.uni-berlin.de> Message-ID: <885681.70845.qm@web33513.mail.mud.yahoo.com> --- "Diez B. Roggisch" wrote: > The elegance of that solution very much depends on > the cost of the duplicate > operation vs. the additional function call. > > And for the usecase at hand, that's exactly the > point not to do it: > > droggisch at ganesha:/tmp$ python -m timeit '(lambda x: > lambda y: y+y)(10 * > 10)' > 1000000 loops, best of 3: 1.04 usec per loop > droggisch at ganesha:/tmp$ python -m timeit 'lambda: 10 > * 10 + 10 * 10' > 1000000 loops, best of 3: 0.336 usec per loop > Good point. I also realized as I was slowly waking up later in the morning that the trigonometry didn't make a whole lot of sense either. ____________________________________________________________________________________ Take the Internet to Go: Yahoo!Go puts the Internet in your pocket: mail, news, photos & more. http://mobile.yahoo.com/go?refer=1GNXIC From solisgb at gmail.com Thu Jun 7 11:24:16 2007 From: solisgb at gmail.com (luis) Date: Thu, 07 Jun 2007 08:24:16 -0700 Subject: ctypes: error passing a list of str to a fortran dll In-Reply-To: <4664e37f$0$59818$c30e37c6@lon-reader.news.telstra.net> References: <1180952246.415068.237400@h2g2000hsg.googlegroups.com> <4664e37f$0$59818$c30e37c6@lon-reader.news.telstra.net> Message-ID: <1181229856.662912.309990@p47g2000hsd.googlegroups.com> On 5 jun, 06:15, Charles Sanders wrote: > luis wrote: > > I'm using ctypes to call afortrandllfrom python. I have no problems > > passing integer and double arryas, but I have an error with str arrys. > > For example: > > [snip] > > I do not know about MicrosoftFortrancompilers (your mention > ofdllindicates you are probably using MS), nor much about > Python, but the C equivalent of a givenFortrancall is operating > system and compiler dependent. You should consult theFortran > compiler manual for the compiler used to create theDLL. > > Despite this, many (but not all) C toFortraninterfaces have > the following characteristics > > + C name isFortranname in lower case > +FortranREAL, DOUBLE PRECISION, INTEGER etc parameters > are pointers to the parameter in C, ie float*, etc > +FortranREAL etc arrays are pointers in C (same as > C arrays decay to pointers). > +FortranCHARACTER and CHARACTER arrays are passed as TWO > parameters, one a pointer to the start of the variable > or array, and the other the length as an integer, not > a pointer. The length parameters follow all other > parameters, in order of the character variables/arrays. > > Variations I have seen (all on Unix) include using upper case > instead of lower, prepending (or postpending) an underscore (or > other character(s)) to the subroutine or function name, and > using special "character descriptors" (packing address and > length into one "word") for character variables. There are > almost certainly more variations that I have not seen. > > For example, given aFORTRANdeclaration > > SUBROUTINE X( CV, RV, CA, N ) > CHARACTER*(*) CV > REAL RV > CHARACTER*(*) CA(*) > INTEGER N > > The C equivalent is likely to be > > void x( char *pcv, float *prv, char *pca, int *pn, > int lv, int la) > > Where lv will hold the length of cv and la the length of > each element of ca (required to be the same for all elements > of the array).Fortranuses fixed length character strings, > padded with blanks. > > Given the error message > > > ValueError: Procedure probably called with not enough > > arguments (4 bytes missing) > > I suspect that yourFortrancompiler is one of the many which > do this, and the missing 4 bytes are the integer length of > each element of the character array. > > Also, I noticed you seem to be passing an array of character > pointers rather than an array of characters. It is doubtful thatFortrancan handle this. You will probably have to pad the strings > to a maximal length with spaces, concatanate then into one big > string, and pass this by reference together with their padded > length. YourFortranmay (but probably won't) have extensions > that allow you to pass an array of character pointers. > > Charles The solution proposed by Jugoslav Dujic, from comp lang fortran is #Python script calling fortran subroutine from ctypes import * ap = windll.LoadLibrary(self.locationDll) ap.TEST_02.restype=None myCadena='D:\BBDD\PythonScripts\pru.txt' strLen=len(myCadena) pf_myCadena = c_char_p(myCadena) pf_srLen = c_int(strLen) ap.TEST_02(pf_myCadena,pf_srLen) !fortran dll subroutine TEST_02(s) !DEC$ ATTRIBUTES DLLEXPORT :: TEST_02 !DEC$ATTRIBUTES REFERENCE:: s !INTEGER(4):: n CHARACTER(*):: s open (unit=31,file=trim(s)) write(31,'(f0.1)') 1.0 write(31,*) trim(s) write(31,'(i0)') len_trim(s) close(31) return END subroutine Regards From nospam at no.spam Fri Jun 1 07:34:13 2007 From: nospam at no.spam (=?ISO-8859-1?Q?Markus_Sch=F6pflin?=) Date: Fri, 01 Jun 2007 13:34:13 +0200 Subject: cStringIO change in 2.4 vs 2.5. Regression? Message-ID: Hello, I just stumbled accross a difference between cStringIO in Python 2.4 and 2.5. You can no longer feed arrays to cStringIO. Python 2.4: ---%<--- ActivePython 2.4.3 Build 12 (ActiveState Software Inc.) based on Python 2.4.3 (#69, Apr 11 2006, 15:32:42) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> from array import array >>> a = array('B', (0, 1, 2)) >>> a array('B', [0, 1, 2]) >>> from StringIO import StringIO >>> StringIO(a) >>> from cStringIO import StringIO >>> StringIO(a) --->%--- Python 2.5: ---%<--- Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> from array import array >>> a = array('B', (0, 1, 2)) >>> a array('B', [0, 1, 2]) >>> from StringIO import StringIO >>> StringIO(a) >>> from cStringIO import StringIO >>> StringIO(a) Traceback (most recent call last): File "", line 1, in TypeError: expected a character buffer object --->%--- Has this change been done on purpose or is it a regression? If it's not a regression, is there another way to feed an array to cStringIO without expensive conversion? TIA, Markus From nagle at animats.com Sat Jun 23 19:41:48 2007 From: nagle at animats.com (John Nagle) Date: Sat, 23 Jun 2007 23:41:48 GMT Subject: urllib interpretation of URL with ".." In-Reply-To: <467cc85f$0$3039$9b622d9e@news.freenet.de> References: <467cc85f$0$3039$9b622d9e@news.freenet.de> Message-ID: <0difi.26794$YL5.11681@newssvr29.news.prodigy.net> Martin v. L?wis wrote: > John Nagle schrieb: > >>Here's a URL, found in a link, which gives us trouble >>when we try to follow the link: >> >> http://sportsbra.co.uk/../acatalog/shop.html >> >>Browsers immediately turn this into >> >> http://sportsbra.co.uk/acatalog/shop.html >> >>and go from there, but urllib tries to open it explicitly, which >>results in an HTTP error 400. >> >>Is "urllib" wrong? > > > I can't see how. HTTP 1.1 says that the parameter to the GET > request should be an abs_path; RFC 2396 says that > /../acatalog/shop.html is indeed an abs_path, as .. is a valid > segment. That RFC also has a section on relative identifiers > and normalization; it defines what .. means *in a relative path*. > > Section 4 is explicit about .. in absolute URIs: > # The syntax for relative URI is a shortened form of that for absolute > # URI, where some prefix of the URI is missing and certain path > # components ("." and "..") have a special meaning when, and only when, > # interpreting a relative path. > > Notice the "and only when": the browsers who modify above > URL before sending it seem to be in clear violation of > RFC 2396. > > Regards, > Martin I think you're right. The problem is that there is apparently a de-facto standard in browsers that any number of "../" sequences at the beginning of the path part of a URL have no effect. Even Google seems to use that interpretation; not only does it follow that link, it lists it in Google without the "..". John Nagle From joe at incomps.com Tue Jun 5 15:15:22 2007 From: joe at incomps.com (Joe) Date: Tue, 5 Jun 2007 13:15:22 -0600 Subject: MySQL InterfaceError In-Reply-To: <002901c7a6f4$f55e56a0$0f01a8c0@desktop9> References: <001e01c7a6f3$e687ed40$0f01a8c0@desktop9> <002901c7a6f4$f55e56a0$0f01a8c0@desktop9> Message-ID: <008e01c7a7a5$ddaf8ae0$0f01a8c0@desktop9> >File "build/bdist.linux-i686/egg/MySQLdb/cursors.py", line 147, in execute > charset = db.character_set_name() > >InterfaceError: (0, '') We got it working. It was caused by passing a database connection to a module: import MySQLdb import module_name connection = MySQLdb.connect(host='localhost', user='user', passwd='password', db='database') module = module_name.ClassName(connection) But, when the connection was made within the module itself, it would work flawlessly every time. Can someone explain to me why this is? Jough -------------- next part -------------- An HTML attachment was scrubbed... URL: From tdelaney at avaya.com Thu Jun 7 19:17:13 2007 From: tdelaney at avaya.com (Delaney, Timothy (Tim)) Date: Fri, 8 Jun 2007 07:17:13 +0800 Subject: Python 2.5.1 - sqlite3.dll issue In-Reply-To: Message-ID: Delaney, Timothy (Tim) wrote: > Josh Ritter wrote: > >> A number of our Windows customers have an issue with the sqlite3 >> module included with Python 2.5.1 >> >> We've tracked the problem down to the sqlite3.dll included with the >> Python >> 2.5.1 distrubtion. It is stripped and thus cannot be relocated. >> This causes the following exception on computers where something is >> already loaded into the address the sqlite3.dll wants to use: >> >> File "sqlite3\__init__.pyc", line 24, in >> File "sqlite3\dbapi2.pyc", line 27, in >> ImportError: DLL load failed: Invalid access to memory location. >> >> I downloaded the latest sqlite3.dll from http://www.sqlite.org and >> this fixes the problem. (This dll isn't stripped) > > Could you raise a bug report on SourceForge please? > http://sourceforge.net/tracker/?group_id=5470&atid=105470&func=add OK - I've raised bug report 1733134 for this. I would strongly encourage people though to get their own SourceForge account so they can participate in the Python development process. Cheers, Tim Delaney From mitko at qlogic.com Wed Jun 6 14:45:07 2007 From: mitko at qlogic.com (Mitko Haralanov) Date: Wed, 6 Jun 2007 11:45:07 -0700 Subject: Invalid argument with fcntl.fcntl Message-ID: <20070606114507.67c1f85b@opal.pathscale.com> I am trying to use the advisory locking with fcntl over NFS (thus, me choosing fcntl instead of flock and friends). I have the following code: lockdata = struct.pack ("hhllhh", fcntl.F_RDLCK, 0, 0, 0, 0, 0) print self.fd, type (self.fd), len (lockdata), type (lockdata) ret = fcntl.fcntl (self.fd, fcntl.F_GETLK, lockdata) when this code executes, I always get the following: 16 Traceback (most recent call last): File "", line 1, in ? File "filelock.py", line 154, in _get_lock_state_nfs ret = fcntl.fcntl (self.fd, fcntl.F_GETLK, lockdata) IOError: [Errno 22] Invalid argument If I execute the same code in the Python interpreter (replacing self.fd with an open file object), it work. Can anyone shed some light on why this code would produce that error? Thanks -- Mitko Haralanov mitko at qlogic.com Senior Software Engineer 650.934.8064 System Interconnect Group http://www.qlogic.com ========================================== FORTRAN is a good example of a language which is easier to parse using ad hoc techniques. -- D. Gries [What's good about it? Ed.] From josiah.carlson at sbcglobal.net Sat Jun 9 19:07:26 2007 From: josiah.carlson at sbcglobal.net (Josiah Carlson) Date: Sat, 09 Jun 2007 23:07:26 GMT Subject: Multiple python interpreters within the same process In-Reply-To: <1181419389.412390.322680@n4g2000hsb.googlegroups.com> References: <1181419389.412390.322680@n4g2000hsb.googlegroups.com> Message-ID: Andr? wrote: > On Jun 9, 5:00 pm, "Marcin Kalicinski" wrote: >> How do I use multiple Python interpreters within the same process? >> >> I know there's a function Py_NewInterpreter. However, how do I use functions >> like Py_RunString etc. with it? They don't take any arguments that would >> tell on which interpreter to run the string...? >> >> Marcin > > You may want to look at the code module http://docs.python.org/lib/module-code.html That's completely unrelated. To answer Marcin's question, from what I understand, running multiple Python interpreters is not supported. There are various issues with object sharing and refcounts, etc., and are unlikely to be fixed soon if ever. - Josiah From oscartheduck at gmail.com Fri Jun 22 17:10:37 2007 From: oscartheduck at gmail.com (oscartheduck) Date: Fri, 22 Jun 2007 21:10:37 -0000 Subject: regular expression concatenation with strings In-Reply-To: References: <1182543519.337279.25800@z28g2000prd.googlegroups.com> Message-ID: <1182546637.032673.106920@a26g2000pre.googlegroups.com> Hi, I noticed a small error in the code (you referenced extension, which you had renamed to filenameRx), and when I corrected it I received the original error again. What was it you were trying to do to solve the problem, though? Thanks! On Jun 22, 2:41 pm, Jacek Trzmiel wrote: > Hi, > > oscartheduck wrote: > > I have a little script that sits in a directory of images and, when > > ran, creates thumbnails of the images. It works fine if I call the > > function inside the program with something like "thumbnailer("jpg), > > but I want to use a regular expression instead of a plain string so > > that I can match jpeg, jpg, JPEG etc. > > Something like this will work: > > #!/usr/bin/env python > #from PIL import Image > import glob, os, re > > size = 128, 128 > > def thumbnailer(dir, filenameRx): > for picture in [ p for p in os.listdir(dir) if > os.path.isfile(os.path.join(dir,p)) and filenameRx.match(p) ]: > file, ext = os.path.splitext(picture) > im = Image.open (picture) > im.thumbnail(size, Image.ANTIALIAS) > im.save(file + ".thumbnail." + extension) > > jpg = re.compile(".*\.(jpg|jpeg)", re.IGNORECASE) > thumbnailer(".", jpg) > > Best regards, > Jacek. From newsgroups at debain.org Sun Jun 17 08:42:41 2007 From: newsgroups at debain.org (Samuel) Date: Sun, 17 Jun 2007 12:42:41 +0000 (UTC) Subject: Trivial string substitution/parser References: Message-ID: On Sun, 17 Jun 2007 11:00:58 +0000, Duncan Booth wrote: > The elegant and lazy way would be to change your specification so that $ > characters are escaped by $$ not by backslashes. Then you can write: > >>>> from string import Template >>>> ... Thanks, however, turns out my specification of the problem was incomplete: In addition, the variable names are not known at compilation time. I just did it that way, this looks fairly easy already: ------------------- import re def variable_sub_cb(match): prepend = match.group(1) varname = match.group(2) value = get_variable(varname) return prepend + value string_re = re.compile(r'(^|[^\\])\$([a-z][\w_]+\b)', re.I) input = r'In this string $variable1 is substituted,' input += 'while \$variable2 is not.' print string_re.sub(variable_sub_cb, input) ------------------- -Samuel From rhamph at gmail.com Fri Jun 1 14:35:38 2007 From: rhamph at gmail.com (Adam Olsen) Date: Fri, 1 Jun 2007 12:35:38 -0600 Subject: Thread-safety of dict In-Reply-To: <465FD122.9030108@v.loewis.de> References: <465FD122.9030108@v.loewis.de> Message-ID: On 6/1/07, "Martin v. L?wis" wrote: > > So there you have it: if you're using a dict with custom classes (or > > anything other than str) across multiple threads, and without locking > > it, it's possible (though presumably extremely rare) for a lookup to > > fail even through the key was there the entire time. > > That could be fixed by adding a generation counter to the dictionary, > right? Then an adversary would have to arrange for the generation > counter to roll over for lookdict to not notice that the > dictionary was modified. Yup. Although it'd still be technically possible to roll over the counter, it's much easier to say how insanely unlikely it is. Incidentally, only resizing should increment the counter; it's not necessary to restart lookups for other accesses (and would harm performance, as well as producing infinite loops in __cmp__ methods that read from their containing dict.) It occurs to me now that getting the original ma_table back could do worse than just a failed lookup: if the size is smaller than before it would lead to memory corruption and segfaults. That could be fixed with with a before/after check of ma_mask. And if you're *really* feeling paranoid you could add reference counting to ma_table. I doubt anybody cares quite that much though. ;) -- Adam Olsen, aka Rhamphoryncus From ptmcg at austin.rr.com Sun Jun 17 08:03:10 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: Sun, 17 Jun 2007 05:03:10 -0700 Subject: Newbie question: how to get started? In-Reply-To: <200706162301448930-user@superhoostcom> References: <2007061622483250073-user@superhoostcom> <200706162301448930-user@superhoostcom> Message-ID: <1182081790.790294.3090@q75g2000hsh.googlegroups.com> On Jun 16, 10:01 pm, ed wrote: > I should also mention that I know C/C++, Perl, Javascript, the basics > of mySQL, and HTML/CSS. If anyone has tried to enter python from these > angles, I'd be grateful to hear from you. > > On 2007-06-16 22:48:32 -0400, ed said: > > > > > Hi, > > > I'm interested in starting to learn python. I'm looking for any > > reccomendations or advice that I can use to get started. Looking > > forward to any help you can give! > > > Thanks! > > > -e- Hide quoted text - > > - Show quoted text - http://wiki.python.org/moin/BeginnersGuide/Programmers?action=AttachFile&do=get&target=Cpp2Python.pdf >From a previous thread addressing a C++'ers questions on how to get started with Python. -- Paul From flebber.crue at gmail.com Fri Jun 8 07:45:44 2007 From: flebber.crue at gmail.com (flebber) Date: Fri, 08 Jun 2007 11:45:44 -0000 Subject: read xml file from compressed file using gzip In-Reply-To: <4668E996.9020006@web.de> References: <1181278784.312152.99910@r19g2000prf.googlegroups.com> <4668E996.9020006@web.de> Message-ID: <1181303144.910159.326690@z28g2000prd.googlegroups.com> On Jun 8, 3:31 pm, Stefan Behnel wrote: > flebber wrote: > > I was working at creating a simple program that would read the content > > of a playlist file( in this case *.k3b") and write it out . the > > compressed "*.k3b" file has two file and the one I was trying to read > > was maindata.xml. > > Consider using lxml. It reads in gzip compressed XML files transparently and > provides loads of other nice XML goodies. > > http://codespeak.net/lxml/dev/ > > Stefan I will, baby steps at the moment for me at the moment though as I am only learning and can't get gzip to work From a.schmolck at gmail.com Sun Jun 10 20:28:09 2007 From: a.schmolck at gmail.com (Alexander Schmolck) Date: Mon, 11 Jun 2007 01:28:09 +0100 Subject: Python's "only one way to do it" philosophy isn't good? References: <1181368143.874341.273140@r19g2000prf.googlegroups.com> Message-ID: Steven D'Aprano writes: > On Sat, 09 Jun 2007 22:42:17 +0100, Alexander Schmolck wrote: > >>> As for why tail calls are not optimized out, it was decided that being able >>> to have the stack traces (with variable information, etc.) was more useful >>> than offering tail call optimization >> >> I don't buy this. > > Do you mean you don't believe the decision was made, or you don't agree > with the decision? Neither. I don't believe the rationale stated in this thread to be the true reason. > Are you volunteering? If you are, I'm sure your suggestion will be welcomed > gratefully. I rather doubt it. Guido has stated quite clearly that his not interested in incorporating this feature. >>> (do what I say). >> >> Where did you say run out of memory and fail? More importantly how do >> you say "don't run out of memory and fail"? > > If we can live with a certain amount of "arbitrary failures" in simple > arithmetic, I prefer not too, and thus when possible avoid to use languages where ``a + b`` is liable to fail arbitrarily (such as C, where the behavior will often be undefined). > then the world won't end if tail recursion isn't optimized away by the > compiler. I'd personally much rather have arithmetic working properly. Unfortunately this is not an option at the moment, although quite a few smart people are working on it and although it is an immensely costly problem. > You can always hand-optimize it yourself. Not tail calls, in general, no. 'as From kaldrenon at gmail.com Fri Jun 22 14:24:52 2007 From: kaldrenon at gmail.com (Kaldrenon) Date: Fri, 22 Jun 2007 18:24:52 -0000 Subject: I need some cleanings tips and advice. In-Reply-To: References: <1182528064.446459.49420@n2g2000hse.googlegroups.com> <467bf4c9@news.nucleus.com> Message-ID: <1182536692.354336.204600@u2g2000hsc.googlegroups.com> On Jun 22, 1:09 pm, Neil Cerutti wrote: > Maybe they lost the business plan. It's not surprising, since it > was probably written on a napkin. Or perhaps they HAD a bunch of good cleaning tips, but accidentally threw them out while cleaning? Tip: don't throw stuff out unless you don't need it any more. =P From anamax at earthlink.net Tue Jun 26 17:54:21 2007 From: anamax at earthlink.net (Andy Freeman) Date: Tue, 26 Jun 2007 14:54:21 -0700 Subject: Python's "only one way to do it" philosophy isn't good? In-Reply-To: <7xps3iy73h.fsf@ruckus.brouhaha.com> References: <1182750077.570603.160240@q69g2000hsb.googlegroups.com> <7xir9cbm0g.fsf@ruckus.brouhaha.com> <7xejjzmk7u.fsf@ruckus.brouhaha.com> <7xy7i7xjl5.fsf@ruckus.brouhaha.com> <1182872972.417776.78650@o11g2000prd.googlegroups.com> <1182873568.454491.302860@e9g2000prf.googlegroups.com> <7xps3iy73h.fsf@ruckus.brouhaha.com> Message-ID: <1182894861.819768.7550@a26g2000pre.googlegroups.com> On Jun 26, 10:10 am, Paul Rubin wrote: > Andy Freeman writes: > > Compare that with what a programmer using Python 2.4 has to do if > > she'd like the functionality provided by 2.5's with statement. Yes, > > with is "just syntax", but it's extremely useful syntax, syntax that > > can be easily implemented with lisp-style macros. > > Not really. Yes really, as the relevant PEP shows. The "it works like" pseudo- code is very close to how it would be defined with lisp-style macros. > The with statement's binding targets all have to support > the protocol, which means a lot of different libraries need redesign. That's a different problem, and it's reasonably solvable for anyone who wants to use the roll-your-own with while writing an application running under 2.4. (You just add the relevant methods to the appropriate classes.) The big obstacle is the syntax of the with-statement. There's no way to define it in python with user-code. From aleax at mac.com Wed Jun 27 11:11:07 2007 From: aleax at mac.com (Alex Martelli) Date: Wed, 27 Jun 2007 08:11:07 -0700 Subject: simplifying algebraic expressions References: <46805dae$1@news.orcon.net.nz> <4680f325@news.orcon.net.nz> <1182856943.974861.10070@q75g2000hsh.googlegroups.com> <46818b96$1@news.orcon.net.nz> Message-ID: <1i0cxcn.1o14qxi95j5fvN%aleax@mac.com> DavidM wrote: ... > Seems that I have to allow a 'punishment free' threshold of complexity, > otherwise the population stagnates. Sounds like you've hit on a good simulation of life: to get innovation, you must be very tolerant of errors!-) Alex From rossum48 at coldmail.com Sat Jun 23 18:04:01 2007 From: rossum48 at coldmail.com (rossum) Date: Sat, 23 Jun 2007 23:04:01 +0100 Subject: Portable general timestamp format, not 2038-limited References: <1182544384.709759.235300@o11g2000prd.googlegroups.com> <1182552560.194980.297550@z28g2000prd.googlegroups.com> <1182631034.645474.14430@q75g2000hsh.googlegroups.com> Message-ID: <3t5r735jm37coi326rm9r190492a6eam26@4ax.com> On Sat, 23 Jun 2007 13:37:14 -0700, James Harris wrote: >On 22 Jun, 23:49, Roger Miller wrote: >... >> My rule of thumb in situations like this is "When in doubt store it as >> text". The one format I am pretty sure we will still be able to deal >> with in 2039. > >Interesting. I hadn't thought about using text. It would add to the >storage a bit as each record is otherwise quite short. But this sounds >like a good option and may help - at least while debugging - to see >the raw date and time as digits. I will consider using this, perhaps >as yyyymmddhhmmssttt. You might prefer to use one of the ISO 8601 formats: yyyymmddThhmmssttt or yyyy-mm-ddThh:mm:ss.ttt http://www.cl.cam.ac.uk/~mgk25/iso-time.html rossum From david.golden at oceanfree.net Fri Jun 22 18:11:10 2007 From: david.golden at oceanfree.net (David Golden) Date: Fri, 22 Jun 2007 23:11:10 +0100 Subject: The Modernization of Emacs: terminology buffer and keybinding References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182272495.990807.99110@a26g2000pre.googlegroups.com> <87tzt3ihev.fsf@kobe.laptop> <1182370216.961241.6960@n60g2000hse.googlegroups.com> <85zm2ufjpb.fsf@lola.goethe.zz> <1182372592.803332.288260@u2g2000hsc.googlegroups.com> <5dtk4tF34jrimU1@mid.dfncis.de> <1182375388.814275.227380@n2g2000hse.googlegroups.com> <87645h73ei.fsf@W0053328.mgh.harvard.edu> <1182548563.561252.82480@i13g2000prf.googlegroups.com> Message-ID: <6OXei.20483$j7.377966@news.indigo.ie> Twisted wrote: > Of course not. It's too hard to get started using it, so I gave up on > it years ago. So wtf makes you think you're remotely qualified to comment about emacs as it stands today? Idiot. From jorgen.maillist at gmail.com Wed Jun 6 05:49:23 2007 From: jorgen.maillist at gmail.com (Jorgen Bodde) Date: Wed, 6 Jun 2007 11:49:23 +0200 Subject: function in a function accessing vars Message-ID: <11e49df10706060249j47b98fc8ie7f619782b046a25@mail.gmail.com> Hi all, I wanted to solve a small problem, and I have a function that is typically meant only as a function belonging inside another function. >From the inner function I want to access a variable from the outer function like; def A(): some_var = 1 def B(): some_var += 1 B() But this does not work, the function B does not recognize the some_var. In my mind I thought the scope would propagate to the new function and the vars would still be accessible. How can I go about this? With regards - Jorgen From gkkvishnu at gmail.com Mon Jun 11 14:59:19 2007 From: gkkvishnu at gmail.com (vishnu) Date: Tue, 12 Jun 2007 00:29:19 +0530 Subject: Python for embedded systems with memory constraints In-Reply-To: <1181430148.793716.110350@q69g2000hsb.googlegroups.com> References: <1181430148.793716.110350@q69g2000hsb.googlegroups.com> Message-ID: Hello, Using the best fit for Python will not be a problem, because Python makes allocations of lot of small size blocks.So those split blocks of small sizes are used by Python sometime. And what I observed from my investigation with the memory manager(MM) for Python is , with any MM we cannot eliminate fragmentation and even though Python is memory hungry I cannot allot some 50MB (or more) just for python application because it will add to the embedded system memory cost. So now I only see the solution to clear my memory pool and restart Python without restarting the system (i.e. no power cycle to hardware). I tried to do this when my memory pool is 60% used in these steps: 1) Py_Finalize( ) 2) Reset my Memory pool (i.e. free list links) 3) Then Restart Python by calling Py_Initialize(). But this resulted in Python crash during Py_Initialize(), where I found that the static variables within embedded Python source code are still holding some of the references to my memory pool. So now my question is how do I restart Python (i.e. reinitialize Python) without restarting whole system. Is there a way to reset/re-initilaize those static variables such that it will be possible to re-Initialize Python. Vishnu On 6/10/07, MRAB wrote: > On Jun 9, 1:33 pm, vishnu wrote: > > Hi, > > Thanks Cameron for your suggestions. > > In fact I am using custom memory sub-allocator where I preallocate a > > pool of memory during initialization of my application and ensure that > > Python doesn't make any system mallocs later . With this arrangement, > > python seems to run out of preallocated memory (of 10MB) after running > > few simple scripts due to huge external fragmentation. My memory > > sub-allocator got a good design which uses the best-fit algorithm and > > coaelescing the adjacent blocks during each free call. > > If anybody out there used their own memory manager and ran Python > > without fragmentation , could provide some inputs on this. > > > >From what I remember, the best-fit algorithm isn't a good idea because > unless the free block was exactly the right size you'd tend to get > left with lots of small fragments. (Suppose that the best fit was a > free block only 4 bytes bigger than what you want; what can you do > with a free block of 4 bytes?) > > A worst-fit algorithm would leave larger free blocks which are more > useful subsequently, but I think that the recommendation was next-fit > (ie use the first free block that's big enough, starting from where > you found the last one). > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From carsten at uniqsys.com Fri Jun 1 11:49:04 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Fri, 01 Jun 2007 11:49:04 -0400 Subject: What is equivalent of *this = that in python? In-Reply-To: <32e43bb70706010830t38e69cb1t732e5dbdaff6cd1b@mail.gmail.com> References: <32e43bb70706010830t38e69cb1t732e5dbdaff6cd1b@mail.gmail.com> Message-ID: <1180712944.3376.59.camel@dot.uniqsys.com> On Fri, 2007-06-01 at 11:30 -0400, Emin.shopper Martinian.shopper wrote: > Dear Experts, > > How do I reassign self to another object? For example, I want > something like > > class foo: > def Update(self,other): > # make this object the same as other or make this object a > copy of other > self = other # This won't work. What I really want is *this = > other in C++ terminology. There is no such thing in Python. What's the actual problem you're trying to solve? -- Carsten Haese http://informixdb.sourceforge.net From S.Mientki-nospam at mailbox.kun.nl Thu Jun 21 13:41:05 2007 From: S.Mientki-nospam at mailbox.kun.nl (Stef Mientki) Date: Thu, 21 Jun 2007 19:41:05 +0200 Subject: Globals in nested functions In-Reply-To: <1182424010.561262.169170@j4g2000prf.googlegroups.com> References: <1182424010.561262.169170@j4g2000prf.googlegroups.com> Message-ID: jm.suresh at no.spam.gmail.com wrote: > def f(): > a = 12 > def g(): > global a > if a < 14: > a=13 > g() > return a > > print f() > > This function raises an error. Is there any way to access the a in f() > from inside g(). > > I could find few past discussions on this subject, I could not find > the simple answer whether it is possible to do this reference. > > - > Suresh > As I'm struggling with this myself at the moment, this will do the job: def f(): global a a = 12 cheers, Stef Mientki From steve at REMOVE.THIS.cybersource.com.au Sun Jun 3 06:05:17 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sun, 03 Jun 2007 20:05:17 +1000 Subject: subexpressions (OT: math) References: <4662675b$1_5@news.bluewin.ch> Message-ID: On Sun, 03 Jun 2007 09:02:11 +0200, Leonhard Vogt wrote: >> Angles are a ratio of two lengths, and are therefore dimensionless units. >> So the square root of an angle is just another angle, in the same units, >> and it requires no special geometric interpretation: the square root of 25 >> degrees (just an angle) is 5 degrees (just another angle). > > But sqrt(25?) = sqrt(25/180*pi) = 5*sqrt(180/pi) != 5? Hmmm... perhaps that's why the author of the "units" program doesn't treat angles as dimensionless when taking square roots. Given that, I withdraw my claim that the sqrt of an angle is just an angle. I can't quite see why it shouldn't be, but the evidence is fairly solid that it isn't. -- Steven From S.Mientki-nospam at mailbox.kun.nl Sun Jun 10 18:22:21 2007 From: S.Mientki-nospam at mailbox.kun.nl (Stef Mientki) Date: Mon, 11 Jun 2007 00:22:21 +0200 Subject: Select one of 2 functions with the same name ? In-Reply-To: <1181512874.648431.194520@q75g2000hsh.googlegroups.com> References: <99c4b$466c582c$d443bb3a$28936@news.speedlinq.nl> <1181512874.648431.194520@q75g2000hsh.googlegroups.com> Message-ID: <6ef5d$466c789b$d443bb3a$10800@news.speedlinq.nl> 7stud wrote: > On Jun 10, 2:03 pm, Stef Mientki > wrote: >> thanks Francesco and "7stud", >> >> The solution with objects is too difficult, >> because I want to stay very close to the orginal language, >> > > Why would you want to duplicate poorly written code? > I didn't know that a program written without OOP's is "poorly written" ;-) The orginal language is th? best language available for that particular micro. cheers, Stef From aisaac at american.edu Fri Jun 22 20:28:00 2007 From: aisaac at american.edu (Alan Isaac) Date: Sat, 23 Jun 2007 00:28:00 GMT Subject: Python plain-text database or library that supports joins? In-Reply-To: <1182532691.182581.110940@m37g2000prh.googlegroups.com> References: <1182532691.182581.110940@m37g2000prh.googlegroups.com> Message-ID: Not Python, but maybe relevant: http://www.scriptaworks.com/cgi-bin/wiki.sh/NoSQL/HomePage Alan Isaac From Eric_Dexter at msn.com Mon Jun 25 02:16:00 2007 From: Eric_Dexter at msn.com (Eric_Dexter at msn.com) Date: Sun, 24 Jun 2007 23:16:00 -0700 Subject: subprocess.popen question In-Reply-To: <1182599186.807361.293060@w5g2000hsg.googlegroups.com> References: <1182353267.200998.43900@w5g2000hsg.googlegroups.com> <1182380572.235876.113160@n2g2000hse.googlegroups.com> <1182389286.706352.64780@o61g2000hsh.googlegroups.com> <1182485136.821993.315710@o11g2000prd.googlegroups.com> <1182517729.509639.254860@m36g2000hse.googlegroups.com> <1182599186.807361.293060@w5g2000hsg.googlegroups.com> Message-ID: <1182752160.543767.223590@n60g2000hse.googlegroups.com> On Jun 23, 6:46 am, SPE - Stani's Python Editor wrote: > On Jun 23, 5:35 am, "Gabriel Genellina" > wrote: > > > > > > > En Fri, 22 Jun 2007 10:08:49 -0300, Eric_Dex... at msn.com > > escribi?: > > > > I seemed to have it working sorta when I run it and save the results I > > > am noticing that inspeit spaces correctly but when I save it to a > > > file I can open it in wordpad there is only one line. when I open in > > > up in WinXound (Acsoundeditor) it is double spaced. if I do it in a > > > batch file the output file is spaced correctly.. when I do splitlines > > > it is giving me one charecter down the page as output.. Do I need to > > > do something or can I do something to put an end of line charecter in > > > the output?? > > > Try > > > print repr(your_data) > > > to see exactly what you got. > > > -- > > Gabriel Genellina > > Did you take in account that line endings on Windows are '\r\n' and > not '\n'? > > Stani > --http://pythonide.stani.be- Hide quoted text - > > - Show quoted text - evedently when they converted awk from unix to windows (gawk) they left the formating the same.. python is working corectly then. gawk seems to return the original line and then the changed line unless I redirect it to a file.... Thanks for the help, at this point it is up to me to go through the different versions of awk to find out how they work with the data... (awke, gawk, mawk, nawk.. exc..) From robert.rawlins at thinkbluemedia.co.uk Thu Jun 28 14:12:53 2007 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins - Think Blue) Date: Thu, 28 Jun 2007 19:12:53 +0100 Subject: Threads Dying? Message-ID: <04ec01c7b9af$f22031c0$d6609540$@rawlins@thinkbluemedia.co.uk> Hello Guys, I've got an application that seems to be a little bit unstable and freezes quite a bit, and I'm suspecting it's something in one of my threads that's causing the problem, when does a thread die? And how can I be sure that its dyeing when its mean to be? Thanks guys, Rob -------------- next part -------------- An HTML attachment was scrubbed... URL: From grante at visi.com Fri Jun 1 14:28:42 2007 From: grante at visi.com (Grant Edwards) Date: Fri, 01 Jun 2007 18:28:42 -0000 Subject: c[:]() References: <1180504190.055427.173610@h2g2000hsg.googlegroups.com> <1180554872.3356.30.camel@dot.uniqsys.com> <465DF3DE.40404@cc.umanitoba.ca> <1180566831.239580.199300@m36g2000hse.googlegroups.com> <005401c7a31a$136f7fe0$240110ac@Muse> <135tobve86qj808@corp.supernews.com> <135tru124pie2b3@corp.supernews.com> <135tv1bjqgbmsc9@corp.supernews.com> <9qudnbFRU9QHJsLbnZ2dnUVZ_rKvnZ2d@speakeasy.net> Message-ID: <1360paqqj12qnfd@corp.supernews.com> On 2007-06-01, Warren Stringer wrote: >> And that your insisting on ``c[:]()`` instead of just ``c()`` >> seems to indicate you want a change that is quite surprising. >> It would mean that a slice of a list returns an other type >> with the __call__ method implemented. > > I am not insisting on anything. I use ``c[:]()`` as shorthand > way of saying "c() for c in d where d is a container" Once again, that's gibberish. Where does "d" come from? c[:]() and c() _ARE_THE_SAME_THING_. c[:]() is another way of saying c() PERIOD. "d" doesn't enter into it, and by no stretch of the imagination is c[:]() "shorthand" for c() since it's _twice_as_long_. > Having c() support containers seems obvious to me. Again, that sentence appears to me to be meaningless. "c()" doesn't "support" anything. "c()" is just syntax that says to invoke the __call__ method of the object to which the name "c" is bound. > It jibes with duck typing. To what does "it" refer? > Perhaps the title of this thread should have been: "Why don't > containers quack?" I'm not sure where you're getting your vocabularly, but it seems to be completely foreign. > A change is surprising only if it breaks something. I still > haven't seen any code that breaks by making such a change. > Seeing such code would teach a great deal. If I show you some, will that make you happy? -- Grant Edwards grante Yow! Where does it go when at you flush? visi.com From michele.simionato at gmail.com Sat Jun 23 10:30:58 2007 From: michele.simionato at gmail.com (Michele Simionato) Date: Sat, 23 Jun 2007 14:30:58 -0000 Subject: Python's "only one way to do it" philosophy isn't good? In-Reply-To: References: <1181368143.874341.273140@r19g2000prf.googlegroups.com> <7x3b0nmkk6.fsf@ruckus.brouhaha.com> Message-ID: <1182609058.566839.210870@n2g2000hse.googlegroups.com> On Jun 22, 7:54 pm, Douglas Alan wrote: > The proof is in the pudding for anyone who has seen the advantages it > brings to Lisp. As Paul Graham points out, it's hard to look up and > see the advantages of what is up there in a more powerful language. > It's only easy to look down and see the disadvantages of what is > missing from a less powerful language. To understand the advantages, > one has to be willing to climb the hill and take in the view. Right. However you fail to recognize that there are people here with a good understanding of Lisp and its macrology that still prefer Python over Lisp. I will go even further and say that the utility of macros is inversely proportional to the power of a language: the more the language is powerful, the less macros are useful. Really powerful languages (say Haskell, just not to be too Python-centric) do not need macros. Provocative-but-with-a-grain-of-salt-in-it-yours, Michele Simionato From stefan.behnel-n05pAM at web.de Wed Jun 20 04:16:40 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Wed, 20 Jun 2007 10:16:40 +0200 Subject: Splitting SAX results In-Reply-To: References: <1181187340.685296.284850@i38g2000prf.googlegroups.com> <4667A954.8070909@web.de> <1181335953.348151.57540@n15g2000prd.googlegroups.com> <1181675805.996632.311070@r19g2000prf.googlegroups.com> Message-ID: <4678E268.1090203@web.de> Gabriel Genellina wrote: > Forget about SAX. Use ElementTree instead > ElementTree is infinitely more flexible and easier to use. > See That's what I told him/her already :) Rephrasing a famous word: Being faced with an XML problem, you might think "Ok, I'll just use SAX". And now you have two problems. SAX is a great way to hide your real problems behind a wall of unreadable code. If you want my opinion, lxml is currently the straightest way to get XML work done in Python. Stefan From max at alcyone.com Wed Jun 27 21:51:19 2007 From: max at alcyone.com (Erik Max Francis) Date: Wed, 27 Jun 2007 18:51:19 -0700 Subject: equality & comparison by default (was Re: Too many 'self' in python.That's a big flaw in this language.) In-Reply-To: References: <1182942154.185461.89620@e9g2000prf.googlegroups.com> <1i0cy8z.z94q5d1dxgexxN%aleax@mac.com> Message-ID: Aahz wrote: > In article <1i0cy8z.z94q5d1dxgexxN%aleax at mac.com>, > Alex Martelli wrote: >> In Python 3000, ordering comparisons will not exist by default (sigh, a >> modest loss of practicality on the altar of purity -- ah well, saw it >> coming, ever since complex numbers lost ordering comparisons), but >> equality and hashing should remain just like now (yay!). > > While emotionally I agree with you, in practice I have come to agree > with the POV that allowing default ordering comparisons between disjoint > types causes subtle bugs that are more difficult to fix than the small > amount of boilerplate needed to force comparisons when desired. I agree. It makes more sense to have to specify an ordering rather than assume an arbitrary one that may or may not have any relation to what you're interested in. I always did think that the inability to compare complex numbers was a bit of a wart -- not because it's not mathematically correct, since it is, but rather since everything else was comparable, even between distinct types -- but I think the more sensible approach is to allow equality by default (which defaults to identity), and only support comparisons when the user defines what it is he wants them to mean. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM, Y!M erikmaxfrancis Water which is too pure has no fish. -- Ts'ai Ken T'an From twisted0n3 at gmail.com Wed Jun 27 07:04:39 2007 From: twisted0n3 at gmail.com (Twisted) Date: Wed, 27 Jun 2007 11:04:39 -0000 Subject: The Modernization of Emacs: terminology buffer and keybinding In-Reply-To: <87ir9924l5.fsf@mail.eng.it> References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182272495.990807.99110@a26g2000pre.googlegroups.com> <87tzt3ihev.fsf@kobe.laptop> <1182370216.961241.6960@n60g2000hse.googlegroups.com> <85zm2ufjpb.fsf@lola.goethe.zz> <1182372592.803332.288260@u2g2000hsc.googlegroups.com> <1182549094.366282.286740@m37g2000prh.googlegroups.com> <87bqf7fwmg.fsf@telesippa.clsnet.nl> <1182553682.197778.138500@g37g2000prf.googlegroups.com> <87r6nzc9nu.fsf@mail.eng.it> <1182904631.083783.170640@o61g2000hsh.googlegroups.com> <87ir9924l5.fsf@mail.eng.it> Message-ID: <1182942279.999992.200250@q75g2000hsh.googlegroups.com> On Jun 27, 4:18 am, Gian Uberto Lauri wrote: [A very long, rambling, semi-coherent post] > Strange. I am *NOT* a native english speaker and I think my Q.I. tends > toward average from below... That much is obvious. > ...but refcard sound very useful to me, maybe is short for "reference card" ? Yes, but you'd have to be some kind of clairvoyant to realize "I know! I'll do a search for "refcard.ps" on the off chance someone happens to have made a reference card, called it "refcard", and chose the Postscript format to record it in!" out of the blue. > I admit. find is less intuitive. But the stuff Windows comes with does > just that and nothing more. It will never suggest you that the long > boring task expecting you can be solved in a completely automatic > way with a little creative job. And with one little typo, it's hello Sorceror's Apprentice mode... > Emacs help was hypertextual when Dr. Watson plagued Windowd 3.11 > users... Dr. Watson just plagued this WinXP user. Please don't mention Dr. Watson again for a while, for the love of Christ. > Splash, large miss. This is usenet, not Battleship. > You usually fire it to the local printer. Yes, if you have one and care to blow through reams of paper and gallons of ink every month by printing everything you encounter instead of reading it on the expensive LCD monitor you got for such purposes. > T> enough. Trying to read anything serious and navigate in GSView is > T> no picnic either. > > A refcard, my dear, is something that goes on an A4/Letter sheet and > NEEDS NOT to be hypertextual. I was being more general. > With a PS file you can do just one thing, execute it. It's a program, > did you know ? For which you need an interpreter. Such as Ghostscript. Which is a pain to install and a bigger one to configure, even on Windoze. > Uh, I forget. For Windows users getting a PDF out of a PS or HTML or > ASCII is not this easy unless they get some extra software (someone > ported CUPS to Windows ?). Again, not an Emacs fault. I wouldn't know CUPS if it dropped on my head. I think the same can be said of most of the 3 or 4 non-expert unix users in the world. > Stop guessing or all will know that all you know about Unix is that > is a 4 letter word... Yeah. Unix is a four-letter word alright. > All the computer screen is devoted to your work, the sheet provides > some extra "real estate" for the help information, a sort of double > heading display. All you need to do is turn your eyes from the > monitor, maybe your eyes and read the informations. It coudl happen > that you need to flip the sheet. But you can keep both your work and > the help text "ready at your fingertips", and this is useful indeed: > you read the command keybinding, turn your eyes, type it and see the > result and/or continue your work. One small step backwards for a man, one giant leap... > About money. Indeed ink/toner and paper costs. Electricity grows on > the spark tree so aboundant in our forests... This intrigues my younger brother. He wants to know how many moons are in the sky and what color the sun is that your planet orbits. He's at that phase where he's fascinated by astronauts, tales of alien worlds, and things like that, you see... > But PostScript printing on my '80 Epson printwriter or my HP720c with > a Unix system with CUP is as easy as opening a browser, telling the > system I have a HP720c plugged to the parallel port and voil?. I'll bet. Something tells me the catch lies somewhere in "a Unix system with CUP". Unless it's in "browser" instead. Something tells me we're not talking about something that resembles Firefox and makes navigation easy and intuitive here. > In the same time I got an HP720c and it come with no other drivers > than Mac and Windows ones. I feared I was SOL when I readed of some > guy that wrote a small program that was able to convert certain gs > output to byte sequences good to pilot the HP720c. > > It was *easy* to put this program in the pipeline in the "printer > driver" script. > > And was *easy* insert a2ps to shoot plain text directly to the printer. *Easy*. Maybe if you know all about the guts of how the printing subsystem of the OS works. I doubt it's anything like that easy for joe random who just wants to hit "print" and print the document already and not have to spend ages learning about the internals of the operating system first. In Windows, you plug it in and pick it from a dialog (or use a disc that comes with the printer to do setup) and print something. Voila! Out pops a document into the tray; no mess, no fuss. Getting out your wrench and going at the plumbing shouldn't be necessary; any more than I'd want to move into a new home and find I needed to break out the tools and mess with the plumbing before the toilet would flush or the kitchen tap spout water. > Ah, you'll start thinking that those who find find syntax arcane are > jackass... You need a little to realize it was not this easy in the > beginning. The dark side of power. Once you start down the dark path, forever will it dominate your destiny. Don't underestimate the power of the dark side! From steve at REMOVE.THIS.cybersource.com.au Sat Jun 23 21:24:06 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sun, 24 Jun 2007 11:24:06 +1000 Subject: Adding method to a class on the fly References: <1182538969.522044.209560@q19g2000prn.googlegroups.com> <1182543862.369337.36880@z28g2000prd.googlegroups.com> <1182547065.295969.258820@g37g2000prf.googlegroups.com> <1182547724.690874.279230@g37g2000prf.googlegroups.com> <1182548694.545515.81060@e9g2000prf.googlegroups.com> <1182582129.462036.84560@m37g2000prh.googlegroups.com> <1182614796.146337.290300@x35g2000prf.googlegroups.com> <1182627099.634025.37430@m37g2000prh.googlegroups.com> Message-ID: On Sat, 23 Jun 2007 12:31:39 -0700, John Henry wrote: > it works fine but PythonCard isn't calling this function when I > clicked on the button. I think you need to take this question onto a PythonCard list. I have no idea how PythonCard decides which method to call. -- Steven. From http Wed Jun 20 02:43:03 2007 From: http (Paul Rubin) Date: 19 Jun 2007 23:43:03 -0700 Subject: Python's "only one way to do it" philosophy isn't good? References: <1181368143.874341.273140@r19g2000prf.googlegroups.com> <1182320758.022154.88360@o61g2000hsh.googlegroups.com> Message-ID: <7xabuv5doo.fsf@ruckus.brouhaha.com> Michele Simionato writes: > I see Python or C as much better practical implementations > of Sussman's quote about minimalism than real Scheme (for > an example of real Scheme, I refer for instance to the PLT > implementation). Python and C as programming languages are like democracy as a system of government--absolutely terrible, but everything else seems to be even worse. The real answer (to programming languages, not governments) seems tantalizingly close, but not here yet. From tim.leslie at gmail.com Tue Jun 12 00:50:47 2007 From: tim.leslie at gmail.com (Tim Leslie) Date: Tue, 12 Jun 2007 14:50:47 +1000 Subject: Problem with following python code In-Reply-To: <1181622331.955264.31610@i38g2000prf.googlegroups.com> References: <1181622331.955264.31610@i38g2000prf.googlegroups.com> Message-ID: On 6/12/07, why? wrote: > I've been having problem with the following code. It's supposed to > print the prime numbers between 10 and 100. But i'm not getting any > output, i.e. i guess the outer 'for' loop is being traversed only > once. I would be greatful if you could help me out. Thanx! > >>> f=1 > >>> for i in range(10,100): You need to switch these two lines to reset the flag each time around the outer loop. Cheers, Tim > ... for j in range(2,i): > ... if i%j==0: > ... f=0 > ... break > ... else: continue > ... if f==1: > ... print i, > ... > > -- > http://mail.python.org/mailman/listinfo/python-list > From martin at see.sig.for.address Tue Jun 26 16:11:58 2007 From: martin at see.sig.for.address (Martin Gregorie) Date: Tue, 26 Jun 2007 21:11:58 +0100 Subject: Portable general timestamp format, not 2038-limited In-Reply-To: <7xlke6y6y1.fsf@ruckus.brouhaha.com> References: <1182544384.709759.235300@o11g2000prd.googlegroups.com> <20070625133843.9e25d0ab.steveo@eircom.net> <82b5l4-tvh.ln1@zoogz.gregorie.org> <7xbqf3lc7i.fsf@ruckus.brouhaha.com> <70c7l4-2gp.ln1@zoogz.gregorie.org> <7xlke6y6y1.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > Same one already given: http://cr.yp.to/proto/utctai.html Nope - you referenced leap seconds, not TAI and not that URL Thanks for the reference, though. -- martin@ | Martin Gregorie gregorie. | Essex, UK org | From jjl at pobox.com Tue Jun 12 15:12:47 2007 From: jjl at pobox.com (John J. Lee) Date: Tue, 12 Jun 2007 19:12:47 GMT Subject: Longest issue tracker thread? Message-ID: <87wsy9j8b4.fsf@pobox.com> Reading a recent message about a mozilla project bugzilla comment thread 7 years old, I am curious re how dismally long and drawn-out a tracker thread has so far been observed in the wild. Possibly there are older issues in the Python project's own tracker, for starters? Separate prizes will be awarded for open source and proprietary projects. The judges' decision is final, etc etc. John From wildemar at freakmail.de Mon Jun 4 02:35:24 2007 From: wildemar at freakmail.de (Wildemar Wildenburger) Date: Mon, 04 Jun 2007 08:35:24 +0200 Subject: subexpressions (OT: math) In-Reply-To: <466354C0.4010700@islandtraining.com> References: <4662675b$1_5@news.bluewin.ch> <1180890214.317409.85100@w5g2000hsg.googlegroups.com> <4662FDC8.9080407@islandtraining.com> <46634BDC.7090104@freakmail.de> <466354C0.4010700@islandtraining.com> Message-ID: <4663B2AC.7010502@freakmail.de> Gary Herron wrote: >> The radian is defined as the ratio of an arc of circumfence of a circle >> to the radius of the circle and is therefore *dimensionless*. End of story. >> http://en.wikipedia.org/wiki/Radian and esp. >> http://en.wikipedia.org/wiki/Radian#Dimensional_analysis >> >> >> > > The arguments to sine and cosine must have an associated unit so you > know whether to interpret sin(1.2) as sine of an angle measured in > degrees or radians (or whatever else). > Touch?. :) Yes, I think we can all agree on that. /W From justin.mailinglists at gmail.com Mon Jun 25 01:00:45 2007 From: justin.mailinglists at gmail.com (Justin Ezequiel) Date: Mon, 25 Jun 2007 05:00:45 -0000 Subject: regular expressions eliminating filenames of type foo.thumbnail.jpg In-Reply-To: <1182746933.413693.103860@p77g2000hsh.googlegroups.com> References: <1182746933.413693.103860@p77g2000hsh.googlegroups.com> Message-ID: <1182747645.092002.68800@x35g2000prf.googlegroups.com> Why not ditch regular expressions altogether for this problem? [ p for p in os.listdir(dir) if os.path.isfile(os.path.join(dir,p)) and p.lower().find('.thumbnail.')==-1 ] From larry.bates at websafe.com Thu Jun 21 11:50:54 2007 From: larry.bates at websafe.com (Larry Bates) Date: Thu, 21 Jun 2007 10:50:54 -0500 Subject: Conceptualizing Threading In-Reply-To: <1182433877.742774.321760@p77g2000hsh.googlegroups.com> References: <1182433877.742774.321760@p77g2000hsh.googlegroups.com> Message-ID: <7MadnZFB5eHPA-fbnZ2dnUVZ_qTinZ2d@comcast.com> JonathanB wrote: > I have a multi-access problem that I'm pretty sure needs to be solved > with threading, but I'm not sure how to do it. This will be my first > foray into threading, so I'm a little confused by all of the new > landscape. So, I'm going to lay out the problem I'm facing and if > someone could point me towards a good example of what I need to do, > that would be great. I read THE tutorial, and while it made since to > me in an esoteric sense, I'm not sure how to implement it. > > I have a program which will be logging who took what orders. These > orders need to have sequential order numbers. SR001001, SR001002, > SR001003, etc. Problem is I'm not sure how many people will be > accessing this program at the same time. I thought about separating > the order number into its own file and the having a function open it, > read it, increment it, write it, and close it really quick to limit > the chance of two people pulling the same number. Then I heard found > threading. > > So this sounds like a consumer/producer problem, right? So I think I > need to use a Queue to crank out quote numbers and have the users > connect to the queue to get their number. Does that mean I'm looking > at two separate programs, a server and a client? Where do I separate > the programs? I was just about to give up and have quote number > assignment be manual (with error checking), but I thought I should > check here first and see if someone could help me wrap my brain around > this problem. You'll never learn if you never try, right? > Just use a database with an auto-incrementing column. It will handle all the "threading" that you think you require and each call will return the next number you need. -Larry From kyle at thenortheastgroup.com Thu Jun 21 11:54:12 2007 From: kyle at thenortheastgroup.com (kyle at thenortheastgroup.com) Date: Thu, 21 Jun 2007 08:54:12 -0700 Subject: Adding Python to the path in Windows In-Reply-To: <1182440996.339856.260130@p77g2000hsh.googlegroups.com> References: <1182437575.810986.205610@n2g2000hse.googlegroups.com> <1182439377.009844.320760@q75g2000hsh.googlegroups.com> <1182439800.148330.221600@p77g2000hsh.googlegroups.com> <1182440715.401553.37590@n60g2000hse.googlegroups.com> <1182440996.339856.260130@p77g2000hsh.googlegroups.com> Message-ID: <1182441252.746366.29820@m36g2000hse.googlegroups.com> On Jun 21, 11:49 am, kyoso... at gmail.com wrote: > I should probably mention that if you have some complicated GUI's, > they will probably load slowly over the network. And I did notice that > scripts using WMI and pyWin32 modules can be slower than they ought to > be. Just something to keep in mind if you have a slow connection. We > have a T1 out to a remote location and it's caused some minor issues > using anything of that nature. > > Mike I will probably do this then, because Duncan's solution does not seem to be working for me. If I run a Python script directly from a command line, it works fine just like he said. But I am using the Shell() command in Visual Basic 2005 to run the Python script, and it doesn't seem to be working. I am getting an error, "File not found". Not sure what the difference would be. But your solution should work. From jackie.BPUG at gmail.com Fri Jun 15 09:57:55 2007 From: jackie.BPUG at gmail.com (Jackie) Date: Fri, 15 Jun 2007 06:57:55 -0700 Subject: Output of HTML parsing Message-ID: <1181915875.875312.137080@z28g2000prd.googlegroups.com> Hi, all, I want to get the information of the professors (name,title) from the following link: "http://www.economics.utoronto.ca/index.php/index/person/faculty/" Ideally, I'd like to have a output file where each line is one Prof, including his name and title. In practice, I use the CSV module. The following is my program: --------------- Program ---------------------------------------------------- import urllib,re,csv url = "http://www.economics.utoronto.ca/index.php/index/person/ faculty/" sock = urllib.urlopen(url) htmlSource = sock.read() sock.close() namePattern = re.compile(r'class="name">(.*)') titlePattern = re.compile(r', (.*)\s*') name = namePattern.findall(htmlSource) title_temp = titlePattern.findall(htmlSource) title =[] for item in title_temp: item_new=" ".join(item.split()) #Suppress the spaces between 'title' and title.extend([item_new]) output =[] for i in range(len(name)): output.insert(i,[name[i],title[i]]) #Generate a list of [name, title] writer = csv.writer(open("professor.csv", "wb")) writer.writerows(output) #output CSV file -------------- End of Program ---------------------------------------------- My questions are: 1.The code above assume that each Prof has a tilte. If any one of them does not, the name and title will be mismatched. How to program to allow that title can be empty? 2.Is there any easier way to get the data I want other than using list? 3.Should I close the opened csv file("professor.csv")? How to close it? Thanks! Jackie From mensanator at aol.com Fri Jun 22 13:20:13 2007 From: mensanator at aol.com (mensanator at aol.com) Date: Fri, 22 Jun 2007 10:20:13 -0700 Subject: SimplePrograms challenge In-Reply-To: References: Message-ID: <1182532813.881683.209530@n2g2000hse.googlegroups.com> Ah, I mistook you for someone who gives a shit. - You DID see my post on comp.lang.python and deliberately ignored it. - You then lied and claimed there was no discussion. - You then lied and claimed my example merely duplicated other examples. - You claimed to be offended by my characterization of your obfuscation policy as foolish and then turned around and proved it was foolish by admitting you couldn't comprehend the example because it didn't have enough comments. Duh! You're going to end up with a really short fucking list if you ignore and delete that which you can't understand. Great way to encourage contributions. From google at mrabarnett.plus.com Sat Jun 9 19:02:28 2007 From: google at mrabarnett.plus.com (MRAB) Date: Sat, 09 Jun 2007 16:02:28 -0700 Subject: Python for embedded systems with memory constraints In-Reply-To: References: Message-ID: <1181430148.793716.110350@q69g2000hsb.googlegroups.com> On Jun 9, 1:33 pm, vishnu wrote: > Hi, > Thanks Cameron for your suggestions. > In fact I am using custom memory sub-allocator where I preallocate a > pool of memory during initialization of my application and ensure that > Python doesn't make any system mallocs later . With this arrangement, > python seems to run out of preallocated memory (of 10MB) after running > few simple scripts due to huge external fragmentation. My memory > sub-allocator got a good design which uses the best-fit algorithm and > coaelescing the adjacent blocks during each free call. > If anybody out there used their own memory manager and ran Python > without fragmentation , could provide some inputs on this. > >From what I remember, the best-fit algorithm isn't a good idea because unless the free block was exactly the right size you'd tend to get left with lots of small fragments. (Suppose that the best fit was a free block only 4 bytes bigger than what you want; what can you do with a free block of 4 bytes?) A worst-fit algorithm would leave larger free blocks which are more useful subsequently, but I think that the recommendation was next-fit (ie use the first free block that's big enough, starting from where you found the last one). From kyosohma at gmail.com Fri Jun 8 13:50:16 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Fri, 08 Jun 2007 10:50:16 -0700 Subject: Tkinter - Force toplevel window to stay on top of Tk() window In-Reply-To: <1181321314.023016.185650@i38g2000prf.googlegroups.com> References: <1181321314.023016.185650@i38g2000prf.googlegroups.com> Message-ID: <1181325016.767396.128640@q69g2000hsb.googlegroups.com> On Jun 8, 11:48 am, rahulna... at yahoo.com wrote: > Hi, > I have a Tk() window "base_win = Tk()" with multiple frames on it > having a combination of widgets. If I click on say a button widget > which launches a new top level window "new_win = TopLevel()", I was > looking for a way for this "new_win" to always stay on top of > "base_win" till I close "new_win", as a result also not allowing any > selections to be made in the "base_win" . > Thanks > Rahul You need to research showing modal dialogs. This link looks promising: http://mail.python.org/pipermail/tkinter-discuss/2005-March/000371.html This one from Lundh's site has better explanations on dialog's in general: http://effbot.org/tkinterbook/tkinter-dialog-windows.htm Mike From ping.nsr.yeh at gmail.com Sun Jun 17 12:49:23 2007 From: ping.nsr.yeh at gmail.com (Ping) Date: Sun, 17 Jun 2007 16:49:23 -0000 Subject: a_list.count(a_callable) ? In-Reply-To: <1182094967.099444.91410@n15g2000prd.googlegroups.com> References: <1181850818.567840.251090@x35g2000prf.googlegroups.com> <1181853479.914070.217270@i13g2000prf.googlegroups.com> <1181855184.511137.100870@z28g2000prd.googlegroups.com> <1181916937.648267.163070@z28g2000prd.googlegroups.com> <1181981527.960296.135820@i13g2000prf.googlegroups.com> <1182026221.039617.56320@n2g2000hse.googlegroups.com> <1182094967.099444.91410@n15g2000prd.googlegroups.com> Message-ID: <1182098963.177045.15110@j4g2000prf.googlegroups.com> > print "b has", b.count(25, cmp=le, key=attrgetter("age")), \ > "elements with age <= 25." > [deleted] > b has 2 elements with age <= 30. Oops, I mixed up when copying and pasting at different times... :p The output was of course b has 1 elements with age <= 25. Ping From s_broscious at comcast.net Wed Jun 27 12:53:36 2007 From: s_broscious at comcast.net (Scott) Date: Wed, 27 Jun 2007 12:53:36 -0400 Subject: Reversing a string Message-ID: Yeah I know strings == immutable, but question 1 in section 7.14 of "How to think like a computer Scientist" has me trying to reverse one. I've come up with two things, one works almost like it should except that every traversal thru the string I've gotten it to repeat the "list" again. This is what it looks like: [code] >>>mylist = [] >>>def rev(x): for char in x: mylist.append(char) mylist.reverse() print mylist [/code] And the output that sorta works like it should, but threw a curveball, at me looks like this: >>> rev("this is just a test") ['t'] ['h', 't'] ['i', 't', 'h'] ['s', 'h', 't', 'i'] [' ', 'i', 't', 'h', 's'] ['i', 's', 'h', 't', 'i', ' '] ['s', ' ', 'i', 't', 'h', 's', 'i'] [' ', 'i', 's', 'h', 't', 'i', ' ', 's'] ['j', 's', ' ', 'i', 't', 'h', 's', 'i', ' '] ['u', ' ', 'i', 's', 'h', 't', 'i', ' ', 's', 'j'] ['s', 'j', 's', ' ', 'i', 't', 'h', 's', 'i', ' ', 'u'] ['t', 'u', ' ', 'i', 's', 'h', 't', 'i', ' ', 's', 'j', 's'] [' ', 's', 'j', 's', ' ', 'i', 't', 'h', 's', 'i', ' ', 'u', 't'] ['a', 't', 'u', ' ', 'i', 's', 'h', 't', 'i', ' ', 's', 'j', 's', ' '] [' ', ' ', 's', 'j', 's', ' ', 'i', 't', 'h', 's', 'i', ' ', 'u', 't', 'a'] ['t', 'a', 't', 'u', ' ', 'i', 's', 'h', 't', 'i', ' ', 's', 'j', 's', ' ', ' '] ['e', ' ', ' ', 's', 'j', 's', ' ', 'i', 't', 'h', 's', 'i', ' ', 'u', 't', 'a', 't'] ['s', 't', 'a', 't', 'u', ' ', 'i', 's', 'h', 't', 'i', ' ', 's', 'j', 's', ' ', ' ', 'e'] ['t', 'e', ' ', ' ', 's', 'j', 's', ' ', 'i', 't', 'h', 's', 'i', ' ', 'u', 't', 'a', 't', 's'] So I figured maybe make it a generator (I'm not TO familiar with generators yet so don't laugh) which changed my code just a slight bit: [code] >>>mylist = [] >>>def rev(x): for char in x: mylist.append(char) mylist.reverse() yield mylist [/code] But even that threw me a curveball: >>> rev("this is just a test") So how on earth would be the best way to: Write a function that takes a string as an argument and outputs the letters backward, one per line. It should look like the first char of every list in the top "working" code. Any help woould be greatly apreciated, and a little bit of explaination as to why you did it the way you did would be more helpful than just the code. Thanks in advance From grante at visi.com Thu Jun 14 13:08:48 2007 From: grante at visi.com (Grant Edwards) Date: Thu, 14 Jun 2007 17:08:48 -0000 Subject: Method much slower than function? References: <1181781612.939800.238890@q19g2000prn.googlegroups.com> Message-ID: <1372th08vud957d@corp.supernews.com> On 2007-06-14, Steven D'Aprano wrote: > However, having said that, the speed difference does seem to be real: even > when I correct the above issue, I get a large time difference using > either cProfile.run() or profile.run(), and timeit agrees: > >>>> f = bar().readgenome >>>> timeit.Timer("f(open('cb_foo'))", "from __main__ import f").timeit(5) > 18.515995025634766 >>>> timeit.Timer("readgenome(open('cb_foo'))", "from __main__ import readgenome").timeit(5) > 0.1940619945526123 > > That's a difference of two orders of magnitude, and I can't see why. Is it independent of the test order? What happens when you reverse the order? What happens if you run the same test twice in a row? -- Grant Edwards grante Yow! Thank god!! ... It's at HENNY YOUNGMAN!! visi.com From showell30 at yahoo.com Sun Jun 3 16:32:32 2007 From: showell30 at yahoo.com (Steve Howell) Date: Sun, 3 Jun 2007 13:32:32 -0700 (PDT) Subject: *Naming Conventions* In-Reply-To: Message-ID: <716715.11596.qm@web33512.mail.mud.yahoo.com> --- Thorsten Kampe wrote: > > for validanswer in validanswers: > if myAnswers.myanswer in > myAnswers.validAnswers[validanswer]: > MyOptions['style'] = validanswer > I can at least sympathize with your problem, although I don't have a great solution for you. I often have trios of variables like this: answer_dct answers answer English mostly pluralizes with an "s," but I sometimes resort to bad English to keep the convention going: mouse_dct mouses (not mice) mouse I also still waste brain cycles on naming dictionaries. Sometimes I name the dictionary after the values it stores, sometimes after the keys it uses, and sometimes after both. ____________________________________________________________________________________ Luggage? GPS? Comic books? Check out fitting gifts for grads at Yahoo! Search http://search.yahoo.com/search?fr=oni_on_mail&p=graduation+gifts&cs=bz From senwin30 at gmail.com Tue Jun 26 10:42:37 2007 From: senwin30 at gmail.com (senthil arasu) Date: Tue, 26 Jun 2007 09:42:37 -0500 Subject: Help needed in Handling HTML file Message-ID: <1ef9860e0706260742r18fd9a6ftb3684e660a5b3aee@mail.gmail.com> Hi, Right now Iam handling HTML files using Python. Is there any modules to support HTML parsing and rendering ? or suggest me any other way to support HTML. thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: From bj_666 at gmx.net Tue Jun 12 12:28:54 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Tue, 12 Jun 2007 18:28:54 +0200 Subject: a question about unicode in python References: <1181663182.251071.10540@i13g2000prf.googlegroups.com> Message-ID: In <1181663182.251071.10540 at i13g2000prf.googlegroups.com>, hzqij wrote: > i have a python source code test.py > > # -*- coding: UTF-8 -*- > > # s is a unicode string, include chinese > s = u'??' > > then i run > > $ python test.py > UnicodeDecodeError: 'utf8' codec can't decode bytes in position 0-1: > invalid data > > by in python interactive, it is right > >>>> s = u'??' > > why? Does the "coding comment" match the actual encoding of the source file? Ciao, Marc 'BlackJack' Rintsch From tokyo246 at gmail.com Wed Jun 20 23:24:28 2007 From: tokyo246 at gmail.com (Kenji Noguchi) Date: Wed, 20 Jun 2007 20:24:28 -0700 Subject: string formatter %x and a class instance with __int__ or __long__ cannot handle long Message-ID: <2ba587f0706202024p240f1bdbld2bba73f970f9968@mail.gmail.com> Hi I'm using Python 2.4.4 on 32bit x86 Linux. I have a problem with printing hex string for a value larger than 0x800000000 when the value is given to % operator via an instance of a class with __int__(). If I pass a long value to % operator it works just fine. Example1 -- pass a long value directly. this works. >>> x=0x80000000 >>> x 2147483648L >>> type(x) >>> "%08x" % x '80000000' Example2 -- pass an instance of a class with __int__() >>> class X: ... def __init__(self, v): ... self.v = v ... def __int__(self): ... return self.v ... >>> y = X(0x80000000) >>> "%08x" % y Traceback (most recent call last): File "", line 1, in ? TypeError: int argument required >>> The behavior looks inconsistent. By the way __int__ actually returned a long type value in the Example2. The "%08x" allows either int or long in the Example1, however it accepts int only in the Example2. Is this a bug or expected? by the way same thing happends on a 64bit system with a value of 0x8000000000000000. Regards, Kenji Noguchi From dsh at linux.ucla.edu Tue Jun 12 00:52:16 2007 From: dsh at linux.ucla.edu (Dan Hipschman) Date: Mon, 11 Jun 2007 21:52:16 -0700 Subject: Problem with following python code In-Reply-To: <1181622331.955264.31610@i38g2000prf.googlegroups.com> References: <1181622331.955264.31610@i38g2000prf.googlegroups.com> Message-ID: <20070612045216.GA548@linux.ucla.edu> On Tue, Jun 12, 2007 at 04:25:31AM -0000, why? wrote: > I've been having problem with the following code. It's supposed to > print the prime numbers between 10 and 100. But i'm not getting any > output, i.e. i guess the outer 'for' loop is being traversed only > once. I would be greatful if you could help me out. Thanx! > >>> f=1 > >>> for i in range(10,100): > ... for j in range(2,i): > ... if i%j==0: > ... f=0 > ... break > ... else: continue > ... if f==1: > ... print i, > ... Move "f=1" inside the outer loop: for i in range(10,100): f=1 for j in range(2,i): if i%j==0: f=0 break else: continue if f==1: print i, It gets set to 0 in the first iteration and never has another chance to be set to 1 after that. From wildemar at freakmail.de Mon Jun 4 06:40:56 2007 From: wildemar at freakmail.de (Wildemar Wildenburger) Date: Mon, 04 Jun 2007 12:40:56 +0200 Subject: subexpressions (OT: math) In-Reply-To: References: <4662675b$1_5@news.bluewin.ch> <1180890214.317409.85100@w5g2000hsg.googlegroups.com> <1180894045.538031.111610@g4g2000hsf.googlegroups.com> <1180895200.108582.313010@k79g2000hse.googlegroups.com> Message-ID: <4663EC38.5080109@freakmail.de> Peter Otten wrote: > With y = x^2 = 1/3 pi^2 - 4(cos x - cos(2x)/2^2 + cos(3x)/3^2 - ...) > > area is dimensionless, too, I suppose. > Ehr, ... maybe this is obvious, but I don't see it: Please explain the second equality sign. /W From gagsl-py2 at yahoo.com.ar Tue Jun 26 23:39:58 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 27 Jun 2007 00:39:58 -0300 Subject: guidance needed: best practice for script packaging References: Message-ID: En Tue, 26 Jun 2007 23:35:37 -0300, Alan Isaac escribi?: > This is a simple question about actual practice. > I just want to know how you (yes you) are > approaching this problem. > > The problem: > What is the recommended packaging of > demo scripts or test scripts for a package > to be distributed to others to "play with". > (I.e., without "installing".) > > Example: > Suppose I have the package structure: > > package/ > __init__.py > subpackage1/ > __init__.py > moduleXX.py > subpackage2/ > __init__.py > moduleYY.py > > Important detail: > moduleXX uses a relative import to access moduleYY. I put test/demo/main scripts *outside* the package - that would be the directory containing "package" here. This way, "import package" works, and intra-package relative references work too. > The goal: > I have a script test.py that I want to > distribute with the package. This script will import > moduleXX to illustrate or test the module's use. > > Is it the case that this script cannot reasonably be > bundled with `package`? (I.e., within its directory > structure.) Yes, perhaps there is no reasonably/good/non-hackish way to bundle it inside "package". At least I don't know how to do that and also keep relative imports working at the same time, without playing with sys.path and such things. > Here is one hack, based on a suggestion of Alex Martelli > http://mail.python.org/pipermail/python-list/2007-May/438250.html > and others. > - add a `scripts` subdirectory to `package` > - use path manipulation to find the directory holding `package` > - insert this directory in sys.path I use directly the parent directory (not a "scripts" subdirectory) because it is already in sys.path (being the current directory where the script resides). And I have only one or two such scripts, so it's not a big problem for me if they are not grouped in its own directory. > I do not want to assume the package will be installed: > a user should be able to play with it without installing it. What I suggest works in this case too. > This is a repeat question. The usual rule is, if you do not get an > answer, you > are asking the question in an unhelpful way. If my question is still > unclear, I > would appreciate any leads on how to clarify it. I read your previous post, but since I didn't feel that I had a "good" answer I didn't reply the first time. I were waiting for someone to enlighten me too on this topic... (Certainly rephrasing the question is a smart move - but most people aren't as smart as you and just keep posting the same thing over and over...) -- Gabriel Genellina From vedrandekovic at v-programs.com Mon Jun 25 16:11:07 2007 From: vedrandekovic at v-programs.com (vedrandekovic at v-programs.com) Date: Mon, 25 Jun 2007 13:11:07 -0700 Subject: Installing python under the linux In-Reply-To: References: <1182800785.231113.199750@n2g2000hse.googlegroups.com> Message-ID: <1182802267.969628.156960@o61g2000hsh.googlegroups.com> Danyelle Gragsone je napisao/la: > Greetings, > > Python is usally already installed on most distros. In a terminal > window type "python" to see if something happens. Also please provide > what distro you are running. > > Danyelle > > On 6/25/07, vedrandekovic at v-programs.com wrote: > > Hello, > > > > I have problem with installing Python on the Linux platform.Can you > > tell me step by step how can I install > > python on linux ( please detailed ) , because I don't know anything > > about linux and I really don't understand > > python documentation about installing python on linux. > > > > > > > > Thanks!!! > > > > -- > > http://mail.python.org/mailman/listinfo/python-list > > Helo, Probably my distro is "ubuntu" <--- I don't what is it, and ' want install/build python from source From china_city2008 at yahoo.com.cn Wed Jun 20 11:20:21 2007 From: china_city2008 at yahoo.com.cn (jim) Date: Wed, 20 Jun 2007 08:20:21 -0700 Subject: ebay Message-ID: <1182352821.514197.148330@j4g2000prf.googlegroups.com> hello: madam and sir . we sell all kinds of laptops and digital cam .our product is a quantity best, the price is the lowest in the world, i think you will be interested in our product . thanks a lot! Our Website:http://www.prs-123.com/ Msn: prs_cool_123 at hotmail.com mail: prs_cool_123 at yahoo.com.cn thanks for everyone good luck with everyone . @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ hello : madam and sir. we sell all kinds of laptops and digital cam .our product is a quantity best, the price is the lowest in the world, i think you will be interested in our product . thanks a lot! Our Website:http:// www.prs-123.com/ Msn: prs_cool_123 at hotmail.com mail: prs_cool_123 at yahoo.com.cn thanks for everyone good luck with everyone @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ hello: madam and sir . we sell all kinds of laptops and digital cam .our product is a quantity best, the price is the lowest in the world, i think you will be interested in our product . thanks a lot! Our Website:http:// www.prs-123.com/ Msn: prs_cool_123 at hotmail.com mail: prs_cool_123 at yahoo.com.cn thanks for everyone good luck with everyone . @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ hello : madam and sir. we sell all kinds of laptops and digital cam .our product is a quantity best, the price is the lowest in the world, i think you will be interested in our product . thanks a lot! Our Website:http:// www.prs-123.com/ Msn: prs_cool_123 at hotmail.com mail: prs_cool_123 at yahoo.com.cn thanks for everyone good luck with everyone hello: madam and sir . we sell all kinds of laptops and digital cam .our product is a quantity best, the price is the lowest in the world, i think you will be interested in our product . thanks a lot! Our Website:http://www.prs-123.com/ Msn: prs_cool_123 at hotmail.com mail: prs_cool_123 at yahoo.com.cn thanks for everyone good luck with everyone . @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ hello : madam and sir. we sell all kinds of laptops and digital cam .our product is a quantity best, the price is the lowest in the world, i think you will be interested in our product . thanks a lot! Our Website:http:// www.prs-123.com/ Msn: prs_cool_123 at hotmail.com mail: prs_cool_123 at yahoo.com.cn thanks for everyone good luck with everyone @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ hello: madam and sir . we sell all kinds of laptops and digital cam .our product is a quantity best, the price is the lowest in the world, i think you will be interested in our product . thanks a lot! Our Website:http:// www.prs-123.com/ Msn: prs_cool_123 at hotmail.com mail: prs_cool_123 at yahoo.com.cn thanks for everyone good luck with everyone . @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ hello : madam and sir. we sell all kinds of laptops and digital cam .our product is a quantity best, the price is the lowest in the world, i think you will be interested in our product . thanks a lot! Our Website:http:// www.prs-123.com/ Msn: prs_cool_123 at hotmail.com mail: prs_cool_123 at yahoo.com.cn thanks for everyone good luck with everyone hello: madam and sir . we sell all kinds of laptops and digital cam .our product is a quantity best, the price is the lowest in the world, i think you will be interested in our product . thanks a lot! Our Website:http://www.prs-123.com/ Msn: prs_cool_123 at hotmail.com mail: prs_cool_123 at yahoo.com.cn thanks for everyone good luck with everyone . @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ hello : madam and sir. we sell all kinds of laptops and digital cam .our product is a quantity best, the price is the lowest in the world, i think you will be interested in our product . thanks a lot! Our Website:http:// www.prs-123.com/ Msn: prs_cool_123 at hotmail.com mail: prs_cool_123 at yahoo.com.cn thanks for everyone good luck with everyone @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ hello: madam and sir . we sell all kinds of laptops and digital cam .our product is a quantity best, the price is the lowest in the world, i think you will be interested in our product . thanks a lot! Our Website:http:// www.prs-123.com/ Msn: prs_cool_123 at hotmail.com mail: prs_cool_123 at yahoo.com.cn thanks for everyone good luck with everyone . @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ hello : madam and sir. we sell all kinds of laptops and digital cam .our product is a quantity best, the price is the lowest in the world, i think you will be interested in our product . thanks a lot! Our Website:http:// www.prs-123.com/ Msn: prs_cool_123 at hotmail.com mail: prs_cool_123 at yahoo.com.cn thanks for everyone good luck with everyone hello: madam and sir . we sell all kinds of laptops and digital cam .our product is a quantity best, the price is the lowest in the world, i think you will be interested in our product . thanks a lot! Our Website:http://www.prs-123.com/ Msn: prs_cool_123 at hotmail.com mail: prs_cool_123 at yahoo.com.cn thanks for everyone good luck with everyone . @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ hello : madam and sir. we sell all kinds of laptops and digital cam .our product is a quantity best, the price is the lowest in the world, i think you will be interested in our product . thanks a lot! Our Website:http:// www.prs-123.com/ Msn: prs_cool_123 at hotmail.com mail: prs_cool_123 at yahoo.com.cn thanks for everyone good luck with everyone @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ hello: madam and sir . we sell all kinds of laptops and digital cam .our product is a quantity best, the price is the lowest in the world, i think you will be interested in our product . thanks a lot! Our Website:http:// www.prs-123.com/ Msn: prs_cool_123 at hotmail.com mail: prs_cool_123 at yahoo.com.cn thanks for everyone good luck with everyone . @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ hello : madam and sir. we sell all kinds of laptops and digital cam .our product is a quantity best, the price is the lowest in the world, i think you will be interested in our product . thanks a lot! Our Website:http:// www.prs-123.com/ Msn: prs_cool_123 at hotmail.com mail: prs_cool_123 at yahoo.com.cn thanks for everyone good luck with everyone hello: madam and sir . we sell all kinds of laptops and digital cam .our product is a quantity best, the price is the lowest in the world, i think you will be interested in our product . thanks a lot! Our Website:http://www.prs-123.com/ Msn: prs_cool_123 at hotmail.com mail: prs_cool_123 at yahoo.com.cn thanks for everyone good luck with everyone . @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ hello : madam and sir. we sell all kinds of laptops and digital cam .our product is a quantity best, the price is the lowest in the world, i think you will be interested in our product . thanks a lot! Our Website:http:// www.prs-123.com/ Msn: prs_cool_123 at hotmail.com mail: prs_cool_123 at yahoo.com.cn thanks for everyone good luck with everyone @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ hello: madam and sir . we sell all kinds of laptops and digital cam .our product is a quantity best, the price is the lowest in the world, i think you will be interested in our product . thanks a lot! Our Website:http:// www.prs-123.com/ Msn: prs_cool_123 at hotmail.com mail: prs_cool_123 at yahoo.com.cn thanks for everyone good luck with everyone . @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ hello : madam and sir. we sell all kinds of laptops and digital cam .our product is a quantity best, the price is the lowest in the world, i think you will be interested in our product . thanks a lot! Our Website:http:// www.prs-123.com/ Msn: prs_cool_123 at hotmail.com mail: prs_cool_123 at yahoo.com.cn thanks for everyone good luck with everyone hello: madam and sir . we sell all kinds of laptops and digital cam .our product is a quantity best, the price is the lowest in the world, i think you will be interested in our product . thanks a lot! Our Website:http://www.prs-123.com/ Msn: prs_cool_123 at hotmail.com mail: prs_cool_123 at yahoo.com.cn thanks for everyone good luck with everyone . @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ hello : madam and sir. we sell all kinds of laptops and digital cam .our product is a quantity best, the price is the lowest in the world, i think you will be interested in our product . thanks a lot! Our Website:http:// www.prs-123.com/ Msn: prs_cool_123 at hotmail.com mail: prs_cool_123 at yahoo.com.cn thanks for everyone good luck with everyone @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ hello: madam and sir . we sell all kinds of laptops and digital cam .our product is a quantity best, the price is the lowest in the world, i think you will be interested in our product . thanks a lot! Our Website:http:// www.prs-123.com/ Msn: prs_cool_123 at hotmail.com mail: prs_cool_123 at yahoo.com.cn thanks for everyone good luck with everyone . @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ hello : madam and sir. we sell all kinds of laptops and digital cam .our product is a quantity best, the price is the lowest in the world, i think you will be interested in our product . thanks a lot! Our Website:http:// www.prs-123.com/ Msn: prs_cool_123 at hotmail.com mail: prs_cool_123 at yahoo.com.cn thanks for everyone good luck with everyone hello: madam and sir . we sell all kinds of laptops and digital cam .our product is a quantity best, the price is the lowest in the world, i think you will be interested in our product . thanks a lot! Our Website:http://www.prs-123.com/ Msn: prs_cool_123 at hotmail.com mail: prs_cool_123 at yahoo.com.cn thanks for everyone good luck with everyone . @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ hello : madam and sir. we sell all kinds of laptops and digital cam .our product is a quantity best, the price is the lowest in the world, i think you will be interested in our product . thanks a lot! Our Website:http:// www.prs-123.com/ Msn: prs_cool_123 at hotmail.com mail: prs_cool_123 at yahoo.com.cn thanks for everyone good luck with everyone @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ hello: madam and sir . we sell all kinds of laptops and digital cam .our product is a quantity best, the price is the lowest in the world, i think you will be interested in our product . thanks a lot! Our Website:http:// www.prs-123.com/ Msn: prs_cool_123 at hotmail.com mail: prs_cool_123 at yahoo.com.cn thanks for everyone good luck with everyone . @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ hello : madam and sir. we sell all kinds of laptops and digital cam .our product is a quantity best, the price is the lowest in the world, i think you will be interested in our product . thanks a lot! Our Website:http:// www.prs-123.com/ Msn: prs_cool_123 at hotmail.com mail: prs_cool_123 at yahoo.com.cn thanks for everyone good luck with everyone hello: madam and sir . we sell all kinds of laptops and digital cam .our product is a quantity best, the price is the lowest in the world, i think you will be interested in our product . thanks a lot! Our Website:http://www.prs-123.com/ Msn: prs_cool_123 at hotmail.com mail: prs_cool_123 at yahoo.com.cn thanks for everyone good luck with everyone . @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ hello : madam and sir. we sell all kinds of laptops and digital cam .our product is a quantity best, the price is the lowest in the world, i think you will be interested in our product . thanks a lot! Our Website:http:// www.prs-123.com/ Msn: prs_cool_123 at hotmail.com mail: prs_cool_123 at yahoo.com.cn thanks for everyone good luck with everyone @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ hello: madam and sir . we sell all kinds of laptops and digital cam .our product is a quantity best, the price is the lowest in the world, i think you will be interested in our product . thanks a lot! Our Website:http:// www.prs-123.com/ Msn: prs_cool_123 at hotmail.com mail: prs_cool_123 at yahoo.com.cn thanks for everyone good luck with everyone . @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ hello : madam and sir. we sell all kinds of laptops and digital cam .our product is a quantity best, the price is the lowest in the world, i think you will be interested in our product . thanks a lot! Our Website:http:// www.prs-123.com/ Msn: prs_cool_123 at hotmail.com mail: prs_cool_123 at yahoo.com.cn thanks for everyone good luck with everyone hello: madam and sir . we sell all kinds of laptops and digital cam .our product is a quantity best, the price is the lowest in the world, i think you will be interested in our product . thanks a lot! Our Website:http://www.prs-123.com/ Msn: prs_cool_123 at hotmail.com mail: prs_cool_123 at yahoo.com.cn thanks for everyone good luck with everyone . @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ hello : madam and sir. we sell all kinds of laptops and digital cam .our product is a quantity best, the price is the lowest in the world, i think you will be interested in our product . thanks a lot! Our Website:http:// www.prs-123.com/ Msn: prs_cool_123 at hotmail.com mail: prs_cool_123 at yahoo.com.cn thanks for everyone good luck with everyone @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ hello: madam and sir . we sell all kinds of laptops and digital cam .our product is a quantity best, the price is the lowest in the world, i think you will be interested in our product . thanks a lot! Our Website:http:// www.prs-123.com/ Msn: prs_cool_123 at hotmail.com mail: prs_cool_123 at yahoo.com.cn thanks for everyone good luck with everyone . @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ hello : madam and sir. we sell all kinds of laptops and digital cam .our product is a quantity best, the price is the lowest in the world, i think you will be interested in our product . thanks a lot! Our Website:http:// www.prs-123.com/ Msn: prs_cool_123 at hotmail.com mail: prs_cool_123 at yahoo.com.cn thanks for everyone good luck with everyone hello: madam and sir . we sell all kinds of laptops and digital cam .our product is a quantity best, the price is the lowest in the world, i think you will be interested in our product . thanks a lot! Our Website:http://www.prs-123.com/ Msn: prs_cool_123 at hotmail.com mail: prs_cool_123 at yahoo.com.cn thanks for everyone good luck with everyone . @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ hello : madam and sir. we sell all kinds of laptops and digital cam .our product is a quantity best, the price is the lowest in the world, i think you will be interested in our product . thanks a lot! Our Website:http:// www.prs-123.com/ Msn: prs_cool_123 at hotmail.com mail: prs_cool_123 at yahoo.com.cn thanks for everyone good luck with everyone @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ hello: madam and sir . we sell all kinds of laptops and digital cam .our product is a quantity best, the price is the lowest in the world, i think you will be interested in our product . thanks a lot! Our Website:http:// www.prs-123.com/ Msn: prs_cool_123 at hotmail.com mail: prs_cool_123 at yahoo.com.cn thanks for everyone good luck with everyone . @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ hello : madam and sir. we sell all kinds of laptops and digital cam .our product is a quantity best, the price is the lowest in the world, i think you will be interested in our product . thanks a lot! Our Website:http:// www.prs-123.com/ Msn: prs_cool_123 at hotmail.com mail: prs_cool_123 at yahoo.com.cn thanks for everyone good luck with everyone From carlistixx at gmail.com Sun Jun 3 20:55:18 2007 From: carlistixx at gmail.com (carlistixx) Date: Mon, 4 Jun 2007 10:55:18 +1000 Subject: Roundup, smtplib, TLS and MS Exchange In-Reply-To: <465fedcd$0$323$e4fe514c@news.xs4all.nl> References: <465fedcd$0$323$e4fe514c@news.xs4all.nl> Message-ID: <40170aa80706031755w3cfe4ef5taa0bfb63a09d67cb@mail.gmail.com> Thanks for your response. I tried modifying the Roundup code as suggested: class SMTPConnection(smtplib.SMTP): ''' Open an SMTP connection to the mailhost specified in the config ''' def __init__(self, config): smtplib.SMTP.__init__(self, config.MAILHOST) self.set_debuglevel(1) # start the TLS if requested if config["MAIL_TLS"]: self.ehlo() self.starttls(config["MAIL_TLS_KEYFILE"], config["MAIL_TLS_CERTFILE"]) self.ehlo() # ok, now do we also need to log in? mailuser = config["MAIL_USERNAME"] if mailuser: self.login(mailuser, config["MAIL_PASSWORD"]) I've inserted a call to ehlo() before and after the call to starttls(). Adding the first call to ehlo() does help - I don't get so many complaints from the server. But it still doesn't work- it seems like the server stops responding after the call to starttls(). I have not specified a keyfile or certfile in the Roundup configuration, but as I understand it these are optional, so I presume this is not causing the problem. [foobar at moe tracker]$ roundup-server -p 8081 roundup=/home/foobar/roundup/tracker Roundup server started on :8081 send: 'ehlo moe.foobar.local\r\n' reply: '250-smtpx15.msoutlookonline.net Hello [202.173.131.223]\r\n' reply: '250-SIZE 31457280\r\n' reply: '250-PIPELINING\r\n' reply: '250-ENHANCEDSTATUSCODES\r\n' reply: '250-STARTTLS\r\n' reply: '250-AUTH LOGIN\r\n' reply: '250-8BITMIME\r\n' reply: '250-BINARYMIME\r\n' reply: '250 CHUNKING\r\n' reply: retcode (250); Msg: smtpx15.msoutlookonline.net Hello [202.173.131.223] SIZE 31457280 PIPELINING ENHANCEDSTATUSCODES STARTTLS AUTH LOGIN 8BITMIME BINARYMIME CHUNKING send: 'STARTTLS\r\n' reply: '220 2.0.0 SMTP server ready\r\n' reply: retcode (220); Msg: 2.0.0 SMTP server ready send: 'ehlo moe.foobar.local\r\n' send: 'ehlo moe.foobar.local\r\n' reply: '250-smtpx15.msoutlookonline.net Hello [202.173.131.223]\r\n' reply: '250-SIZE 31457280\r\n' reply: '250-PIPELINING\r\n' reply: '250-ENHANCEDSTATUSCODES\r\n' reply: '250-STARTTLS\r\n' reply: '250-AUTH LOGIN\r\n' reply: '250-8BITMIME\r\n' reply: '250-BINARYMIME\r\n' reply: '250 CHUNKING\r\n' reply: retcode (250); Msg: smtpx15.msoutlookonline.net Hello [202.173.131.223] SIZE 31457280 PIPELINING ENHANCEDSTATUSCODES STARTTLS AUTH LOGIN 8BITMIME BINARYMIME CHUNKING send: 'STARTTLS\r\n' reply: '220 2.0.0 SMTP server ready\r\n' reply: retcode (220); Msg: 2.0.0 SMTP server ready send: 'ehlo moe.foobar.local\r\n' 192.168.100.68 - - [04/Jun/2007 10:43:24] "POST /roundup/issue1638 HTTP/1.1" 400 - EXCEPTION AT Mon Jun 4 10:43:24 2007 Traceback (most recent call last): File "/usr/lib/python2.3/site-packages/roundup/scripts/roundup_server.py", line 106, in run_cgi self.inner_run_cgi() File "/usr/lib/python2.3/site-packages/roundup/scripts/roundup_server.py", line 266, in inner_run_cgi tracker.Client(tracker, self, env).main() File "/usr/lib/python2.3/site-packages/roundup/cgi/client.py", line 196, in main self.inner_main() File "/usr/lib/python2.3/site-packages/roundup/cgi/client.py", line 314, in inner_main self.mailer.exception_message() File "/usr/lib/python2.3/site-packages/roundup/mailer.py", line 153, in exception_message self.standard_message(to, subject, content) File "/usr/lib/python2.3/site-packages/roundup/mailer.py", line 93, in standard_message self.smtp_send(to, message) File "/usr/lib/python2.3/site-packages/roundup/mailer.py", line 173, in smtp_send smtp = SMTPConnection(self.config) File "/usr/lib/python2.3/site-packages/roundup/mailer.py", line 194, in __init__ self.ehlo() File "/usr/lib/python2.3/smtplib.py", line 390, in ehlo (code,msg)=self.getreply() File "/usr/lib/python2.3/smtplib.py", line 344, in getreply line = self.file.readline() File "/usr/lib/python2.3/smtplib.py", line 159, in readline chr = self.sslobj.read(1) sslerror: The read operation timed out On 6/1/07, Tijs wrote: > carlistixx wrote: > > > [foobar at moe tracker]$ roundup-server -p 8081 > > roundup=/home/foobar/roundup/tracker > > Roundup server started on :8081 > > send: 'STARTTLS\r\n' > > reply: '503 5.5.2 Send hello first\r\n' > > reply: retcode (503); Msg: 5.5.2 Send hello first > > I think this must be an issue with roundup, issuing commands in the wrong > order. The correct order should (according to the rfc and the python docs) > be: > * ehlo() > * starttls() > * ehlo() > * login() > ... > > -- > > Regards, > Tijs > -- > http://mail.python.org/mailman/listinfo/python-list > From grante at visi.com Fri Jun 1 00:55:14 2007 From: grante at visi.com (Grant Edwards) Date: Fri, 01 Jun 2007 04:55:14 -0000 Subject: c[:]() References: <1180504190.055427.173610@h2g2000hsg.googlegroups.com> <1180554872.3356.30.camel@dot.uniqsys.com> <465DF3DE.40404@cc.umanitoba.ca> <1180566831.239580.199300@m36g2000hse.googlegroups.com> <005401c7a31a$136f7fe0$240110ac@Muse> <135tobve86qj808@corp.supernews.com> <135tru124pie2b3@corp.supernews.com> <135tv1bjqgbmsc9@corp.supernews.com> Message-ID: <135v9liaoqgcf83@corp.supernews.com> On 2007-06-01, Warren Stringer wrote: > As mentioned a while back, I'm now predisposed towards using > `do(c)()` because square brackets are hard with cell phones. Yet you insist on adding gratuitous instances of [:] in your code. Methinks you're being disingenuous. > The one mitigating factor for more general use, outside of > cell phones, is speed. If a PEP enables a much faster solution > with c[selector()]() then it may be worthwhile. But, I feel a > bit circumspect about suggesting a change as I haven't looked > at Python source, nor have I looked at the BNF, lately. I > think Martelli's recent post on implantation may be relevant: > >> Tuples are implemented as compact arrays of >> pointer-to-PyObject (so are lists, BTW). So, for example, a >> 10-items tuple takes 40 bytes (plus a small overhead for the >> header) on a 32-bit build, not 80 as it would if implemented >> as a linked list of (pointer-to-object, pointer-to-next) >> pairs; addressing sometuple[N] is O(1), NOT O(N); etc, etc. > > The questions about implementing a working c[:]() are: Again, _why_ the [:] ??? > 1) Does it break anything? Not if you do it in a class of your own. > 2) Does it slow anything down? > 3) Could it speed anything up? > 4) Does it make code easier to read? > 5) What question(s) did I forget to ask? > > 1) No? The fact that c() currently fails on a container > implies that enabling it would not break existing client > code. No, it doesn't. I can think of several cases where somebody might depend on the fact that lists and tuples are not callable. It's quite common in Python to write a function that accepts a variety of argument types (e.g. accepting either a file object or a file name). It's not unimaginable that somebody might write a fuction that will accept either a function or a list and expect that a list isn't callable. [Please quit saying "a container" if you mean lists and tuples. "A container" is way too general. There most probably _are_ containers for which c() does not fail.] > Would this break the language definition? That depends on what you mean by "a container". If it's a container class that you or somebody else wrote, then no, it doesn't break the language definition. If you mean the builtin list or tuple types, then yes, it breaks the language definition because the language is currently defined such that lists and tuples aren't callable. > A couple years ago, I hand transcribed the BNF of version 2.2 > to an alternative to BNF. I would love to know if c[:]() would > break the BNF in a fundamental way. No, the syntax is fine. It's just that the containers you seem to have chosen don't do what you want. For pete's sake, use one that does. > 2) I don't know. I've always assumed that Python objects are > hash table entries. How would this change? Would it change? > Does the message "TypeError: 'list' object is not callable" > guarantee a short path between bytecode and hash table? Is > there some other mitigating factor? I don't see why you think this has to be built into the language when it would only take a few lines of code to define such a class. IIRC, somebody already has. Your problem has been solved for you. The whole point of having user-defined classes/types is so that the language doesn't have to have built-in every conceivable data type and behavior that anybody will ever want. >> So if you think `c()` and `c[:]()` should do something >> different in this case, you are profoundly confused about >> Python's semantics of what objects are, what it means to >> shallow copy a list, and what it means to make a function >> call. That you keep including the slice suggests that there's >> something about its meaning that's not yet clicking. > > I use `c[:]()` because it is unambiguous about using a > container That makes no sense. >> If you really want syntax where a function call on a container >> calls all of its elements, then that is trivially easy to do >> by creating such an object and overriding its `__call__` >> method. >> >> If you're not willing to do that, but still insisting that >> `c[:]()` makes sense, then perhaps it would be more advisable >> to learn more about Python rather than try to suggest profound >> changes to the language and its conventions. > > You're right. At the same time, version 3 is coming up soon. > There is a short window of opportunity for profound changes. > > Also, my audacious suggestion The suggestion that containers broadcast a "call" operation isn't audacious. It's not going to happen, but there's nothing wrong with the suggestion. You just choose to write a lot of audacious nonsense along with it. -- Grant Edwards grante Yow! Someone is DROOLING at on my collar!! visi.com From borud-news at borud.no Wed Jun 20 10:39:13 2007 From: borud-news at borud.no (Bjorn Borud) Date: 20 Jun 2007 16:39:13 +0200 Subject: The Modernization of Emacs References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182344981.372713.298580@w5g2000hsg.googlegroups.com> Message-ID: [Kaldrenon ] | Just so everyone's clear: | | Nothing he has said makes much sense, if any. (it'd be good if you explicitly specify who "he" is since pronouns by nature are extremely context sensitive, and in this context an unattentive reader might think you are referring to me. thanks :-). | Emacs' uniqueness may hurt its adoption rate, but it still has plenty | of users, who are all perfectly happy with how things are done. I don't see popularity as a goal in itself. I am selfish. I only care what the software can do for me and I think that this is the only way to write good software: make something you'd want to use yourself. -Bj?rn From kf9150 at gmail.com Fri Jun 22 12:47:06 2007 From: kf9150 at gmail.com (kf9150 at gmail.com) Date: Fri, 22 Jun 2007 09:47:06 -0700 Subject: sqlite newbie question - how to know if a table exists? In-Reply-To: <5e1lapF36b36fU1@mid.uni-berlin.de> References: <1182498744.922560.320760@a26g2000pre.googlegroups.com> <5e1lapF36b36fU1@mid.uni-berlin.de> Message-ID: <1182530826.418609.18850@q19g2000prn.googlegroups.com> On Jun 22, 12:07 am, Gerhard H?ring wrote: > That approach is ok. If your SQLite library is recent enough (I don't > know the exact version), you can use "create table if not exists ...". > > -- Gerhard Thanks Gerhard. I'm using sqlite3 that came with Python2.5 installation. So "create table if not exists" works. From steven.bethard at gmail.com Fri Jun 1 19:27:10 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Fri, 01 Jun 2007 17:27:10 -0600 Subject: Observer-Pattern by (simple) decorator In-Reply-To: References: Message-ID: Wildemar Wildenburger wrote: > I thought: I'll just write a decorator that lets me react to method > calls easily (the ever so popular observer-pattern). I've looked at some > recepies, but I just don't get them (I'm feeling kinda dumb today, sorry). [snip] > This is more complicated than expected mainly for two reasons: > > * I can't find a way to pass the proper 'instance' argument to > callback, that is, I don't know how to retrieve the instance that > meth() was called on, because the observable decorator only gets > the *function* object but not the *method*. (I hope this was clear > enough) > * Also, I don't see how I could add the add_callback() method to the > meth object. That doesn't seem possible. I can add it to meth's > function object just fine in the definition of observable, but I > thats not what I really want. This is probably just a cosmetic > issue because I don't like the idea of calling > sa.meth.im_func.add_callback(callback). I think you want to define __get__ on your Observable class so that it can do the right thing when the method is bound to the instance: >>> class Observable(object): ... def __init__(self, func, instance=None, observers=None): ... if observers is None: ... observers = [] ... self.func = func ... self.instance = instance ... self.observers = observers ... def __get__(self, obj, cls=None): ... if obj is None: ... return self ... else: ... func = self.func.__get__(obj, cls) ... return Observable(func, obj, self.observers) ... def __call__(self, *args, **kwargs): ... result = self.func(*args, **kwargs) ... for observer in self.observers: ... observer(self.instance) ... return result ... def add_callback(self, callback): ... self.observers.append(callback) ... >>> class SomeActor(object): ... @Observable ... def meth(self, foo): ... print foo ... >>> def callback(instance): ... print "Yippie, I've been called on", instance ... instance.bar = True ... >>> sa = SomeActor() >>> sa.meth.add_callback(callback) >>> sa.meth("I'm the boring old argument") I'm the boring old argument Yippie, I've been called on <__main__.SomeActor object at 0x00E7A4D0> >>> sa.bar True STeVe From jstroud at mbi.ucla.edu Sun Jun 24 15:29:16 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sun, 24 Jun 2007 12:29:16 -0700 Subject: Accessing variable from a function within a function In-Reply-To: References: Message-ID: Nathan Harmston wrote: > Hi, > > I m playing around with extended euclids algorithm from Knuth. I m > trying to build a function with a function inside it. > > def exteuclid(m,n): > a,a1,b,b1,c,d = 0,1,1,0,m,n > def euclid(c,d): > q = c /d > r = c % d > if r == 0: > print a,b > return d > else: > print a1,a,b1,b,c,d,q,r > t = b1 > b = t - q * b > a = t - q * a > c,d,a1,b1 = d,r,a,b > return euclid(c,d) > return euclid(c,d) > > Unfortunately this doesnt work since a,a1,b,b1 arent declared in the > function. Is there a way to make these variables accessible to the > euclid function. Or is there a better way to design this function? > > Many Thanks in advance, > > Nathan That last return statement does not match indentation of another block. But this is probably what you mean: def exteuclid(m,n): x = 0,1,1,0,m,n def euclid(c,d,x=x): a,a1,b,b1,c,d = x q = c /d r = c % d if r == 0: print a,b return d else: print a1,a,b1,b,c,d,q,r t = b1 b = t - q * b a = t - q * a c,d,a1,b1 = d,r,a,b return euclid(c,d) return euclid(c,d) James From kyosohma at gmail.com Wed Jun 20 14:41:18 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Wed, 20 Jun 2007 11:41:18 -0700 Subject: visual gui ides for python/jythpn In-Reply-To: <1182363400.993370.109800@k79g2000hse.googlegroups.com> References: <1182363400.993370.109800@k79g2000hse.googlegroups.com> Message-ID: <1182364878.904133.160560@p77g2000hsh.googlegroups.com> On Jun 20, 1:16 pm, kromakey wrote: > Hi, > > Are there any free visual GUI IDE's available for python/jython, which > have a drag and drop form designer similar to Visual Studio or > Delphi ? > > Cheers > kromakey I think Boa Contructor and wxGlade do that for the wxPython GUI toolkit: http://boa-constructor.sourceforge.net/ http://wxglade.sourceforge.net/ XRCed kind of does this as well: http://xrced.sourceforge.net/ Dabo: http://dabodev.com wxGlade and XRCed are included in SPE - http://pythonide.blogspot.com/ Mike From josiah.carlson at sbcglobal.net Sat Jun 9 16:05:05 2007 From: josiah.carlson at sbcglobal.net (Josiah Carlson) Date: Sat, 09 Jun 2007 20:05:05 GMT Subject: Python's "only one way to do it" philosophy isn't good? In-Reply-To: References: <1181368143.874341.273140@r19g2000prf.googlegroups.com> Message-ID: James Stroud wrote: > Terry Reedy wrote: >> In Python, you have a choice of recursion (normal or tail) > > Please explain this. I remember reading on this newsgroup that an > advantage of ruby (wrt python) is that ruby has tail recursion, implying > that python does not. Does python have fully optimized tail recursion as > described in the tail recursion Wikipedia entry? Under what > circumstances can one count on the python interpreter recognizing the > possibility for optimized tail recursion? Note that Terry said that you could do normal or tail recursion, he didn't claim that either were optimized. As for why tail calls are not optimized out, it was decided that being able to have the stack traces (with variable information, etc.) was more useful than offering tail call optimization (do what I say). - Josiah From antroy at gmail.com Tue Jun 19 08:32:29 2007 From: antroy at gmail.com (Ant) Date: Tue, 19 Jun 2007 05:32:29 -0700 Subject: static python classes ? In-Reply-To: <1182254405.901790.189190@p77g2000hsh.googlegroups.com> References: <1182254405.901790.189190@p77g2000hsh.googlegroups.com> Message-ID: <1182256349.390764.252640@q69g2000hsb.googlegroups.com> It's not clear what you mean here. If you mean something like static inner classes in Java, then you can simply nest classes in Python: >>> class A(object): ... class B(object): ... def aaa(self): ... print "AAAAAA" ... >>> z = A.B() >>> z.aaa() AAAAAA (In contrast the equivalent of Java's ordinary inner class: >>> class A(object): ... def __init__(self): ... class B(object): ... def aa(self): ... print "BBBB" ... self.B = B ... >>> A().B().aa() BBBB ) If you mean "static class" as in an class which only has static methods and variables, then the python equivalent is a module. > I'm new to python, and I can't seem to find in the docs how to create > the python equivalent of what's called in most OOP languages "static > classes", can you give me a hint ? Hope the above was what you are looking for. -- Ant... http://antroy.blogspot.com/ From justin.mailinglists at gmail.com Fri Jun 29 04:49:09 2007 From: justin.mailinglists at gmail.com (Justin Ezequiel) Date: Fri, 29 Jun 2007 08:49:09 -0000 Subject: Python & MySQL problem with input to table..! In-Reply-To: <1183105583.922597.72930@n2g2000hse.googlegroups.com> References: <1183105583.922597.72930@n2g2000hse.googlegroups.com> Message-ID: <1183106949.790378.309910@g37g2000prf.googlegroups.com> On Jun 29, 4:26 pm, hiroc13 wrote: > >>> import MySQLdb > >>> db = MySQLdb.connect (host = "localhost", user = "root", passwd = "pass", db = "base1") > >>> c = db.cursor () > >>> c.execute(""" INSERT INTO table1 (prvo, drugo) VALUES ('test', '1') """) > >>> c.execute("SELECT * FROM table1") > >>> res = c.fetchall () > >>> print res > > When I start this code I get ((15L, 'test', 1L),) on the screen but if > I first execute this: > > >>> import MySQLdb > >>> db = MySQLdb.connect (host = "localhost", user = "root", passwd = "pass", db = "base1") > >>> c = db.cursor () > >>> c.execute(""" INSERT INTO table1 (prvo, drugo) VALUES ('test', '1') """) > > .... this write to table1 > and now this: > > >>> Import MySQLdb > >>> db = MySQLdb.connect (host = "localhost", user = "root", passwd = "pass", db = "base1") > >>> c = db.cursor () > >>> c.execute("SELECT * FROM table1") > >>> res = c.fetchall () > >>> print res > > I get only this: "()" - the table1 is empty ... I write 10 times same > thing to table... only PRIMARY KEY is change > > WHY???? try a `db.commit()` after the INSERT From showell30 at yahoo.com Mon Jun 4 06:30:58 2007 From: showell30 at yahoo.com (Steve Howell) Date: Mon, 4 Jun 2007 03:30:58 -0700 (PDT) Subject: Python, Dutch, English, Chinese, Japanese, etc. In-Reply-To: <1180950609.696851.138410@k79g2000hse.googlegroups.com> Message-ID: <552279.3098.qm@web33508.mail.mud.yahoo.com> --- montyphyton at gmail.com wrote: > what about slavic languages? > in croatian you have five accented letters plus > three letters for > digrahps. russian, bulgarian, serbian, macedonian, > ukranian etc. use > cyrilic alphabet (lets not forget that russia isn't > that small - > around 150 million people), polish also has some of > its own > characters... > all in all, it is estimated that some 400 million > people speak slavic > languages... > Agreed, but FWIW, if you compared Slavic-writing people to Chinese-writing people, I would think that a higher percentage of Slavic-writing people would be bilingual in terms of their ability to write code in non-Slavic alphabets, due to various cultural/geographical factors. I don't predict a huge upswing in Slavic-writing Python programmers after PEP 3131, even among children. ____________________________________________________________________________________ It's here! Your new message! Get new email alerts with the free Yahoo! Toolbar. http://tools.search.yahoo.com/toolbar/features/mail/ From sergio at sergiomb.no-ip.org Mon Jun 18 15:38:18 2007 From: sergio at sergiomb.no-ip.org (Sergio Monteiro Basto) Date: Mon, 18 Jun 2007 20:38:18 +0100 Subject: HTMLParser.HTMLParseError: EOF in middle of construct Message-ID: <1182195498.16548.5.camel@localhost.localdomain> Hi, Can someone explain me, what is wrong with this site ? python linkExtractor3.py http://www.noticiasdeaveiro.pt > test HTMLParser.HTMLParseError: EOF in middle of construct, at line 1173, column 1 at line 1173 of test file is perfectly normal . I like to know what I have to clean up before parse the html page I send in attach the python code . thanks in advance -- S?rgio M. B. -------------- next part -------------- A non-text attachment was scrubbed... Name: linkExtractor3.py Type: text/x-python Size: 1407 bytes Desc: not available URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: smime.p7s Type: application/x-pkcs7-signature Size: 2192 bytes Desc: not available URL: From oscartheduck at gmail.com Fri Jun 22 15:50:12 2007 From: oscartheduck at gmail.com (James) Date: Fri, 22 Jun 2007 13:50:12 -0600 Subject: regular expression Message-ID: Hi folks, I have a little script that sits in a directory of images and, when ran, creates thumbnails of the images. It works fine if I call the function inside the program with something like "thumbnailer("jpg), but I want to use a regular expression instead of a plain string so that I can match jpeg, jpg, JPEG etc. Here's the script: --- #!/usr/bin/env python from PIL import Image import glob, os, re size = 128, 128 # takes an extension (e.g. jpg, png, gif, tiff) as argument def thumbnailer(extension): #glob the directory the script is in for files of the type foo.extension for picture in glob.glob("*." + extension): file, ext = os.path.splitext(picture) im = Image.open(picture) im.thumbnail(size, Image.ANTIALIAS) im.save(file + ".thumbnail." + extension) jpg = re.compile("jpg|jpeg", re.IGNORECASE) thumbnailer(jpg) --- And here's the error: --- Traceback (most recent call last): File "./thumbnail.py", line 19, in ? thumbnailer(jpg) File "./thumbnail.py", line 11, in thumbnailer for picture in glob.glob("*." + extension): TypeError: cannot concatenate 'str' and '_sre.SRE_Pattern' objects --- It looks to me like the conversion to a regex object instead of a plain string is screwing up the file glob + extension concatenation. Is there a simple way to accomplish what I'm trying to do here and get rid of that error? Thanks! -------------- next part -------------- An HTML attachment was scrubbed... URL: From simonkagwe at yahoo.com Mon Jun 4 11:00:20 2007 From: simonkagwe at yahoo.com (simon kagwe) Date: Mon, 4 Jun 2007 15:00:20 +0000 (UTC) Subject: Using pyTTS with other languages. References: <1180967733.566489.128430@h2g2000hsg.googlegroups.com> Message-ID: gmail.com> writes: > It describes how to use mis-spelled words to force correct > pronunciation as well as how to do it with XML. > > Mike > Thanks Mike. I had already read that article. I thought the mis-spelling and XML are meant to deal with pronunciation of English words. Will it really handle pronunciation of words of a whole new language? For example, if I want to say 'good' in Zulu, I may end up saying a word that has entirely different phenomes (and throw in some clicking sounds like in those 'God's must be crazy' movies). For my language, I have already collected recordings of its syllables and some words. I tried it out with pyTTS and it pronounces some words completely different they aren't even close to the way they should be. From rweir at ertius.org Wed Jun 27 03:05:52 2007 From: rweir at ertius.org (Rob Weir) Date: Wed, 27 Jun 2007 17:05:52 +1000 Subject: bicycle repair man help In-Reply-To: References: Message-ID: On 6/24/07, Rustom Mody wrote: > Does someone know that when using bicycle repair man to refactor python code > what exactly extract local variable means? It means extracting a part (or all of) an expression and replacing it with a sensibly-named local variable. Shamelessly copied from c2: > For example: > > if ( (x==0) || ((y<17) && name == null) ) { > .. > } > > becomes: > > final boolean outOfActiveAreal = (x==0) || ((y<17) && name == null) ; > if (outOfActiveAreal ) { > .. > } Some more articles: http://refactoring.com/catalog/introduceExplainingVariable.html and http://c2.com/cgi-bin/wiki?IntroduceExplainingVariable have discussions of them. -rob From bj_666 at gmx.net Wed Jun 27 02:46:10 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Wed, 27 Jun 2007 08:46:10 +0200 Subject: Set builtin lookups References: Message-ID: In , Evan Klitzke wrote: > I have a question about the internal representation of sets in Python. > If I write some code like > > if x in some_list: > do_something() > > the lookup for the in statement is O(n), where n is the number of > elements in the list. Is this also true if I am using a set or are > sets represented by a hash table? Sets are implemented as hash tables. Ciao, Marc 'BlackJack' Rintsch From eadmund42 at NOSPAMgmail.com Thu Jun 21 12:09:10 2007 From: eadmund42 at NOSPAMgmail.com (Robert Uhl) Date: Thu, 21 Jun 2007 10:09:10 -0600 Subject: The Modernization of Emacs: terminology buffer and keybinding References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182272495.990807.99110@a26g2000pre.googlegroups.com> <87tzt3ihev.fsf@kobe.laptop> <1182370216.961241.6960@n60g2000hse.googlegroups.com> <85zm2ufjpb.fsf@lola.goethe.zz> <1182372592.803332.288260@u2g2000hsc.googlegroups.com> <1182373919.262388.100740@c77g2000hse.googlegroups.com> <85r6o6fhkb.fsf@lola.goethe.zz> <1182375045.626510.188170@m36g2000hse.googlegroups.com> Message-ID: Twisted writes: > >> > I have that exact URL now -- >> >http://www.asktog.com/columns/027InterfacesThatKill.html >> >> Utterly unrelated to Emacs. > > I think it is quite relevant. Clunky computer interfaces may not be so > dramatically dangerous, but they certainly can hamper productivity. You're quite right. Windows/Mac user interfaces are so clunky that they massively hamper productivity. Emacs, OTOH, enables it. For example, C-s is search forward; C-r is search backward ('reverse'); C-M-s is search forward for a regular expression; C-M-r is search backward for a regular expression. A Windows or Mac editor would have C-s for save, and that's it. It might have C-f for find, but it'd pop up a dialogue instead of offering an interactive search, causing a mental context switch. Searching would interrupt one's flow of thought rather than being part of it. > Between Windows bugs and gratuitous misfeatures (e.g. DRM) and Unix > clunkiness, billions of dollars of potential productivity is lost > worldwide every *month*. You left out user refusal to learn... -- Robert Uhl If I could sum up my life in one sentence, I think it would be: He was born, he lived, and then he kept on living, much longer than anyone had ever lived before, getting richer and richer and glowing with a bright white light. --Deep Thoughts, by Jack Handey [1999] From vedrandekovic at v-programs.com Sat Jun 23 09:07:53 2007 From: vedrandekovic at v-programs.com (vedrandekovic at v-programs.com) Date: Sat, 23 Jun 2007 06:07:53 -0700 Subject: Changing the names of python keywords Message-ID: <1182604073.068301.241290@k79g2000hse.googlegroups.com> Hello, I on working on windows and Python 2.4. Where can I find and CHANGE python grammar. ( I just want to change the keywords ) PLEASE HELP ME SOMEBODY!!!!!! THANKS!!!!!!!!!!!!!!!!! From usereplyto at gmail.com Sat Jun 16 10:37:34 2007 From: usereplyto at gmail.com (Josh Hill) Date: Sat, 16 Jun 2007 10:37:34 -0400 Subject: Do U have anything to share with this students References: <1181926856.041008.258770@o11g2000prd.googlegroups.com> <1181999183.047568.44000@m36g2000hse.googlegroups.com> Message-ID: On Sat, 16 Jun 2007 13:06:23 -0000, Milt wrote: >On Jun 15, 1:00?pm, slvsl... at gmail.com wrote: >> This is a network of students. Find the people of your kind there >> >> http://tinyurl.com/33uvla >> >> Click and register to access millions of students. > >Your link doesn't work. Hope you're protected against malware. -- Josh "Paranoia results from a proper perception of the food chain." - Boots From kennerly at finegamedesign.com Fri Jun 22 02:45:55 2007 From: kennerly at finegamedesign.com (Ethan Kennerly) Date: Thu, 21 Jun 2007 23:45:55 -0700 Subject: Does altering a private member decouple the property's value? Message-ID: <20070622064605.A54481E400B@bag.python.org> Thanks for the help! Using the "class name (object)" syntax fixed my problem. Usually, I don't need properties, but in the case of a dependent attribute, I used a set method of a property to update that dependent attribute. I have a stopwatch class with a time limit property. When the time limit is changed, the dependent attribute, remaining time, should also change. I am having to unteach myself some of the defensive programming techniques in C++, such as using name mangling to ensure privacy, when privacy is not the most important criterion. For prototyping, starting public and going "private" later is more efficient when refactoring. And since properties have the same access signature as a public member, it can be done without changes to the client. -- Ethan From jeffrey.rollin at gmail.com Tue Jun 12 05:35:41 2007 From: jeffrey.rollin at gmail.com (Jeff Rollin) Date: Tue, 12 Jun 2007 10:35:41 +0100 Subject: Accessing attributes Message-ID: Hi there. I'm working with the Python Tutorial "Byte of Python" at swaroopch.info. I have created the attached file, but when I execute: % objvar.py I get the error message: (Initializing Calamity Jane) Traceback (most recent call last): File "/home/jef/bin/objvar.py", line 49, in Person.how_many() AttributeError: class Person has no attribute 'how_many' Where am I going wrong? Many TIA for any help. Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: objvar.py Type: application/x-python Size: 1402 bytes Desc: not available URL: From roberth+news at ifi.uio.no Fri Jun 15 13:09:13 2007 From: roberth+news at ifi.uio.no (Robert Bauck Hamar) Date: Fri, 15 Jun 2007 19:09:13 +0200 Subject: Re printing on same line. References: <1181920861.071568.4860@w5g2000hsg.googlegroups.com> Message-ID: Jerry Hill wrote: > On 6/15/07, HMS Surprise wrote: >> I want to print a count down timer on the same line. I tried >> >> print '\r', timeLeft, >> >> which just appends to the same line. > > Sounds to me like whatever you're printing to doesn't do what you > expect when it encounters a carriage return (\r). Is your program > running in a terminal? Both the windows cmd.exe shell and bash under > linux seem to do the right thing when encountering a '\r'. Actually, bash has nothing to do with how the terminal handles \r. The job of the shell (bash, ksh, csh, sh ...) is to execute your script when you type its name. Outputting a \r might or might not move the cursor to the beginning of the line. It's completely system specific, and even on the same OS, it depends on the capabilities of the actual terminal the programs run on, and on some terminal emulators it might depend on configuration settings. If you need to explore the capabilities of the terminal, curses will be a good place to start. -- rbh From bbxx789_05ss at yahoo.com Sat Jun 23 15:06:02 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: Sat, 23 Jun 2007 12:06:02 -0700 Subject: Collections of non-arbitrary objects ? In-Reply-To: <1182620734.940718.196520@e16g2000pri.googlegroups.com> References: <1182449993.223262.229500@z28g2000prd.googlegroups.com> <87k5twx4hf.fsf@benfinney.id.au> <1182559502.069773.321620@i38g2000prf.googlegroups.com> <87wsxvrzsj.fsf@benfinney.id.au> <1182620734.940718.196520@e16g2000pri.googlegroups.com> Message-ID: <1182625562.657089.66150@p77g2000hsh.googlegroups.com> On Jun 23, 11:45 am, walterbyrd wrote: > On Jun 22, 11:43 pm, Ben Finney > wrote: > > > Can you help us understand, by showing a use case that would in your > > estimation be improved by the feature you're describing? > > Suppose you are sequentially processing a list with a routine that > expects every item to be of a certain type. Something in the list that > doesn't conform to the type could give you unexpected results, maybe > crash your application. > if hasattr(elmt, some_func): elmt.some_func() From kevin.bell at slcgov.com Thu Jun 21 11:20:52 2007 From: kevin.bell at slcgov.com (Bell, Kevin) Date: Thu, 21 Jun 2007 09:20:52 -0600 Subject: newbie question: parsing street name from address In-Reply-To: <1182433644.485185.197690@w5g2000hsg.googlegroups.com> References: <1182433644.485185.197690@w5g2000hsg.googlegroups.com> Message-ID: <2387F0EED10A4545A840B231BBAAC722F11B56@slcimail1.slcgov.com> Look at the string.split() built-in, then you could use s.isalpha & s.isdigit to test each word... regular expressions would be the way to go, but that's a bit to chew on if you're getting started with string methods. You'll need to look at list indexing as well. Kev SLC DOT GIS -----Original Message----- From: python-list-bounces+kevin.bell=slcgov.com at python.org [mailto:python-list-bounces+kevin.bell=slcgov.com at python.org] On Behalf Of cjl Sent: Thursday, June 21, 2007 7:47 AM To: python-list at python.org Subject: newbie question: parsing street name from address P: I am working on a project that requires geocoding, and have written a very simple geocoder that uses the Google service. I would like to be able to extract the name of the street from the addresses in my data, however they vary significantly. Here a some examples: 25 Main St 2500 14th St 12 Bennet Pkwy Pearl St Bennet Rd and Main st 19th St As you can see, sometimes I have the house number, and sometimes I do not. Sometimes the street name is a number. Sometimes I simply have the names of intersecting streets. I would like to be able to parse the above into the following: Main St 14th St Bennet Pkwy Pearl St Bennet Rd Main St 19th St How might I approach this complex parsing problem? -CJL -- http://mail.python.org/mailman/listinfo/python-list From evan at yelp.com Sat Jun 16 20:38:06 2007 From: evan at yelp.com (Evan Klitzke) Date: Sat, 16 Jun 2007 17:38:06 -0700 Subject: a_list.count(a_callable) ? In-Reply-To: <1182040111.087082.222160@k79g2000hse.googlegroups.com> References: <1181850818.567840.251090@x35g2000prf.googlegroups.com> <1181853479.914070.217270@i13g2000prf.googlegroups.com> <1181855184.511137.100870@z28g2000prd.googlegroups.com> <1181916937.648267.163070@z28g2000prd.googlegroups.com> <1181981527.960296.135820@i13g2000prf.googlegroups.com> <1182026221.039617.56320@n2g2000hse.googlegroups.com> <1182040111.087082.222160@k79g2000hse.googlegroups.com> Message-ID: On 6/16/07, Dustan wrote: > On Jun 16, 3:37 pm, Dustan wrote: > > class SmartCountingList(list): > > def count(self, item, func=lambda x: x): > > return sum(1 for i in self if func(item)==item) > > > > Then, you would call it as follows: > > a_list.count(True, a_function) > > I need to learn to think things through before hitting the send button > (or test my examples); none of the mistakes I've made on this thread > have been from ignorance. > > If a_function returns a true value other than True or the number 1 > (which are technically the same), it is not 'equal' to True. Either If you're _really_ pedantic, 1 and True are _not_ the same, and this can be an important distinction in some situations. >>> 1 == True True >>> 1 is True False -- Evan Klitzke From kennerly at finegamedesign.com Sun Jun 24 03:23:55 2007 From: kennerly at finegamedesign.com (Ethan Kennerly) Date: Sun, 24 Jun 2007 00:23:55 -0700 Subject: visual gui ides for python/jythpn Message-ID: <20070624072409.E8EA11E4006@bag.python.org> Luis M. Gonzalez wrote: > PythonCard is an extremely easy to use alternative. > It's like a simplified Visual Basic or Delphi IDE. > Check IT out: www.pythoncard.org I second that! PythonCard is a rapid way to prototype an ugly Windows GUI. (It's not PythonCard's fault that Windows are ugly. ;) ) I use it for prototyping. But ONLY for prototyping. At least with my version in Windows, it's got bugs in the resource editor. For example, Korean characters in Korean fonts are rotated sideways. And the color of a font can't be changed; only the foreground color can, which corrupts button display. The send to back/front options don't seem to work. Transparent images (like PNG) don't seem to work ... for me, anway. Yet, still, when I'm rapidly developing the mechanics of a game and need a GUI front-end, PythonCard was a quick solution. It brilliantly stores the GUI as a recursive dictionary, which is like XML, only easy for a human to read. The widgets require very little of your coding. It's got a lot of samples, which makes some of its peculiar conventions easy to apply. And any Python app made with the PythonCard framework has a namespace viewer, shell, and GUI message integrated into the application. Flash and Python: The ultimate GUI prototyping combo? In my dreams, I would use Flash for the GUI portion of a Python app. Flash is by far my favorite environment for rapidly designing interfaces. It is an (almost) object-oriented drawing environment that can quickly produce good visual design. Because the elements are instances of prototypes (Flash calls them symbols), they can be easily replaced and updated at any time. The timeline, animation, color, layer, and drawing tools are wonderful. You can quickly make traditional or experimental interfaces. The only thing that sucked (for me), was ActionScript. It's not bad. It's quite good for interface scripting. But for back-end procedures it is prison compared to Python. Does anyone successfully use a Flash front-end and Python back-end in real-time? I've tried an example of XMLRPC servers where a Flash app (SWF) communicates with Python (http://www.cs.unc.edu/~parente/tech/tr01.shtml), but that has a round-trip time that is too slow for something like a videogame (updates at 30 frames per second). Some of the projects at OS flash look promising (http://osflash.org/ext_howto), but I haven't found the part that says that my interface made in Macromedia Flash (which is a fantastic design environment) can be used with my code in Python with a real-time frame rate. -- Ethan From Brettmf at gmail.com Wed Jun 13 11:23:10 2007 From: Brettmf at gmail.com (Brettmf) Date: Wed, 13 Jun 2007 08:23:10 -0700 Subject: Python Job Opportunity Message-ID: <1181748190.232970.120020@o11g2000prd.googlegroups.com> My company : EWT, LLC EWT is a proprietary securities trading company and is a member firm of major stock and futures exchanges. Founded in 2002, EWT was formed to capitalize on the shift of the securities industry towards electronic platforms in the United States and abroad. Location: Beverly Hills, CA - USA Position: We are seeking developers to work on proprietary trading strategies that will run on our high-performance, electronic trading platform. Responsibilities include improving the scalability, performance and efficiency of existing strategies. This position involves strong collaboration with traders to research and prototype new strategies. ? Candidates should have an interest in trading and financial markets ? Candidates should enjoy working in a fast-paced, dynamic environment ? Analytic ability and raw talent are required ? Strong mathematical aptitude; background in math, physics, or statistics is a plus ? Proficiency with Python is required ? Experience in distributed and/or highly concurrent systems is a plus As a highly successful firm in the finance industry, we are able to offer extremely competitive compensation, well above market value. We are always looking for people with extraordinary skills, experience, creativity and drive to join our rapidly expanding company. If this describes you, then please apply. Please email resumes to bfairclough at ewtllc.com or, preferably, apply through our website at www.ewtcareers.com (follow the Careers tab). From rene at korteklippe.de Tue Jun 12 13:20:20 2007 From: rene at korteklippe.de (=?UTF-8?B?UmVuw6kgRmxlc2NoZW5iZXJn?=) Date: Tue, 12 Jun 2007 19:20:20 +0200 Subject: Forgetting an import In-Reply-To: <1181666164.640868.225130@i38g2000prf.googlegroups.com> References: <1181666164.640868.225130@i38g2000prf.googlegroups.com> Message-ID: <466ed5d1$0$6399$9b4e6d93@newsspool2.arcor-online.net> HMS Surprise schrieb: > I imported a set of functions from a file I wrote to interpreter > shell: > > from myFile import * > > Now if I change functions in this file how can I make python forget it > so I can force a fresh import? I think you are looking for reload(). But don't forget to check its documentation, there may be some caveats. -- Ren? From steve at REMOVE.THIS.cybersource.com.au Mon Jun 11 07:56:58 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Mon, 11 Jun 2007 21:56:58 +1000 Subject: Postpone creation of attributes until needed References: <1181553891.447344.109390@g4g2000hsf.googlegroups.com> <1181559496.911368.219210@p77g2000hsh.googlegroups.com> Message-ID: On Mon, 11 Jun 2007 03:58:16 -0700, Frank Millman wrote: >> By using slots, you're telling Python not to reserve space for a __dict__, >> which means that your class cannot create attributes on the fly. >> > > I understand that. In fact I was already using slots, as I was > concerned about the number of 'column' instances that could be created > in any one program, and wanted to minimise the footprint. Unless you have thousands and thousands of instances, __slots__ is almost certainly not the answer. __slots__ is an optimization to minimize the size of each instance. The fact that it prevents the creation of new attributes is a side-effect. > I have since > read some of caveats regarding slots, but I am not doing anything out > of the ordinary so I feel comfortable with them so far. > >> > I use __slots__ to catch any invalid attributes, otherwise I would get >> > a 'maximum recursion depth exceeded' error. >> >> That's the wrong solution to that problem. To avoid that problem, >> __getattr__ should write directly to self.__dict__. >> > > Are you saying that instead of > > self.z = self.x * self.y > return getattr(self.name) > > I should have > > self.__dict__['z'] = self.x * self.y > return self.__dict__[name] > > I tried that, but I get AttributeError: 'A' object has no attribute > '__dict__'. Of course you do, because you are using __slots__ and so there is no __dict__ attribute. I really think you need to lose the __slots__. I don't see that it really gives you any advantage. > Aslo, how does this solve the problem that 'name' may not be one of > the attributes that my 'compute' method sets up. Or are you saying > that, if I fixed the previous problem, it would just raise > AttributeError anyway, which is what I would want to happen. You haven't told us what the 'compute' method is. Or if you have, I missed it. >> > Is this ok, or is there a better way? >> >> At the interactive Python prompt: >> >> help(property) >> > > See my reply to Phil - I would use property if there was only one > attribute, but there are several. Writing "several" properties isn't that big a chore, especially if they have any common code that can be factored out. Another approach might be to create a factory-function that creates the properties for you, so you just need to call it like this: class MyClass(object): x = property_maker(database1, tableX, 'x', other_args) y = property_maker(database2, tableY, 'y', other_args) # blah blah blah def property_maker(database, table, name, args): def getx(self): return getattr(database[table], name) # or whatever... def setx(self, value): setattr(database[table], name, value) return property(getx, setx, None, "Some doc string") -- Steven. From psaroudakis at gmail.com Wed Jun 27 10:28:42 2007 From: psaroudakis at gmail.com (psaroudakis) Date: Wed, 27 Jun 2007 14:28:42 -0000 Subject: sort pygtk gtktreeview column containing dates Message-ID: <1182954522.086112.9750@g4g2000hsf.googlegroups.com> Hello... I have been trying to sort a gtktreelist column that contains dates in the following format: eg: 01-Jan-1993 12-Dec-1992 etc i don't seem to be able to find any other solution than using dates in the format "YYYY-MM-DD" which is something i am trying to avoid.. Is there something very trivial that I am missing/overlooking? any suggestions? Thanks, Nik Disclaimer: I am very new to Python and Pygtk From see.signature at no.spam Wed Jun 6 09:38:53 2007 From: see.signature at no.spam (Eric Brunel) Date: Wed, 06 Jun 2007 15:38:53 +0200 Subject: Tkinter, tkMessagebox and overrideredirect References: <1181060331.167762.19180@q69g2000hsb.googlegroups.com> <1181132772.551848.192400@o5g2000hsb.googlegroups.com> Message-ID: On Wed, 06 Jun 2007 14:26:12 +0200, wrote: >> As an aside, having a window with overrideredirect(1) creating "normal" >> windows such as the one created via tkMessageBox.showinfo is asking for >> problems. What are you trying to do here? > > I just need a window without the titlebar as my main window (think of > it as a kiosk application). No titlebar is mandatory :-( > I place controls on it and I open popup dialog windows. > If there is a better way to do it, I would be happy to know it. My only advice would then be to avoid using the standard functions to create dialog boxes, and to create them yourself. For example: ---------------------------------------------------------- from Tkinter import * class App: def __init__(self): self.root = Tk() self.root.overrideredirect(1) frm = Frame(self.root, width=320, height=200, borderwidth=5, relief=RAISED) frm.pack_propagate(0) frm.pack() Button(frm, text="Quit", command=self.root.quit).pack(pady=20) Button(frm, text="Hello", command=self.hello).pack(pady=20) def hello(self): dialogWdw = Toplevel() dialogWdw.title('Popup') Label(dialogWdw, text='Hello!').pack(side=TOP) Button(dialogWdw, text='OK', command=dialogWdw.destroy).pack(side=TOP) dialogWdw.tkraise(self.root) self.root.wait_window(dialogWdw) app = App() app.root.mainloop() ---------------------------------------------------------- But even with this, you may run into problems. For example, on my Linux box with my window manager, the main window goes behind all other windows once the button in the dialog is clicked. So I'd say that if you want to bypass the window manager, bypass it for everything and do overrideredirect(1) on all the windows you create. But this means that you'll have to do everything "manually", especially window stacking. -- python -c "print ''.join([chr(154 - ord(c)) for c in 'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])" From deets at nospam.web.de Mon Jun 4 05:23:05 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 04 Jun 2007 11:23:05 +0200 Subject: magic names in python References: <1180939436.862957.127810@p77g2000hsh.googlegroups.com> <1180943167.241208.37080@q75g2000hsh.googlegroups.com> Message-ID: <5ci3vpF308r3mU1@mid.uni-berlin.de> per9000 wrote: > On Jun 4, 9:11 am, Marc 'BlackJack' Rintsch wrote: >> In <1180939436.862957.127... at p77g2000hsh.googlegroups.com>, per9000 >> wrote: >> > >> > [...] >> > >> > So another question emerges: >> > * is the use of magic names encouraged and/or part of good coding >> > practice. >> >> What do you mean by "use"? Implement them to override behavior? Yes, >> that's their purpose. Invent new magic names? No of course not, they >> are >> special for a reason: preventing name clashes with the user's names. >> > > [in my taste: UGLY] > I think of something like this: Perhaps I create a class that works > with a lot of files, and with inheritance new types of files can be > opened and worked with. > > When it is time for an instance of this class to die the files need to > be closed - perhaps "right now" and not when it is suitable for the > garbage collector. To facilitate this I create a number of functions > with names like close_*_file (f.x. close_indata_file, > close_outdata_file, close_error_file etc). (compare with [PyTest| > unittest] "test*" names.) > > If this class has been inherited to some other class that works with > more than one indata file perhaps we want to magically close all files > that are open by calling all function in this instance that has names > matching "close_*_file". > > I would consider this an ugly way of solving it. > > [in my taste: NICER] > I'd perhaps add file-handles to some list (and encourage inherited > classes to use this list) and close everything in the list. I would > not use magic wildcard names. This is a completely different topic than the usage of "magic" names in python to allow e.g. operator overloading and the like. > So in other words: Do I need to go to yellow alert, and watch out for > magic names in non-core add-on packages to python? Or should I just > RTFM a little more? (I hate RTFM'ing.) Certainly RTFM. Diez From fredrik at pythonware.com Mon Jun 11 15:23:28 2007 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 11 Jun 2007 21:23:28 +0200 Subject: REALLY need help with iterating a list. In-Reply-To: <1181588376.426556.46530@j4g2000prf.googlegroups.com> References: <1181586648.614514.228900@m36g2000hse.googlegroups.com> <1181588376.426556.46530@j4g2000prf.googlegroups.com> Message-ID: infidel wrote: > How about something like this? > > while serverlist: > server = serverlist.pop(0) > pinger = ping[server] > if pinger.returncode==None: > pinger.poll() > serverlist.append(server) > else: > pingresult[server] = pinger.stdout.read() > pingreturncode[server] = pinger.returncode > > Basic idea: as long as there are servers in the list, pop the first > one out of the list, see if it's done, and if it isn't, put it back on > the end of the list. here's a simple variation of that, which is a bit more efficient, and perhaps also a bit easier to use in the general case: while serverlist: still_active = [] for server in serverlist: pinger = ping[server] if pinger.returncode is None: pinger.poll() still_active.append(server) else: pingresult[server] = pinger.stdout.read() pingreturncode[server] = pinger.returncode serverlist = still_active From jloden at jayloden.com Mon Jun 18 13:16:57 2007 From: jloden at jayloden.com (Jay Loden) Date: Mon, 18 Jun 2007 13:16:57 -0400 Subject: Parsing HTML, extracting text and changing attributes. In-Reply-To: <4676B809.2010307@web.de> References: <1182175239.122827.4150@g4g2000hsf.googlegroups.com> <4676B809.2010307@web.de> Message-ID: <4676BE09.6050707@jayloden.com> Stefan Behnel wrote: > Jay Loden wrote: >> Someone else mentioned lxml but as I understand it lxml will only work if >> it's valid XHTML that they're working with. > > No, it was meant as the OP requested. It even has a very good parser from > broken HTML. > > http://codespeak.net/lxml/dev/parsing.html#parsing-html I stand corrected, I missed that whole part of the LXML documentation :-) From sjmachin at lexicon.net Sun Jun 10 18:10:40 2007 From: sjmachin at lexicon.net (John Machin) Date: Sun, 10 Jun 2007 15:10:40 -0700 Subject: codecs / subprocess interaction: utf help requested In-Reply-To: <1181510260.821468.151320@h2g2000hsg.googlegroups.com> References: <1181510260.821468.151320@h2g2000hsg.googlegroups.com> Message-ID: <1181513440.723767.40650@a26g2000pre.googlegroups.com> On Jun 11, 7:17 am, smitty1e wrote: > The first print statement does what you'd expect. > The second print statement has rather a lot of rat in it. > The goal here is to write a function that will return the man page for > some command (mktemp used as a short example here) as text to client > code, where the groff markup will be chopped to extract all of the > command options. Those options will eventually be used within an > emacs mode, all things going swimmingly. > I don't know what's going on with the piping in the second version. > It looks like the output of p0 gets converted to unicode at some > point, Whatever gave you that idea? > but I might be misunderstanding what's going on. The 4.8 > codecs module documentation doesn't really offer much enlightment, > nor google. About the only other place I can think to look would be > the unit test cases shipped with python. Get your head out of the red herring factory; unicode, "utf" (which one?) and codecs have nothing to do with your problem. Think about looking at your own code and at the bzip2 documentation. > Sort of hoping one of the guru-level pythonistas can point to > illumination, or write something to help out the next chap. This > might be one of those catalytic questions, the answer to which tackles > five other questions you didn't really know you had. > Thanks, > Chris > --------------------------- > #!/usr/bin/python > import subprocess > > p = subprocess.Popen(["bzip2", "-c", "-d", "/usr/share/man/man1/mktemp. > 1.bz2"] > , stdout=subprocess.PIPE) > stdout, stderr = p.communicate() > print stdout > > p0 = subprocess.Popen(["cat","/usr/share/man/man1/mktemp.1.bz2"], > stdout=subprocess.PIPE) > p1 = subprocess.Popen(["bzip2"], stdin=p0.stdout , > stdout=subprocess.PIPE) > stdout, stderr = p1.communicate() > print stdout > --------------------------- You left out the command-line options for bzip2. The "rat" that you saw was the result of compressing the already-compressed man page. Read this: http://www.bzip.org/docs.html which is a bit obscure. The --help output from my copy of an antique (2001, v1.02) bzip2 Windows port explains it plainly: """ If invoked as `bzip2', default action is to compress. as `bunzip2', default action is to decompress. as `bzcat', default action is to decompress to stdout. If no file names are given, bzip2 compresses or decompresses from standard input to standard output. """ HTH, John From john at datavoiceint.com Tue Jun 12 13:50:19 2007 From: john at datavoiceint.com (HMS Surprise) Date: Tue, 12 Jun 2007 10:50:19 -0700 Subject: List sequential initialization Message-ID: <1181670619.086709.116730@g37g2000prf.googlegroups.com> I thought if I could do this: >>> a = b = '' >>> a = 'a' >>> a 'a' >>> b '' then this would behave similarly: >>> la = lb = [] >>> la.append('a') >>> la ['a'] >>> lb ['a'] I thought wrong! But don't know why. Inquiring minds want to know..... thanx, jh From jjl at pobox.com Mon Jun 25 16:53:31 2007 From: jjl at pobox.com (John J. Lee) Date: Mon, 25 Jun 2007 20:53:31 GMT Subject: eggs considered harmful References: Message-ID: <87odj3u56c.fsf@pobox.com> Harry George writes: > Robert Kern writes: [...] > This is a possibility. The tarballs can be seen in a directory > listing. They are in different subdirs (for different "bundles" of > functionality), so I'll need -f to look several places. One possibility here is to have a script maintain symlinks (or have it otherwise appropriately configure a web server). [...] > I agree pure eggs are rare. The fact that they increased this past > quarter was what concerned me. ZODB even looks like a normal tarball, > builds ok, but uses a easy-install-style lookup during install. All setuptools-based packages work this way: they have a setup.py that (roughly) imports the setup function from setuptools rather than distutils. John From grante at visi.com Wed Jun 6 00:29:15 2007 From: grante at visi.com (Grant Edwards) Date: Wed, 06 Jun 2007 04:29:15 -0000 Subject: Who uses Python? References: <1180985830.288414.208850@q69g2000hsb.googlegroups.com> <1181103447.194971.78840@o11g2000prd.googlegroups.com> Message-ID: <136ce0rmse7alfe@corp.supernews.com> On 2007-06-06, Vijayendra Bapte wrote: > Python is a rapid application development language..we uses it > every where.. in web application development..GUI > development..Automation/Regression test-suite > development..Text/XML processing..website Scrapping Boy, do I know some web sites that need to be scrapped. ;) -- Grant Edwards grante Yow! Am I accompanied by at a PARENT or GUARDIAN? visi.com From esj at harvee.org Sun Jun 10 10:07:54 2007 From: esj at harvee.org (Eric S. Johansson) Date: Sun, 10 Jun 2007 10:07:54 -0400 Subject: Python in the Mozilla world Message-ID: this morning I was looking at Python and XUL. I was impressed by the very interesting projects that were happening around 2005 but it seems like they have all died. Integrating Python at the Mozilla was also very intriguing as it held the promise of eliminating JavaScript for extension development (yaaa). But that seems to have died as well. In fact, it looks like that almost all of the alternative languages for browsers have died for lack of interest or something. I was really looking forward to pyax As a result, I started looking at Python generating JavaScript and I know there is pypy but is that really something one can count on or is it more a good demonstration of technology? Just wondering. From x31equsenet at gmail.com Sun Jun 24 22:35:09 2007 From: x31equsenet at gmail.com (Graham Breed) Date: Sun, 24 Jun 2007 19:35:09 -0700 Subject: Python's "only one way to do it" philosophy isn't good? References: <7x3b0nmkk6.fsf@ruckus.brouhaha.com> Message-ID: <1182738909.918893.92220@m37g2000prh.googlegroups.com> Steven D'Aprano wote: > But if you really want declarations, you can have them. > > >>> import variables > >>> variables.declare(x=1, y=2.5, z=[1, 2, 4]) > >>> variables.x = None > >>> variables.w = 0 > Traceback (most recent call last): > File "", line 1, in > File "variables.py", line 15, in __setattr__ > raise self.DeclarationError("Variable '%s' not declared" % name) > variables.DeclarationError: Variable 'w' not declared Another way is to decorate functions with their local variables: >>> from strict import my >>> @my("item") ... def f(x=1, y=2.5, z=[1,2,4]): ... x = float(x) ... w = float(y) ... return [item+x-y for item in z] ... Traceback (most recent call last): File "", line 2, in File "strict.py", line 11, in dec raise DeclarationError("No slot for %s"%varname) strict.DeclarationError: No slot for w and the implementation import re class DeclarationError(TypeError): pass def my(slots=""): tokens = slots.split() def dec(func): code = func.func_code for varname in code.co_varnames[code.co_argcount:]: if re.match('\w+$', varname) and varname not in tokens: raise DeclarationError("No slot for %s"%varname) return func return dec The best way to catch false rebindings is to stick a comment with the word "rebound" after every statement where you think you're rebinding a variable. Then you can search your code for cases where there's a "rebound" comment but no rebinding. Assuming you're the kind of person who knows that false rebindings can lead to perplexing bugs, but doesn't check apparent rebindings in a paranoid way every time a perplexing bug comes up, anyway. (They aren't that common in modern python code, after all.) And that you remembered to add the comments (like you would have remembered the let and set). And you're also the kind of person who's troubled by perplexing bugs but doesn't run a fully fledged lint. Maybe that's the kind of person who wouldn't put up with anything short of a macro as in the original proposal. All I know is that it's the kind of person I don't want to second guess. Graham From zapman449 at gmail.com Mon Jun 25 11:13:32 2007 From: zapman449 at gmail.com (Jason Zapman II) Date: Mon, 25 Jun 2007 08:13:32 -0700 Subject: How to save initial configuration? (program installation) In-Reply-To: <1182784231.530101.258640@q75g2000hsh.googlegroups.com> References: <1182783746.718276.209460@w5g2000hsg.googlegroups.com> <1182784231.530101.258640@q75g2000hsh.googlegroups.com> Message-ID: <1182784412.829377.265320@q75g2000hsh.googlegroups.com> On Jun 25, 11:10 am, kyoso... at gmail.com wrote: > I would think you could pop-up some dialog when the program is first > run to ask where they want the file to be. On the first run though, > you can just have the config file located in the current working > directory with the script file itself. Then just move it or save a new > copy to the new location and delete the original. The 'pop-up' is easy. The problem is how does the program know where it's state file is the SECOND time it is run? I can't stash it in the state file, since the program won't know where it is if it's not in the CWD... (unless I'm missing something obvious). From rohitsethidce at gmail.com Sat Jun 2 11:08:20 2007 From: rohitsethidce at gmail.com (rohit) Date: Sat, 02 Jun 2007 08:08:20 -0700 Subject: monitoring the filesystem for changes Message-ID: <1180796900.356829.31050@i13g2000prf.googlegroups.com> hello, i have designed a desktop search utility in python and a file system monitoring using readdirectorychangesw from win32api but for eg. it has a high cpu utilization (using a 2GHz processor). a solution ntfs change journal proposed here works only for ntfs partitions is there another low (processor) cost alternative that works on fat32 partitions as well. Rohit From DustanGroups at gmail.com Thu Jun 14 17:06:24 2007 From: DustanGroups at gmail.com (Dustan) Date: Thu, 14 Jun 2007 21:06:24 -0000 Subject: a_list.count(a_callable) ? In-Reply-To: <1181853479.914070.217270@i13g2000prf.googlegroups.com> References: <1181850818.567840.251090@x35g2000prf.googlegroups.com> <1181853479.914070.217270@i13g2000prf.googlegroups.com> Message-ID: <1181855184.511137.100870@z28g2000prd.googlegroups.com> On Jun 14, 3:37 pm, Dustan wrote: > Which can then be converted into a generator expression (round > brackets instead of square brackets) to avoid the intermediate list: > len((i for i in a_list if a_callable(i))) Sorry for the excess of posts everybody. I just realized that the generator expression would not work. I'm not sure how else could be implemented efficiently and without using up memory besides by accumulating the count as your earlier example shows. From S.Mientki-nospam at mailbox.kun.nl Wed Jun 27 17:12:26 2007 From: S.Mientki-nospam at mailbox.kun.nl (Stef Mientki) Date: Wed, 27 Jun 2007 23:12:26 +0200 Subject: listing the type of an object Message-ID: <71af3$4682d18c$d443bb3a$9028@news.speedlinq.nl> How can I list a type of an object instance ? I tried: class tLED (tDevice): def some_proc(self): print 'type(self)', type(self) But i gives me: type(self) Moreover, I want even the type to be listed by it's ancestor, like this class tDevice: def some_other_proc: print 'type(self)', type(self) thanks, Stef Mientki From kyosohma at gmail.com Mon Jun 25 10:43:56 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Mon, 25 Jun 2007 07:43:56 -0700 Subject: Capturing and sending keys {Esperanto} In-Reply-To: References: Message-ID: <1182782636.006761.44400@g4g2000hsf.googlegroups.com> On Jun 25, 8:26 am, AJK wrote: > Hello there! > > I've been googleing yet, and suppose it's hopeless to try, but better ask it... > > I want to write a program which turns Cx to ?, cx to ? et al WHILE > TYPING. (i.e. converting Esperanto x-system to real hats, for those > who know about this.) Therefore I though will need to capture the last > 2 typed characters (from any application), send a double backspace and > after that send the correct letters (back to the same application)... > > However, it seems inpossible to capture those letters, and maybe to > send them too... > > Or am I wrong? > > Greetings, > > LaPingvino > > (project:http://code.google.com/p/iksilo/- SVN Repository is free > viewable, project is GPL) > > -- > ?ar Dio tiel amis la mondon, ke Li donis Sian solenaskitan Filon, por > ke ?iu, kiu fidas al li, ne pereu, sed havu eternan vivon. > -Johano 3:16, La sankta Biblio- > > ?oju ?iam, pre?u sen?ese, pri ?io donu dankon. > -1 Tesalonikanoj 5:16-18a, La sankta Biblio- I just thought of something. Look for real time spell checkers! I found this one: http://ponderer.org/cvs/index.pl/javascript/spell.py Even if you can't find one in Python, you can probably translate to the snake. Mike From showell30 at yahoo.com Thu Jun 7 19:02:26 2007 From: showell30 at yahoo.com (Steve Howell) Date: Thu, 7 Jun 2007 16:02:26 -0700 (PDT) Subject: Bragging about Python In-Reply-To: <1181255542.549027.164730@p47g2000hsd.googlegroups.com> Message-ID: <165026.51779.qm@web33510.mail.mud.yahoo.com> --- Szabolcs Nagy wrote: > > actually i don't like when a tutorial uses over > complicated cute names > if the context is obvious (fibonacci) then we don't > need to add > 'parent_rabbits' and such identifiers I still prefer the use of "rabbits," but I don't mind if people change that, as I understand the brevity argument. ____________________________________________________________________________________ Pinpoint customers who are looking for what you sell. http://searchmarketing.yahoo.com/ From nagle at animats.com Wed Jun 27 12:21:10 2007 From: nagle at animats.com (John Nagle) Date: Wed, 27 Jun 2007 09:21:10 -0700 Subject: PEP 3107 and stronger typing (note: probably a newbie question) In-Reply-To: <46824d8d$0$2324$426a74cc@news.free.fr> References: <1182369568.941307.316260@p77g2000hsh.googlegroups.com> <5dveb4F360un0U1@mid.individual.net> <467a9209$0$22165$426a74cc@news.free.fr> <1182858785.886469.93060@n60g2000hse.googlegroups.com> <46824d8d$0$2324$426a74cc@news.free.fr> Message-ID: Bruno Desthuilliers wrote: > harri a ?crit : > Indeed - static typing is for compilers, not for programmers. Actually, static typing is for detecting errors before the program is run. John Nagle From nano at nano.ono Fri Jun 15 17:46:20 2007 From: nano at nano.ono (nano) Date: Fri, 15 Jun 2007 14:46:20 -0700 Subject: Get the current date, python 2.2 References: Message-ID: In article , rtw at freenet.co.uk says... > On Fri, 15 Jun 2007 14:30:36 -0700, nano wrote: > > > Using python 2.2 what is the simplest way to get the current date value? > > I have looked in so many places. The question is often asked and the > > usual response indicates how to get the current date and time like > > > > now = time.localtime() > > > > I want just the date, like 2007-06-15. The value will go into a > > postgresql Date type column. > > >>> import datetime > >>> d = datetime.date.today() > >>> d.isoformat() > '2007-06-15' > >>> > > Rob. > Thanks, I'd read that today() was only good for 2.3? From kelvin.you at gmail.com Wed Jun 6 02:40:38 2007 From: kelvin.you at gmail.com (=?utf-8?B?5Lq66KiA6JC95pel5piv5aSp5rav77yM5pyb5p6B5aSp5rav5LiN6KeB5a62?=) Date: Wed, 06 Jun 2007 06:40:38 -0000 Subject: Does unicode() equal to unicode(sys.getfilesystemencoding()) ? Message-ID: <1181112038.934840.158590@q19g2000prn.googlegroups.com> The follow statement comes from the Python 2.5 documentation -------------- encode( [encoding[,errors]]) Return an encoded version of the string. Default encoding is the current default string encoding. errors may be given to set a different error handling scheme. --------------- what's the "Default encoding" mean ? Does it equal to the sys.getfilesystemencoding()? If yes, but : >>>unicode('??', sys.getfilesystemencoding()) u'\u4e2d\u56fd' >>>unicode('??') Traceback (most recent call last): File "", line 1, in UnicodeDecodeError: 'ascii' codec can't decode byte 0xd6 in position 0: ordinal not in range(128) It seems the "Default encoding" is not equal to the sys.getfilesystemencoding(). And then, what is it ? From rbell01824 at earthlink.net Mon Jun 4 11:12:46 2007 From: rbell01824 at earthlink.net (puff) Date: Mon, 04 Jun 2007 15:12:46 -0000 Subject: pychecker Message-ID: <1180969966.644186.119100@p47g2000hsd.googlegroups.com> I'm new to pychecker. Some of my code generates the following No class attribute (HWND) found While HWND is not an attribute of the class, it IS an attribute of the instance created (my class is one of several classes used to create the new class). Can I use __pychecker__ to selectively supress this message? How? From hanser at club-internet.fr Sat Jun 16 12:20:05 2007 From: hanser at club-internet.fr (Pierre Hanser) Date: Sat, 16 Jun 2007 18:20:05 +0200 Subject: PIL cutting off letters In-Reply-To: <1181934049.401650.115360@q19g2000prn.googlegroups.com> References: <1181934049.401650.115360@q19g2000prn.googlegroups.com> Message-ID: <46740d88$0$21149$7a628cd7@news.club-internet.fr> Matt Haggard a ?crit : > I'm using PIL (Python Imaging Library) to generate button images. > They consist of a left end image, a middle, repeating image and a > right side image.... anyway, that's not important > > I'm using a TTF font for the text of the button (Verdana.TTF) and it > keeps cutting the bottom part of the the g's q's and y's off. hello may be the problem is in your code, but it is also possibly in PIL which clips caracters at the top and bottom line; that's not the typographic names, but these are *font* values, not characters ones. There are fonts with caracters far higher than these conventionnal lines (try Liorah.ttf or any swashed font for exemple)! I don't remember for sure but may be there is the same problem horizontally. -- Pierre From haraldarminmassa at gmail.com Fri Jun 8 03:38:25 2007 From: haraldarminmassa at gmail.com (GHUM) Date: Fri, 08 Jun 2007 00:38:25 -0700 Subject: EuroPython: Draft program posted, today last day of early registration Message-ID: <1181288305.287941.19400@p77g2000hsh.googlegroups.com> Dear Pythonistas! On www.euroypython.org the draft program and timetable has been posted! http://www.europython.org/sections/tracks_and_talks/draft-timetable Do a click and check out the fabulous talks. Then check in, best today, the 8th of June, the last day of early bird registration. EuroPython 2007 will take place at the Reval Hotel Lietuva in Vilnius, Lithuania from Monday 9th July to Wednesday 11th July. See you there! Best wishes, Harald From grflanagan at yahoo.co.uk Thu Jun 7 08:13:17 2007 From: grflanagan at yahoo.co.uk (Gerard Flanagan) Date: Thu, 07 Jun 2007 05:13:17 -0700 Subject: howto obtain directory where current (running) py-file is placed? In-Reply-To: <1181215154.325114.318910@g4g2000hsf.googlegroups.com> References: <1181198387.952428.163120@q75g2000hsh.googlegroups.com> <1181200735.220105.19250@q69g2000hsb.googlegroups.com> <1181215154.325114.318910@g4g2000hsf.googlegroups.com> Message-ID: <1181218397.581610.84570@g4g2000hsf.googlegroups.com> On Jun 7, 1:19 pm, dmitrey wrote: > On Jun 7, 10:18 am, Gerard Flanagan wrote:> On Jun 7, 8:39 am, dmitrey wrote: > > Thank you. > And what is the simplest way (without split/join, if exist) to obtain > name of directory parent to directory my_directory_name? > > Thx, D. > >>> os.path.join(os.pardir, os.path.dirname('/a/b/c/d/e/f.log')) '/a/b/c/d/e' >>> os.path.join(os.pardir, os.path.dirname(_)) '/a/b/c/d' >>> os.path.join(os.pardir, os.path.dirname(_)) '/a/b/c' >>> os.path.join(os.pardir, os.path.dirname(_)) '/a/b' >>> os.path.join(os.pardir, os.path.dirname(_)) '/a' >>> os.path.join(os.pardir, os.path.dirname(_)) '/' >>> os.path.join(os.pardir, os.path.dirname(_)) '/' (When using the interactive interpreter, an underscore '_' means 'the previous result') HTH Gerard From vinay_sajip at yahoo.co.uk Fri Jun 8 02:57:50 2007 From: vinay_sajip at yahoo.co.uk (Vinay Sajip) Date: Thu, 07 Jun 2007 23:57:50 -0700 Subject: Sorry for the multiple posts In-Reply-To: <1181240839.314945.302160@w5g2000hsg.googlegroups.com> References: <1181226795.455934.177550@n15g2000prd.googlegroups.com> <1181240839.314945.302160@w5g2000hsg.googlegroups.com> Message-ID: <1181285870.066880.281820@q69g2000hsb.googlegroups.com> Sorry for the multiple posts. I kept getting network errors and it looked like the posts weren't getting through. Regards, Vinay From bj_666 at gmx.net Mon Jun 4 05:36:05 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Mon, 04 Jun 2007 11:36:05 +0200 Subject: int vs long References: <1180839659.196587.194200@p77g2000hsh.googlegroups.com> <7xr6otiv4l.fsf@ruckus.brouhaha.com> <1180895701.813483.326780@k79g2000hse.googlegroups.com> <7xabvgj33p.fsf@ruckus.brouhaha.com> <1hz4uas.7jeyyu192pb8tN%aleax@mac.com> Message-ID: In , Peter Otten wrote: >> Hm, my test above was from 2.5!? > > Then your installation is broken. What does > >>>> import itertools >>>> itertools > '/usr/local/lib/python2.5/lib-dynload/itertools.so'> > > print? Python 2.5 (r25:51908, Oct 6 2006, 15:22:41) [GCC 4.1.2 20060928 (prerelease) (Ubuntu 4.1.1-13ubuntu4)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import itertools >>> itertools > By the way, here's what I get if I force the wrong library upon python2.5: > > /usr/local/lib/python2.4/lib-dynload $ python2.5 > Python 2.5 (r25:51908, Oct 3 2006, 08:48:09) > [GCC 3.3.3 (SuSE Linux)] on linux2 Seems to be the same Python version, just build three days earlier and with a different GCC version. Weird. Ciao, Marc 'BlackJack' Rintsch From jUrner at arcor.de Tue Jun 5 14:48:41 2007 From: jUrner at arcor.de (=?iso-8859-1?q?J=FCrgen_Urner?=) Date: Tue, 05 Jun 2007 11:48:41 -0700 Subject: Python for embedded systems with memory constraints In-Reply-To: References: Message-ID: <1181069321.777632.55740@p47g2000hsd.googlegroups.com> Who else is using python (programmers, scientists, finance)? Me! Graduated in fine arts. Python is what I do when I am fed up with all those colors. Much easier to manufacture sense with. From soring at gmail.com Mon Jun 18 02:06:47 2007 From: soring at gmail.com (soring at gmail.com) Date: Mon, 18 Jun 2007 06:06:47 -0000 Subject: Memory problem with Python In-Reply-To: <1182138694.632692.17590@x35g2000prf.googlegroups.com> References: <1182138694.632692.17590@x35g2000prf.googlegroups.com> Message-ID: <1182146807.758384.301000@j4g2000prf.googlegroups.com> On Jun 17, 8:51 pm, Squzer Crawler wrote: > i am developing distributed environment in my college using Python. I > am using therads in client for downloading wepages. Even though i am > reusing the thread, memory usage get increased. I don know why.? I am > using BerkelyDB for URLQueue, BeautifulShop for Parsing the webpages. Isn't the increased memory resulted from storing the already processed pages? Look first at all places where your code instantiates new objects - and make sure you don't keep references to such objects that are not needed anymore. Also, reusing threads has nothing to do with saving memory - but with saving on thread creation time, if I understand your problem description. From steve at REMOVE.THIS.cybersource.com.au Mon Jun 18 19:40:03 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Tue, 19 Jun 2007 09:40:03 +1000 Subject: Making static dicts? References: Message-ID: On Mon, 18 Jun 2007 21:46:23 +0100, Ognjen Bezanov wrote: > Hello! > > Just to ask, is it possible to make a static dictionary in python. So > that the keys in the dictionary cannot be removed, changed or new ones > added, but the value pairs can. > > Is this possible with python? I'm sure it is possible, but you'll have to program it yourself. The usual term for what you are describing is "immutable" rather than static. For some ways of making an immutable class, see here: http://northernplanets.blogspot.com/2007/01/immutable-instances-in-python.html To get the dictionary behaviour, the easiest ways would be either to sub-class from dict: class ImmutableDict(dict): pass or perhaps use delegation (google on "Python automatic delegation" for more information). You might like to look at the source code for the UserDict module in the standard library for some ideas (especially the DictMixin class). I leave putting these pieces together into a working immutable dictionary up to you. Good luck! -- Steven. From jeffrey.rollin at gmail.com Tue Jun 12 06:10:01 2007 From: jeffrey.rollin at gmail.com (Jeff Rollin) Date: Tue, 12 Jun 2007 11:10:01 +0100 Subject: Accessing attributes References: <466e70da$0$6400$9b4e6d93@newsspool2.arcor-online.net> Message-ID: In the last episode, on Tuesday 26 Sivan 5767 11:09, Marc Christiansen wrote: > > The indentation of __del__, say_hi and how_many is wrong. You define > them inside __init__. Move them to the same indentation level as > __init__ and all should work. Thanks very much. Jeff From nospam at nowhere.com Tue Jun 26 07:06:13 2007 From: nospam at nowhere.com (DavidM) Date: 26 Jun 2007 23:06:13 +1200 Subject: simplifying algebraic expressions References: <46805dae$1@news.orcon.net.nz> Message-ID: <4680f325@news.orcon.net.nz> On Tue, 26 Jun 2007 11:11:39 +0100, Robin Becker wrote: > I have seen this sort of evolution strategy in the past and it's very wrong to > attempt to simplify outside the genetic framework. The implication is that you > know better than the overall fitness requirement. The additional expressions and > redundancies allow for extra mutation and combination possibilities which is a > good thing for the whole population. If you must, add the requirement to the > target ie give extra fitness points to organisms which perform efficiently. I'm sorry, but there's something important I forgot to mention - I only want to do the simplification *after* a winning successful organism has evolved and satisfied the fitness function. From cor at clsnet.nl Sat Jun 23 08:10:01 2007 From: cor at clsnet.nl (Cor Gest) Date: 23 Jun 2007 12:10:01 +0000 Subject: The Modernization of Emacs: terminology buffer and keybinding References: <1182272495.990807.99110@a26g2000pre.googlegroups.com> <87tzt3ihev.fsf@kobe.laptop> <1182370216.961241.6960@n60g2000hse.googlegroups.com> <85zm2ufjpb.fsf@lola.goethe.zz> <1182372592.803332.288260@u2g2000hsc.googlegroups.com> <1182549094.366282.286740@m37g2000prh.googlegroups.com> <87bqf7fwmg.fsf@telesippa.clsnet.nl> <1182553682.197778.138500@g37g2000prf.googlegroups.com> <877ipvfswe.fsf@telesippa.clsnet.nl> Message-ID: <87bqf6c1nq.fsf@telesippa.clsnet.nl> Some entity, AKA Tim Roberts , wrote this mindboggling stuff: (selectively-snipped-or-not-p) > Boys, do you really not understand that this is a religious issue? You > can't use arguments and logic to convince someone to convert their > religion, and you can't use arguments and logic to convince someone to > change editors. Nah, nothing beats a nice flame-war on a slow fridaynight & a Pint of Bitter, while it spares the fingers to keep on manipulating all those nice keyboard-modifiers to nag the ignorati for an other day ... ;-) Cor -- (defvar MyComputer '((OS . "GNU/Emacs") (IPL . "GNU/Linux"))) The biggest problem LISP has, is that it does not appeal to dumb people If that fails to satisfy read the HyperSpec, woman frig or Tuxoharata mailpolicy @ http://www.clsnet.nl/mail.php From kay.schluehr at gmx.net Tue Jun 12 10:46:23 2007 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Tue, 12 Jun 2007 07:46:23 -0700 Subject: Convert String to Int and Arithmetic In-Reply-To: <1181658761.300066.118210@a26g2000pre.googlegroups.com> References: <1181658761.300066.118210@a26g2000pre.googlegroups.com> Message-ID: <1181659583.424110.194340@r19g2000prf.googlegroups.com> On 12 Jun., 16:32, tereglow wrote: > Hello, > > I am a complete newbie to Python and am accustomed to coding in PHP/ > Perl/Shell. I am trying to do the following: > > I have a string: > > cpuSpeed = 'Speed: 1000000000' > > What I would like to do is extract the '1000000000' from the string, > and divide that by 1000 twice to get the speed of a processor in MHz. > > My understanding is that I need to 'import re' and then use re.split > to get the first part done. It shall suffice to use string methods in this case: >>> int(cpuSpeed.split(":")[1].strip()) 1000000000 Finally you might trim the numerical value by division just as you wish. From josiah.carlson at sbcglobal.net Wed Jun 6 12:34:05 2007 From: josiah.carlson at sbcglobal.net (Josiah Carlson) Date: Wed, 06 Jun 2007 16:34:05 GMT Subject: who know? In-Reply-To: References: Message-ID: <1mB9i.32238$Um6.18362@newssvr12.news.prodigy.net> Michel Claveau wrote: > Hi! > > This image show IronPython. > But... what is it? > > Link : > http://msdn2.microsoft.com/en-us/vstudio/bb510103.vss_IronPython_large.jpg What is generally referred to as "Python", available from python.org, is really the 'CPython' runtime and associated libraries. It implements the Python runtime using C. There is also Jython, which uses a Python -> Java compiler on roughly Python 2.2 compatible source. There is also PyPy, which implements the Python runtime in Python with various backends (LLVM -> GCC, etc.). Finally, IronPython is an implementation of Python using Microsoft's .NET common language runtime (the CLR), which allows for Python to gain access to everything available in .NET . - Josiah From reedobrien at gmail.com Sat Jun 2 18:46:30 2007 From: reedobrien at gmail.com (reed) Date: Sat, 02 Jun 2007 22:46:30 -0000 Subject: Python Pop Quiz In-Reply-To: <1180751587.951837.191480@h2g2000hsg.googlegroups.com> References: <1180751587.951837.191480@h2g2000hsg.googlegroups.com> Message-ID: <1180824390.712329.162870@u30g2000hsc.googlegroups.com> On Jun 1, 10:33 pm, snor... at hotmail.com wrote: > 1. Do you like Python? 0 > 2. Do you think Python is good? 0 > 3. Do you think Python is real good? 0 > 4. What is your favorite version of Python? 2.4+ > 5. Because of Python, do you think it will be easier to take over the > world? If so, when? If not, when? from future import __all__ print "done" > 7. How many Z80 assembly language programmers does it take to equal > one Python guru? from z80 import guru > Essay: "C++ is better than C", agree or disagree? (four word maximum) sigh > Bonus: A rabbi walks into a bar while nursing a baby goat. He is > closely followed by a priest, and a Perl hacker. Explain. $_ From tjreedy at udel.edu Thu Jun 21 20:29:51 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 21 Jun 2007 20:29:51 -0400 Subject: Python's "only one way to do it" philosophy isn't good? References: <1181368143.874341.273140@r19g2000prf.googlegroups.com><7x3b0nmkk6.fsf@ruckus.brouhaha.com> Message-ID: "Douglas Alan" wrote in message news:lcfy4ljej2.fsf at gaffa.mit.edu... | > But why is the ability to abstract syntax good? | | It allows the community to develop language features in a modular way | without having to sully the code base for the language itself. Anyone can write modules, experimental or otherwise, without touching the code base for any particular implementation. For those whose know one of the implementation languages, source code control systems allow one to do experiments on branches without 'sullying' the trunk or impeding the development thereof. There are a least a few experimental branches, and branches of branches, in the main CPython repository and an unknown number of independent branches out in the community for either production use or for developing features aimed back at the core. One of the goals of the PyPy project was to allow people to experiment with syntax extensions in Python itself. (But I don't know how easy that is yet.) But I think that overall the problem of designing new syntax is more in the design than the implementation. Anything new has to be usable, readable, not clash too much with existing style, not introduce ambiguities, and not move the extended language outside the LL(1) [I believe that is right] subset of CFLs. tjr From gur.tom at gmail.com Tue Jun 19 03:41:35 2007 From: gur.tom at gmail.com (Tom Gur) Date: Tue, 19 Jun 2007 07:41:35 -0000 Subject: Rotating a picture Message-ID: <1182238895.646197.270090@k79g2000hse.googlegroups.com> Hi, I'm trying to build a small spaceship battle game as an exercise, using pygame. How can I rotate the gif file of my ship by X degrees ? From robin at reportlab.com Thu Jun 28 09:35:37 2007 From: robin at reportlab.com (Robin Becker) Date: Thu, 28 Jun 2007 14:35:37 +0100 Subject: 16bit hash In-Reply-To: References: <46833DC0.3050503@v.loewis.de> Message-ID: <4683B929.2080303@chamonix.reportlab.co.uk> Thomas Jollans wrote: > Robin Becker wrote: ....... >> I'm not sure my postscript is really good enough to do the latter so I >> hoped to pursue a python based approach which has a low probability of >> busting. Originally I thought the range was a 16bit number which is why >> I started with 16bit hashes. > > > For identifying something, I suggest you use a hash function like sha1 > truncating it to as much as you can use, similarly to what Jon Ribbens > suggested. that is in fact what I'm doing; my function looks like this 4000000+(reduce(operator.xor,struct.unpack('i'*4,md5.md5(s).digest()))&0x3ffff) whether it's any better than using the lowest bits I have no real idea. I suppose (sha being flavour of the month) I should really use 4000000+(reduce(operator.xor,struct.unpack('i'*5,sha.sha(s).digest()))&0x3ffff) -- Robin Becker From bjourne at gmail.com Fri Jun 15 14:06:00 2007 From: bjourne at gmail.com (=?ISO-8859-1?Q?BJ=F6rn_Lindqvist?=) Date: Fri, 15 Jun 2007 20:06:00 +0200 Subject: a_list.count(a_callable) ? In-Reply-To: <1181916937.648267.163070@z28g2000prd.googlegroups.com> References: <1181850818.567840.251090@x35g2000prf.googlegroups.com> <1181853479.914070.217270@i13g2000prf.googlegroups.com> <1181855184.511137.100870@z28g2000prd.googlegroups.com> <1181916937.648267.163070@z28g2000prd.googlegroups.com> Message-ID: <740c3aec0706151106v1017d4e2t9937177b5801c3b9@mail.gmail.com> On 6/15/07, Ping wrote: > > > > sum(1 for i in a_list if a_callable(i)) > > > > -- > > Carsten Haesehttp://informixdb.sourceforge.net > > This works nicely but not very intuitive or readable to me. > > First of all, the generator expression makes sense only to > trained eyes. Secondly, using sum(1 ...) to mean count() > isn't very intuitive either. > > I would still prefer an expression like a_list.count(a_callable), > which is short, clean, and easy to understand. :) However, > it does produce ambiguities if a_list is a list of callables. > Should the count() method match values or check return values > of a_callable? There are several possible designs but I'm not > sure which is better. Maybe you could extend count() analogous to how sort() works: # L is a list of Person objects, each Person has a name attribute L.sort(key = attrgetter("name")) # How many olle are there? print L.count("olle", key = attrgetter("name")) # And index could be extended in the same way! # Whom has id 1234? print L.index(1234, key = attrgetter("id")).name All of these could be solved by giving Person an __eq__() method, but it fails when you need to search, sort or count on a different key. -- mvh Bj?rn From josiah.carlson at sbcglobal.net Wed Jun 27 12:07:11 2007 From: josiah.carlson at sbcglobal.net (Josiah Carlson) Date: Wed, 27 Jun 2007 16:07:11 GMT Subject: 16bit hash In-Reply-To: References: Message-ID: Robin Becker wrote: > Is the any way to get an efficient 16bit hash in python? hash(obj)&65535 - Josiah From duncan.booth at invalid.invalid Fri Jun 1 08:13:42 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 1 Jun 2007 12:13:42 GMT Subject: c[:]() References: Message-ID: Steve Holden wrote: >> Actually you can copy and paste from a Windows cmd/command shell: >> right-click the title-bar of the window, select "Edit" from the pop-up >> menu, then "Mark" from the sub-menu to copy whatever you want to select >> into the Windows clipboard. >> >> HTH, > > Better still, modify your shortcut by bring up the command window's > Properties page and setting "Quick Edit Mode". Then you can select with > the mouse and hit Enter to copy. > Even better use regedit to set key HKEY_CURRENT_USER\Console, value QuickEdit to 1. Then you have copy and paste enabled for all console windows by default. From deets at nospam.web.de Fri Jun 1 08:08:36 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 01 Jun 2007 14:08:36 +0200 Subject: subexpressions References: Message-ID: <5cagi4F2vbf43U1@mid.uni-berlin.de> Steve Howell wrote: > --- Sergey Dorofeev wrote: >> > What syntax would you suggest for a lambda >> enhanced to cover your use >> > case? >> > I suppose you will end up with roughly the same >> number of characters, all >> > crammed in one line -- or broken into lines at a >> random position as it >> > happens with overambitious list comprehensions. >> >> Agree, this argument is strong. >> > > FWIW there's the possibility that even without a > subexpression syntax, some Python implementations > would detect the duplication of x*x and optimize that > for you. It would have to know that x*x had no side > effects, which I think is a safe assumption even in a > dynamic language like Python. Of course it's not. You can create arbitrarily overloaded __mul__-operators here. Unless you can guarantee that the objects in question are immutable (which you can only for python-builtins), you can't be sure that there are no sideeffects. And the needed guarding statements for this kind of optimization might well eat up the gain from not multiplying two numbers together. Diez From flebber.crue at gmail.com Sun Jun 10 06:08:02 2007 From: flebber.crue at gmail.com (flebber) Date: Sun, 10 Jun 2007 10:08:02 -0000 Subject: read xml file from compressed file using gzip In-Reply-To: <466BC7CC.1080709@lexicon.net> References: <1181278784.312152.99910@r19g2000prf.googlegroups.com> <466AE729.8070602@web.de> <1181452004.347078.241840@q19g2000prn.googlegroups.com> <466BC7CC.1080709@lexicon.net> Message-ID: <1181470082.977493.62960@a26g2000pre.googlegroups.com> On Jun 10, 7:43 pm, John Machin wrote: > On 10/06/2007 3:06 PM, flebber wrote: > > > > > On Jun 10, 3:45 am, Stefan Behnel wrote: > >> flebber wrote: > >>> I was working at creating a simple program that would read the content > >>> of a playlist file( in this case *.k3b") and write it out . the > >>> compressed "*.k3b" file has two file and the one I was trying to read > >>> was maindata.xml > >> The k3b format is a ZIP archive. Use the zipfile library: > > >> file:///usr/share/doc/python2.5-doc/html/lib/module-zipfile.html > > >> Stefan > > > Thanks for all the help, have been using the docs at python.org and > > the magnus t Hetland book. Is there any docs tha re a little more > > practical or expressive as most of the module documentation is very > > confusing for a beginner and doesn't provide much in the way of > > examples on how to use the modules. > > > Not criticizing the docs as they are probably very good for > > experienced programmers. > > Somebody else has already drawn your attention to the/a tutorial. You > need to read, understand, and work through a *good* introductory book or > tutorial before jumping into the deep end. > > > class GzipFile([playlist_file[decompress[9, 'rb']]]); > > Errr, no, the [] are a documentation device used in most computer > language documentation to denote optional elements -- you don't type > them into your program. See below. > > Secondly as Stefan pointed out, your file is a ZIP file (not a gzipped > file), they're quite different animals, so you need the zipfile module, > not the gzip module. > > > os.system(open("/home/flebber/tmp/maindata.xml")); > > The manuals say quite simply and clearly that: > open() returns a file object > os.system's arg is a string (a command, like "grep -i fubar *.pl") > So that's guaranteed not to work. > > From the docs of the zipfile module: > """ > class ZipFile( file[, mode[, compression[, allowZip64]]]) > > Open a ZIP file, where file can be either a path to a file (a string) or > a file-like object. The mode parameter should be 'r' to read an existing > file, 'w' to truncate and write a new file, > or 'a' to append to an existing file. > """ > ... and you don't care about the rest of the class docs in your simple > case of reading. > > A class has to be called like a function to give you an object which is > an instance of that class. You need only the first argument; the second > has about a 99.999% chance of defaulting to 'r' if omitted, but we'll > play it safe and explicit: > > import zipfile > zf = zipfile.ZipFile('/home/flebber/oddalt.k3b', 'r') > > OK, some more useful docs: > """ > namelist( ) > Return a list of archive members by name. > printdir( ) > Print a table of contents for the archive to sys.stdout. > read( name) > Return the bytes of the file in the archive. The archive must be > open for read or append. > """ > > So give the following a try: > > print zf.namelist() > zf.printdir() > xml_string = zf.read('maindata.xml') > zf.close() > > # xml_string will be a string which may or may not have line endings in > it ... > print len(xml_string) > > # If you can't imagine what the next two lines will do, > # you'll have to do it once, just to see what happens: > for line in xml_string: > print line > > # Wasn't that fun? How big was that file? Now do this: > lines = xml_text.splitlines() > print len(lines) # number of lines > print len(lines[0]) # length of first line > > # Ummm, maybe if it's only one line you don't want to do this either, > # but what the heck: > for line in lines: > print line > > HTH, > John Thanks that was so helpful to see how to do it. I have read a lot but it wasn't sinking in, and sometimes its better to learn by doing. Some of the books I have read just seem to go from theory to theory with the occasional example ( which is meant to show us how good the author is rather than help us). For the record >>> ## working on region in file /usr/tmp/python-F_C5sr.py... ['mimetype', 'maindata.xml'] File Name Modified Size mimetype 2007-05-27 20:36:20 17 maindata.xml 2007-05-27 20:36:20 10795 >>> print len(xml_string) 10795 >>> for line in xml_string: print line ... ... < ? x m l v e r s i.....(etc ...it went for a while) and >>> lines = xml_string.splitlines() >>> print len(lines) 387 >>> print len(lines[0]) 38 >>> for line in lines: ... print line File "", line 2 print line ^ IndentationError: expected an indented block >>> for line in lines: print line From devicerandom at gmail.com Thu Jun 28 09:07:48 2007 From: devicerandom at gmail.com (massimo s.) Date: Thu, 28 Jun 2007 06:07:48 -0700 Subject: problem with hack using multiple inheritance for plugins In-Reply-To: <1183034478.587345.214570@w5g2000hsg.googlegroups.com> References: <1183026288.857294.91620@q69g2000hsb.googlegroups.com> <1183028051.940679.145680@q69g2000hsb.googlegroups.com> <46839f4c$0$22380$426a74cc@news.free.fr> <1183034478.587345.214570@w5g2000hsg.googlegroups.com> Message-ID: <1183036068.348031.240690@n60g2000hse.googlegroups.com> On 28 Giu, 14:41, "massimo s." wrote: > The new-style behaviour only appears when wxFrame is plugged with the > current hack. > That is: > > - print type(self) in wxFrame alone returns > - print type(self) in the plugged (multiply inherited) wxFrame returns > < class '__main__.MainWindowPlugged'> > > So the problem is that I acquire a new style behaviour somewhere! Forget this one, it is wrong (Don't know how did I obtain it). I rechecked and, yes, problem is that cmd.Cmd is old-style (and the plugin hack works) while wxFrame is new style (and the plugin hack works no more). Again: using a new-style plugin class for multiple inheritance does not work. What can I do now? From squabbit8 at gmail.com Fri Jun 29 21:33:17 2007 From: squabbit8 at gmail.com (felix seltzer) Date: Fri, 29 Jun 2007 19:33:17 -0600 Subject: HTML Render Support in PyGTK In-Reply-To: <200706292250.32997.thomas@jollans.com> References: <1ef9860e0706291305x4c1de081p508d1edba9a8f981@mail.gmail.com> <200706292250.32997.thomas@jollans.com> Message-ID: http://directory.fsf.org/webauth/htmlpreproc/gtkhtml.html might help. just like thomas though... more info on what your doing/have done would help us help you On 6/29/07, Thomas Jollans wrote: > > There was no need to re-ask so soon. > > On Friday 29 June 2007, senthil arasu wrote: > > Hi, > > I am trying to render HTML in PyGTK widget but iam not getting the > expected > ^^^^^^ > What have you tried so far ? > > result. > > I would like to know whether PyGTK supports HTML rendering feature or > not. > > I believe GTK+2 has an HTML renderer, I don't know whether it's included > in > PyGTK by default etc. > > -- > Regards, Thomas Jollans > GPG key: 0xF421434B may be found on various keyservers, eg pgp.mit.edu > Hacker key : > v4sw6+8Yhw4/5ln3pr5Ock2ma2u7Lw2Nl7Di2e2t3/4TMb6HOPTen5/6g5OPa1XsMr9p-7/-6 > > -- > http://mail.python.org/mailman/listinfo/python-list > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From no-sp at m-from.net Wed Jun 6 08:03:00 2007 From: no-sp at m-from.net (Giuseppe Di Martino) Date: Wed, 06 Jun 2007 14:03:00 +0200 Subject: PATH or PYTHONPATH under Windows ??? References: <90155$4665db45$d443bb3a$16812@news.speedlinq.nl> <5339c$466685ea$83aef404$30848@news1.tudelft.nl> Message-ID: Il Wed, 06 Jun 2007 12:01:13 +0200, stef ha scritto: >> > I ran your program but it didn't solve the problem (running Python, > embedded in Delphi). > I'm beginning to get the feeling that Python installation is a very > complex case. > Anyway thanks. > In the original post you don't mention "embedded in Delphi" ! This is a different thing, the problem is that your Delphi's app relies on a Python installation in the system and, insteed, it shoud have on its own copy of Python, avoiding any problems. Giuseppe From kirby.urner at gmail.com Sun Jun 10 15:54:20 2007 From: kirby.urner at gmail.com (kirby urner) Date: Sun, 10 Jun 2007 12:54:20 -0700 Subject: New mailing list mirrors In-Reply-To: <1181486678.120099.35880@n4g2000hsb.googlegroups.com> References: <1181486678.120099.35880@n4g2000hsb.googlegroups.com> Message-ID: Thanks tomer, I joined both through Google. Kirby "moe" Urner 4dsolutions.net/ocn/cp4e.html myspace.com/4dstudios urnerk at python.org (moe rhymes with Minister of Education was my thinking -- a portfolio I sometimes grab for a gig, but always put back where I found it). On 6/10/07, sebulba wrote: > Hi all, > > I created two new google groups to mirror the activity of python-dev > and python-3000: > * http://groups.google.com/group/python-3000 > * http://groups.google.com/group/python-dev2 > > There are many mirrors out there, but none of them lets you post > to a thread. With google groups you can just hit "reply" on the > message you want to reply to, and that's it. No need to send an > email to the group (although you still need to register your email > with python mailing list). > > Supports searching, tree-view, list-view, fixed/proportional font, > tracking > of read/unread messages, etc. Enjoy. > > > -tomer > > -- > http://mail.python.org/mailman/listinfo/python-announce-list > > Support the Python Software Foundation: > http://www.python.org/psf/donations.html > From michele.simionato at gmail.com Sat Jun 23 10:13:35 2007 From: michele.simionato at gmail.com (Michele Simionato) Date: Sat, 23 Jun 2007 14:13:35 -0000 Subject: Python's "only one way to do it" philosophy isn't good? In-Reply-To: References: <1181368143.874341.273140@r19g2000prf.googlegroups.com> <7x3b0nmkk6.fsf@ruckus.brouhaha.com> Message-ID: <1182608015.004758.49060@w5g2000hsg.googlegroups.com> On Jun 22, 8:09 pm, Douglas Alan wrote: > Functionality is no good if it's too cumbersome to use. For instance, > Scheme gives you first class continuations, which Python doesn't. > Continuations let you do *all sorts* of interesting things that you > just cannot do in Python. Like backtracking, for instance. (Well > maybe you could do backtracking in Python with lots of putting code > into strings and liberal use of eval, for all I know, but the results > would almost certainly be too much of a bear to actually use.) > > Now, continuations, by themselves, in Scheme actually don't buy you > very much, because although they let you do some crazy powerful > things, making use of them to do so, is too confusing and verbose. In > order to actually use this very cool functionality, you need macros so > that you can wrap a pretty and easy-to-use face on top of all the > delicious continuation goodness. > > You'll, just have to trust me on this one. I've written code with > continuations, and I just couldn't make heads or tails out of the code > a few hours later. But when prettied-up with a nice macro layer, they > can be a joy to behold. Been there, done that. So what? Your example will not convince any Pythonista. The Pythonista expects Guido to do the language job and the application developer to do the application job. Consider for instance generators. In Python they are already implemented in the core language and the application developer does not care at all about implementing them. In Scheme I am supposed to implement them myself with continuations, but why should I do that, except as a learning exercise? It is much better if competent people are in charge of the very low level stuff and give me just the high level tools. I essentially view macros are low- level performance hacks, useful for language developers more than for application developers. BTW, there are already Python-like languages with macros (i.e. logix) and still nobody use them, including people with a Scheme/Lisp background. That should be telling you something. Michele Simionato From JoeSalmeri at hotmail.com Fri Jun 1 13:18:59 2007 From: JoeSalmeri at hotmail.com (Joe Salmeri) Date: Fri, 1 Jun 2007 13:18:59 -0400 Subject: Python 2.5.1 broken os.stat module References: <1180648618.295955.68600@x35g2000prf.googlegroups.com><465fa702$0$2944$9b622d9e@news.freenet.de> Message-ID: Hi Terry, > If, when discussion is concluded here, you still think there is a bug, > file > a report on SF. Make a concise summary in the comments section and attach > a file with the output from your experiments. You may have to submit the > attachment separately after first submitting the report. I have submitted the bug report and test script to SF. I purposely used the Python\lib directory for my test so that anyone could run the test and get the results. > Keep in mind that all the 'you's who might fix this are volunteers just > like you.r Understood, that's why I went to such great time and effort to create the scripts which demonstrate the problem. I'd fix it if I could but think that it would be better for the person that made the change in os.stat for Python 2.5.1 since they would be much more aware of the extent of that change. From max at alcyone.com Mon Jun 4 04:49:31 2007 From: max at alcyone.com (Erik Max Francis) Date: Mon, 04 Jun 2007 01:49:31 -0700 Subject: subexpressions (OT: math) In-Reply-To: References: <4662675b$1_5@news.bluewin.ch> <1180890214.317409.85100@w5g2000hsg.googlegroups.com> <1180894045.538031.111610@g4g2000hsf.googlegroups.com> <1180895200.108582.313010@k79g2000hse.googlegroups.com> Message-ID: Wildemar Wildenburger wrote: > So in each term of the sum you have a derivative of f, which in the > case of the sine function translates to sine and cosine functions at the > point 0. It's not like you're rid of the function just by doing a > polynomial expansion. The only way to *solve* this is to forbid x from > having a dimension. At least *I* see no other way. Do you? That was precisely his point. The Maclaurin series (not MacLaurin) only makes any sense if the independent variable is dimensionless. And thus, by implication, so it is also the case for the original function. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM, Y!M erikmaxfrancis The time to repair the roof is when the sun is shining. -- John F. Kennedy From ralmeida at gmail.com Fri Jun 22 11:11:50 2007 From: ralmeida at gmail.com (Rob De Almeida) Date: Fri, 22 Jun 2007 08:11:50 -0700 Subject: What was that web interaction library called again? In-Reply-To: <1182521949.813529.75140@w5g2000hsg.googlegroups.com> References: <1182521949.813529.75140@w5g2000hsg.googlegroups.com> Message-ID: <1182525110.547508.275900@n2g2000hse.googlegroups.com> On Jun 22, 11:19 am, Harald Korneliussen wrote: > Hi, > > I remember I came across a python library that made it radically > simple to interact with web sites, connecting to gmail and logging in > with four or five lines, for example. I thought, "that's interesting, > I must look into it sometime". Now there's this child I know who asked > me about programming, especially programs that could do things like > this, how difficult it was, and so on. I mentioned how I though Python > was a good intro to programming, and there was a library which was > perfect for what he wanted. httplib2? From steven.robbins at gmail.com Mon Jun 18 06:52:54 2007 From: steven.robbins at gmail.com (Stevo) Date: Mon, 18 Jun 2007 10:52:54 -0000 Subject: Using a web service [newbie] In-Reply-To: <1182160515.533065.203530@n60g2000hse.googlegroups.com> References: <1182160515.533065.203530@n60g2000hse.googlegroups.com> Message-ID: <1182163974.096010.60440@n15g2000prd.googlegroups.com> On Jun 18, 7:55 pm, Alchemist wrote: > I am working with Python 2.5 and would like to use of a web service. > > What shall I install on my setup (or import in my Python script)? > > I read about Zolera Soap Infrastructure, which seems to be the > preferred Python web service framework (http:// > pywebsvcs.sourceforge.net/). However, its documentation seems quite > old (c. 2001/2002) whilst the Babel Fish translation example (http:// > livedocs.adobe.com/coldfusion/6.1/htmldocs/webserv3.htm) did not work > for me. > > Are there any more recent frameworks or tools for using web services > by Python scripts? > > Thank you. This might be useful to you. http://www.diveintopython.org/soap_web_services/index.html From frank at chagford.com Wed Jun 13 05:15:11 2007 From: frank at chagford.com (Frank Millman) Date: Wed, 13 Jun 2007 02:15:11 -0700 Subject: Postpone creation of attributes until needed In-Reply-To: References: <1181553891.447344.109390@g4g2000hsf.googlegroups.com> <1181559496.911368.219210@p77g2000hsh.googlegroups.com> <1181564855.890242.116840@m36g2000hse.googlegroups.com> <1181626546.323759.80500@i13g2000prf.googlegroups.com> <1181663591.272374.156010@d30g2000prg.googlegroups.com> Message-ID: <1181726111.422149.89130@q19g2000prn.googlegroups.com> On Jun 13, 1:24 am, Steven D'Aprano wrote: > On Tue, 12 Jun 2007 08:53:11 -0700, Frank Millman wrote: > > Ah, if I had ever read that there were two instances involved, I hadn't > noticed. Sorry! > No problem - I really appreciate your input. I snipped the rest of your post, as I have figured out a way to make my problem go away, without changing my code radically. It was a 'sequence of events' problem. 1. create table a 2. create table b, create pseudo column on table a, link to column on table b 3. create table c, create pseudo column on table b, link to column on table c This works most times, but if, in step 2, I want to link the pseudo column in table a to the pseudo column in table b, it fails, as the pseudo column in table b does not get created until step 3. Now, if I try to link to a column that does not exist, I set a flag and carry on. When I go to the next step, after creating the pseudo column, I check if the flag exists, and if so I go back and create the link that it tried to create in the first place. It is not very pretty, but it has the big advantage that, by the time all the tables are opened, all the links are correctly set up, and I never have the problem of trying to access non-existent attributes. I will try to explain what benefit all this gives me. Assume a Customers table and an Invoices table. Customers has a primary key which is a generated 'next number', and an alternate key which is the Customer Code. Users will never see the primary key, only the alternate key. Invoices has a foreign key CustomerId, which references the primary key of Customers. However, when capturing an invoice, the user wants to enter the code, not the primary key. It is not difficult to program for this, but it is tedious to do it on every data-entry form. Therefore, in my framework, I set up a pseudo column on Invoices called CustomerCode, which the application programmer can use as if it is a real column. Behind the scenes, I automatically use that to check that it is a valid code, and populate the real column with the primary key. This has been working for some time, and really simplifies the 'business logic' side of things by abstracting a common idiom which would otherwise have to be coded explicitly every time. Now I have added a complication. I have decided to implement the idea of using a single table to store details of all parties with whom we have a relationship, such as Customers, Suppliers, Agents, etc, instead of separate tables each with their own Code, Name, and Address details. Therefore I now have the following- a Parties table with a 'next number' primary key and a PartyCode alternate key, a Customers table with a 'next number' primary key and a PartyId foreign key reference to the Parties table, and an Invoices table with a CustomerId foreign key reference to the Customers table. Now when capturing an invoice, the user enters a Code, then the program must check that the code exists on Parties, retrieve the primary key, then check that it exists on Customers, retrieve that primary key, then store the result on Invoices, with appropriate error messages if any step fails. I have successfully abstracted all of that, so all that complication is removed from the application. Hope that makes sense. Thanks very much for all your attempts to help me, Steven. You have succeeded in getting me to think properly about my problem and come up with a much cleaner solution. I really appreciate it. Frank From thorsten at thorstenkampe.de Mon Jun 4 00:03:39 2007 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Sun, 3 Jun 2007 21:03:39 -0700 Subject: *Naming Conventions* Message-ID: Okay, I hear you saying 'not another naming conventions thread'. I've read through Google and the 'naming conventions' threads were rather *spelling conventions* threads. I'm not interested in camelCase versus camel_case or anything mentioned in 'PEP 8 -- Style Guide for Python Code'. What I'm looking for is hints or ideas how to name your variables and especially how to name functions, methods and classes. I know this depends on what the function is doing. If I know what it is doing I should be able to give them a desciptive name. But actually I'm often not able. Especially when the task is quite similar to another function or Class. Recently I wrote this code and noticed that I was completely lost in giving these objects names to describe and distinguish them: for validanswer in validanswers: if myAnswers.myanswer in myAnswers.validAnswers[validanswer]: MyOptions['style'] = validanswer The 'tips' I got through some postings or articles on the net are: if a function simply tests something and returns a boolean call it def is_(): pass like 'is_even'. Makes sense. The other thing I captured was to use something like def get_values(): ... Makes sense, too, but aren't all functions getting something? So if someone had a similar dilemma to mine and could tell me how he dealt with that, I'd be grateful... Thorsten From george.sakkis at gmail.com Thu Jun 21 14:51:44 2007 From: george.sakkis at gmail.com (George Sakkis) Date: Thu, 21 Jun 2007 18:51:44 -0000 Subject: Inferring initial locals() Message-ID: <1182451904.703471.141000@n60g2000hse.googlegroups.com> I wonder if there is a (preferably not too-hackish) solution to the following introspection problem: given a callable and a number of positional and/or keyword arguments, infer what would be the frame's locals() right after the function is called. For example, given: def f(x, y=1, *a, **k): z = x + y w = len(a) - len (k) return z * w I'd like to have a function def get_init_locals(callable, *args, **kwds): # TODO pass so that: >>> get_init_locals(f, 3) {'a': (), 'k': {}, 'x': 3, 'y': 1} >>> get_init_locals(f, 3, 4, 5) {'a': (5,), 'k': {}, 'x': 3, 'y': 4} >>> get_init_locals(f, 3, q=-1) {'a': (), 'k': {'q': -1}, 'x': 3, 'y': 1} Any takers ? George From john at datavoiceint.com Tue Jun 12 14:03:18 2007 From: john at datavoiceint.com (HMS Surprise) Date: Tue, 12 Jun 2007 11:03:18 -0700 Subject: Forgetting an import In-Reply-To: <1181669413.643796.304850@x35g2000prf.googlegroups.com> References: <1181666164.640868.225130@i38g2000prf.googlegroups.com> <1181669413.643796.304850@x35g2000prf.googlegroups.com> Message-ID: <1181671398.411182.91140@i13g2000prf.googlegroups.com> Thanks for the reloads folks. This is a big help as I am running a jython based tool (maxq) and re-starting takes awhile. Can't seem to make reload work using the form "from dvTime import ...". So I am prefacing my calls with the module name now. thanx, jh From chris.arndt at web.de Mon Jun 25 14:12:34 2007 From: chris.arndt at web.de (Christopher Arndt) Date: Mon, 25 Jun 2007 11:12:34 -0700 Subject: eggs considered harmful In-Reply-To: References: Message-ID: <1182795154.631581.247410@o61g2000hsh.googlegroups.com> On 21 Jun., 14:10, Harry George wrote: > I've asked before, and I'll ask again: If you are doing a Python > project, please make a self-sufficient tarball available as well. Alomost all projects I know of that provide eggs, also have a CVS or SVN repository. Just download a tagged release and then use "python setup.py " or "easy_install ." in the checkout. easy_install can even do the checkout for you. > You can have dependencies, as long as they are documented and can be > obtained by separate manual download. Eggs document dependencies better (i.e with version numbers) than most other projects do, through the "install_requires" argument to the "setup()" call in "setup.py". In an egg, this list is found in *-egg- info/requires.txt. > Ok, setup.py itself may not do the work, but from the end users' > perspective it works that way. Setup.py runs a configure and a make, > which in turn find the right already-installed libraries. The point > is, setup.py plays well in such an environment. Configure etc. may be able to detect an installed version number of a package/module because they include scripts to check for those. IMHO it's silly to place the burden for checking for version numbers on the developer who wants to distribute an app. The package/module should provide a standard way to query the version number itself. This is exactly one of things that setuptools is about. Chris From paul at boddie.org.uk Tue Jun 19 18:56:44 2007 From: paul at boddie.org.uk (Paul Boddie) Date: Tue, 19 Jun 2007 15:56:44 -0700 Subject: stftime %z time conversion character In-Reply-To: References: Message-ID: <1182293804.305752.243840@w5g2000hsg.googlegroups.com> Evan Klitzke wrote: > Although it is not present in ANSI C, the GNU version of stftime > supports the conversion character %z, which is a time offset from GMT. > The four digit time offset is required in RFC 2822 dates/times, and is > used by a number of other programs as well. I need to convert times > that use this convention to python time representations, and because > Python does not support the %z time conversion character I cannot > simply use the time.strptime function. See this patch for an idea of the scope of this problem: https://sourceforge.net/tracker/?func=detail&atid=305470&aid=1667546&group_id=5470 > What solutions have people used for this? I'm currently thinking of > creating a dict that maps four digit time offsets to the time zone > name and then use the %Z token on that. Is there another (or better) > way? Apart from a patch which would allow the time module functions to produce the output you desire, an alternative might involve the datetime module and timezone-aware datetime objects: http://groups.google.com/group/comp.lang.python/msg/9848f3054b4f3eae I refer indirectly to the pytz module in the above message: http://pytz.sourceforge.net/ Paul From jm.suresh at gmail.com Thu Jun 21 07:06:50 2007 From: jm.suresh at gmail.com (jm.suresh@no.spam.gmail.com) Date: Thu, 21 Jun 2007 11:06:50 -0000 Subject: Globals in nested functions Message-ID: <1182424010.561262.169170@j4g2000prf.googlegroups.com> def f(): a = 12 def g(): global a if a < 14: a=13 g() return a print f() This function raises an error. Is there any way to access the a in f() from inside g(). I could find few past discussions on this subject, I could not find the simple answer whether it is possible to do this reference. - Suresh From deets at nospam.web.de Tue Jun 12 05:00:51 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 12 Jun 2007 11:00:51 +0200 Subject: A gotcha: Python pain point? References: <1181604836.292323.154510@z28g2000prd.googlegroups.com> Message-ID: <5d75m5F33j4d3U1@mid.uni-berlin.de> Beorn wrote: > Consider this example: > > >>> def funcs(x): > ... for i in range(5): > ... def g(): return x + i > ... yield g > > I would expect the value of x used in g to be that at the function You mean i here, don't you? > declaration time, as if you've pass g a (x=x) argument, especially > after reading this post: http://lua-users.org/wiki/LuaScopingDiscussion > > But: > > >>> [ fun() for fun in list(funcs(1)) ] > [5, 5, 5, 5, 5] > > Whereas: > > >>> [ fun() for fun in funcs(1) ] > [1, 2, 3, 4, 5] > > This came up while discussing Python pain points at > http://intertwingly.net/blog/2007/06/04/Python-Pain-Points#c1181602242 > > I can see how it works now, but I haven't found an easy-to-read > documentation on this. This has been discussed here very often. Python closures do capture the names, not the values. If you want a value at a certain point, you need to bind in the generated function scope by passing it as parameter. Like this: def funcs(x): for i in xrange(5): def g(i=i): return x + i yield g Diez From dak at gnu.org Mon Jun 25 03:11:07 2007 From: dak at gnu.org (David Kastrup) Date: Mon, 25 Jun 2007 09:11:07 +0200 Subject: The Modernization of Emacs: terminology buffer and keybinding References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182272495.990807.99110@a26g2000pre.googlegroups.com> <87tzt3ihev.fsf@kobe.laptop> <1182370216.961241.6960@n60g2000hse.googlegroups.com> <85zm2ufjpb.fsf@lola.goethe.zz> <1182372592.803332.288260@u2g2000hsc.googlegroups.com> <1182373919.262388.100740@c77g2000hse.googlegroups.com> <85r6o6fhkb.fsf@lola.goethe.zz> <1182375045.626510.188170@m36g2000hse.googlegroups.com> <85myyufgwj.fsf@lola.goethe.zz> <1182375528.985142.293900@q69g2000hsb.googlegroups.com> <1182545268.055596.228700@i38g2000prf.googlegroups.com> <1182661040.286559.150880@q75g2000hsh.googlegroups.com> <1182731526.329068.101540@c77g2000hse.googlegroups.com> <1182732527.577903.63600@q75g2000hsh.googlegroups.com> <87wsxsam2w.fsf@telesippa.clsnet.nl> Message-ID: <86fy4gh5kk.fsf@lola.quinscape.zz> Cor Gest writes: > Some entity, AKA JackT , > wrote this mindboggling stuff: > (selectively-snipped-or-not-p) > >> We don't care about the 1970 version of Emacs, >> because of course back then there WAS NO GUI. > > But if you are blind as bat, any 2007's GUI is useless. Have you actually talked to a blind person about that? They often prefer the GUI applications since they tend to interact better with screen readers and the accessibility software available for the GUI's toolkits. Sounds crazy, I know. Anyway, Emacs plays in a league of its own for blind people due to Emacspeak. -- David Kastrup From ndbecker2 at gmail.com Fri Jun 15 13:07:35 2007 From: ndbecker2 at gmail.com (Neal Becker) Date: Fri, 15 Jun 2007 13:07:35 -0400 Subject: global destructor not called? References: <4672b53f$0$31597$426a74cc@news.free.fr> Message-ID: Bruno Desthuilliers wrote: > Neal Becker a ?crit : >> To implement logging, I'm using a class: > > If I may ask : any reason not to use the logging module in the stdlib ? Don't exactly recall, but needed some specific behavior and it was just easier this way. > >> class logger (object): >> def __init__ (self, name): >> self.name = name >> self.f = open (self.name, 'w') >> def write (self, stuff): >> self.f.write (stuff) >> def close (self): >> self.f.close() >> def flush (self): >> self.f.flush() >> def reopen (self): >> self.f.flush() >> self.f.close() >> os.rename (self.name, self.name + '.old') >> self.f = open (self.name, 'w') >> def __del__ (self): >> try: >> os.remove (self.name + '.old') >> except: >> pass >> >> And setting: >> sys.stderr = logger(...) >> >> It seems my cleanup (__del__) is never called, > > What makes you think so ? Cleanup should remove file file '.old', and it wasn't removed. Adding atexit.register (self.__del__) to the logger constructor DID fix it. > >> even though I believe my >> program exits normally. What's wrong? > > Not enough data... From warren at muse.com Sat Jun 9 16:52:19 2007 From: warren at muse.com (Warren Stringer) Date: Sat, 9 Jun 2007 13:52:19 -0700 Subject: Hooking exceptions outside of call stack In-Reply-To: <001f01c7aab4$71153940$240110ac@Muse> References: <001f01c7aab4$71153940$240110ac@Muse> Message-ID: <002c01c7aad8$12963440$240110ac@Muse> Am still trying to hook a NameError exception and continue to run. After a few more hours of searching the web and pouring over Martelli's book, the closest I've come is: >>> import sys >>> def new_exit(arg=0): ... print 'new_exit called' ... #old_exit(arg) ... >>> def hook(type, value, tb): ... print 'hook called with', type ... return ... >>> sys.excepthook = hook >>> old_exit = sys.exit >>> sys.exit = new_exit >>> a[b]=1 # would like to get new_exit called hook called with exceptions.NameError >>> >>> def test(): ... sys.exit() ... >>> test() new_exit called The interactive session is different from running in the IDE (am using ActiveState's Visual Python) which exits just after the `a[b]=1` without calling hook. Am I missing something? Perhaps this is the wrong approach? I want Python to check a specific set of locals first, before checking globals. For instance: a.b[c] will call: a.__getattr__('b') but an exception is thrown before: a.b.__getitem__(c) Is there a way of intervening as `exec cmd in globals, locals` attempts to translate 'c' into an object? I thought that trapping a NameError might work. But now, I'm not so sure. Many thanks, \~/ > Here is what I would like to do: > > #------------------------------------------------------------ > a = Tr3() # implements domain specific language > a.b = 1 # this works, Tr3 overrides __getattr__ > a.__dict__['b'] = 2 # just so you know that b is local > a[b] = 3 # I want to resolve locally, but get: > > Traceback (most recent call last): ... > exec cmd in globals, locals ... > NameError: global name 'b' is not defined > #------------------------------------------------------------ > > So far, I've tried capturing exceptions in __getattr__, __setitem__, and > __setattr__, with no luck. I do NOT want to put `a[b]=3` inside a > try...except block because I want to enable a command line `>>>a[b]=3` > > Is there a way to hook a NameError exception outside of the call stack? > Perhaps, inside Tr3.__init__ ? Is there a way of putting back unhandled > NameError exceptions, so that they unwind the stack normally? > > This is intended for production code. From streamservenl at gmail.com Wed Jun 20 10:26:09 2007 From: streamservenl at gmail.com (jvdb) Date: Wed, 20 Jun 2007 07:26:09 -0700 Subject: How to hide a program? In-Reply-To: <5dsq6hF36eulqU1@mid.uni-berlin.de> References: <1182347596.414718.117190@w5g2000hsg.googlegroups.com> <5dsq6hF36eulqU1@mid.uni-berlin.de> Message-ID: <1182349569.122969.284950@q19g2000prn.googlegroups.com> On 20 jun, 15:59, "Diez B. Roggisch" wrote: > jvdb wrote: > > Hi all, > > > I've created a program that receives files and opens the corresponding > > program (for example adobe acrobat). However, when started, i would > > like to see nothing of the running program. I only want to see the > > program that will be opened. > > Is it possible to start a program 'hidden' or minimized to at least > > the system tray? And, if yes., could some one help me on this? > > I'm not exactly sure what you mean here, but I guess you want the > command-window suppressed. You can do so by naming your scripts *.pyw, > which will invoke pythonw.exe instead. That has no command-window. > > Diez Hi Diez, I forgot to mention that i have created a Windows executable of the script. What i want is to run the application minimized in the system tray or totally hidden. regards, Jeroen From justpratik at gmail.com Fri Jun 8 00:48:42 2007 From: justpratik at gmail.com (justpratik) Date: Thu, 07 Jun 2007 21:48:42 -0700 Subject: have a look at my blog site for asp.net .. there is microsoft contest also ( u can win so much)have a look at my blog site for asp.net .. there is microsoft contest also ( u can win so much) Message-ID: <1181278122.586940.109870@q19g2000prn.googlegroups.com> hi please a have a look at my site http://justpratik.blogspot.com and there's link for contest so hurry before 15th june From mwm at mired.org Wed Jun 6 15:20:09 2007 From: mwm at mired.org (Mike Meyer) Date: Wed, 6 Jun 2007 15:20:09 -0400 Subject: urllib2.urlopen broken? Message-ID: <18023.2281.63362.844051@bhuda.mired.org> In 2.5.1 (and 2.[45], but not 2.3): -- Mike Meyer http://www.mired.org/consulting.html Independent Network/Unix/Perforce consultant, email for more information. From jmoy.matecon at gmail.com Thu Jun 28 01:06:56 2007 From: jmoy.matecon at gmail.com (Jyotirmoy Bhattacharya) Date: Thu, 28 Jun 2007 05:06:56 -0000 Subject: nested list comprehension and if clauses Message-ID: <1183007216.684569.222450@k79g2000hse.googlegroups.com> I'm a newcomer to Python. I have just discovered nested list comprehensions and I need help to understand how the if-clause interacts with the multiple for-clauses. I have this small program: def multab(n): print 'multab',n return [n*i for i in range(5)] print [(m,n) for m in range(5) for n in multab(m) if m>2] It produces the output: multab 0 multab 1 multab 2 multab 3 multab 4 [(3, 0), (3, 3), (3, 6), (3, 9), (3, 12), (4, 0), (4, 4), (4, 8), (4, 12), (4, 16)] I was wondering if there is some way to write the if-clause so that it is 'hoisted' out of the inner loop and the multab function is not called at all for m=0,1,2. That would seem to be important if multab were an expensive function. From luismgz at gmail.com Sun Jun 24 12:48:27 2007 From: luismgz at gmail.com (=?iso-8859-1?q?Luis_M=2E_Gonz=E1lez?=) Date: Sun, 24 Jun 2007 16:48:27 -0000 Subject: visual gui ides for python/jythpn In-Reply-To: References: Message-ID: <1182703707.238396.30830@n2g2000hse.googlegroups.com> On 24 jun, 04:23, "Ethan Kennerly" wrote: > Luis M. Gonzalez wrote: > > PythonCard is an extremely easy to use alternative. > > It's like a simplified Visual Basic or Delphi IDE. > > Check IT out:www.pythoncard.org > > I second that! PythonCard is a rapid way to prototype an ugly Windows GUI. > (It's not PythonCard's fault that Windows are ugly. ;) ) I use it for > prototyping. > > But ONLY for prototyping. At least with my version in Windows, it's got > bugs in the resource editor. For example, Korean characters in Korean fonts > are rotated sideways. And the color of a font can't be changed; only the > foreground color can, which corrupts button display. The send to back/front > options don't seem to work. Transparent images (like PNG) don't seem to > work ... for me, anway. > > Yet, still, when I'm rapidly developing the mechanics of a game and need a > GUI front-end, PythonCard was a quick solution. It brilliantly stores the > GUI as a recursive dictionary, which is like XML, only easy for a human to > read. The widgets require very little of your coding. It's got a lot of > samples, which makes some of its peculiar conventions easy to apply. And > any Python app made with the PythonCard framework has a namespace viewer, > shell, and GUI message integrated into the application. > > Flash and Python: The ultimate GUI prototyping combo? > > In my dreams, I would use Flash for the GUI portion of a Python app. Flash > is by far my favorite environment for rapidly designing interfaces. It is > an (almost) object-oriented drawing environment that can quickly produce > good visual design. Because the elements are instances of prototypes (Flash > calls them symbols), they can be easily replaced and updated at any time. > The timeline, animation, color, layer, and drawing tools are wonderful. You > can quickly make traditional or experimental interfaces. The only thing > that sucked (for me), was ActionScript. It's not bad. It's quite good for > interface scripting. But for back-end procedures it is prison compared to > Python. > > Does anyone successfully use a Flash front-end and Python back-end in > real-time? I've tried an example of XMLRPC servers where a Flash app (SWF) > communicates with Python (http://www.cs.unc.edu/~parente/tech/tr01.shtml), > but that has a round-trip time that is too slow for something like a > videogame (updates at 30 frames per second). Some of the projects at OS > flash look promising (http://osflash.org/ext_howto), but I haven't found the > part that says that my interface made in Macromedia Flash (which is a > fantastic design environment) can be used with my code in Python with a > real-time frame rate. > > -- Ethan Ethan, If you are looking for something more ?advanced? than a simple windows GUI, I suggest checking out Silverlight, wich is the new deployment technology that ties Ironpython to the browser. With it, you can use Ironpython (wich is Python for .NET) to create apps that run on the browser, the same way you would use javascript, with a lot of new features like animations (ala flash). You are not only limited to Ironpython though. You can use any .NET language, includin other dynamic ones such as Ironruby (not released yet). It is a Microsoft technology, but it works on Firefox as well as IE, on Windows and Mac. It will also run on linux through a Mono project called Moonlight. Luis From timr at probo.com Sat Jun 23 01:11:18 2007 From: timr at probo.com (Tim Roberts) Date: Sat, 23 Jun 2007 05:11:18 GMT Subject: The Modernization of Emacs: terminology buffer and keybinding References: <1182272495.990807.99110@a26g2000pre.googlegroups.com> <87tzt3ihev.fsf@kobe.laptop> <1182370216.961241.6960@n60g2000hse.googlegroups.com> <85zm2ufjpb.fsf@lola.goethe.zz> <1182372592.803332.288260@u2g2000hsc.googlegroups.com> <1182549094.366282.286740@m37g2000prh.googlegroups.com> <87bqf7fwmg.fsf@telesippa.clsnet.nl> <1182553682.197778.138500@g37g2000prf.googlegroups.com> <877ipvfswe.fsf@telesippa.clsnet.nl> Message-ID: Cor Gest wrote: >Some entity, AKA nebulous99 at gmail.com, >wrote this mindboggling stuff: > >> On Jun 22, 6:32 pm, Cor Gest wrote: >> >> So now we're expected to go on a filesystem fishing expedition instead >> of just hit F1? One small step (backwards) for a man; one giant leap >> (backwards) for mankind. :P > >that's M-` Escape-Backtick in a CLI, for you, thank you very much ... >Function-Keys do not work in in a vt100 terminal. > >You really are that shallow, aren't you ? and lazy too, huh ? Boys, do you really not understand that this is a religious issue? You can't use arguments and logic to convince someone to convert their religion, and you can't use arguments and logic to convince someone to change editors. Editors are like underwear. We each have our own favorite brand, and nothing you say will convince me to change mine. Editor, that is. I do occasionally change my underwear. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From http Sat Jun 16 23:03:45 2007 From: http (Paul Rubin) Date: 16 Jun 2007 20:03:45 -0700 Subject: Want to learn Python References: <1181907696.878873.214760@i13g2000prf.googlegroups.com> <1181950960.793735.304570@c77g2000hse.googlegroups.com> <1hzrppt.1i3pamvoxog4rN%aleax@mac.com> <1182011078.358795.151590@c77g2000hse.googlegroups.com> <1hzt7iz.1s2iz1hlvanlvN%aleax@mac.com> Message-ID: <7xvednmgdq.fsf@ruckus.brouhaha.com> Dennis Lee Bieber writes: > > Aahz's book is really good, in my opinion. So are many others in the > > "for Dummies" series that I've had occasion to try (including the one > > with the delightfully unintended pun in its title, "Bridge for Dummies": > > despite the title it applies to declarers and defenders just as well:-). > > Judging a book by its cover (and, by extension, by how its publisher > > markets a series) is the proverbial epitome of superficiality. > > > The first edition "Wicca for Dummies" had a few laughs too... > Biggest one is that someone inserted a photo of the "Venus de Milo" > where the text called for the "Venus of Willendorf". I wonder if they had a series about automotive safety engineering, with a volume called "crash testing for dummies". From NunezD at gmail.com Fri Jun 22 13:58:17 2007 From: NunezD at gmail.com (hiro) Date: Fri, 22 Jun 2007 17:58:17 -0000 Subject: comparing two lists and returning "position" In-Reply-To: References: <1182481876.028589.71710@x35g2000prf.googlegroups.com> <7xvedg4n2d.fsf@ruckus.brouhaha.com> <467b624e$0$16271$c30e37c6@lon-reader.news.telstra.net> <1182493019.795629.108860@w5g2000hsg.googlegroups.com> <1182534010.884992.119690@u2g2000hsc.googlegroups.com> Message-ID: <1182535097.054481.296050@p77g2000hsh.googlegroups.com> On Jun 22, 1:56 pm, Marc 'BlackJack' Rintsch wrote: > In <1182534010.884992.119... at u2g2000hsc.googlegroups.com>, hiro wrote: > > Hi once again, Charles.. I have tried your approach in my data set l2 > > and it keeps crashing on me, > > bare in mind that I have a little over 10 million objects in my list > > (l2) and l1 contains around 4 thousand > > objects.. (i have enough ram in my computer so memory is not a > > problem) > > > python 2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit > > (Intel)] on win32 > > > error is : ValueError: list.index(x): x not in list > > So you are saying you get this error with the value of `x` actually in the > list!? Somehow hard to believe. > > Ciao, > Marc 'BlackJack' Rintsch yes I do From python at jayloden.com Thu Jun 14 00:55:16 2007 From: python at jayloden.com (Jay Loden) Date: Thu, 14 Jun 2007 00:55:16 -0400 Subject: dynamically generated runtime methods & reflection Message-ID: <25e163710706132155i640186f6l3166f40f83c1c28@mail.gmail.com> Hi all, First, apologies if anyone gets this twice, but it took me quite a while to figure out that Python.org is evidently rejecting all mail from my mail server because I don't have reverse DNS configured. Anyway: I'm not even sure how to phrase this question properly or the right terminology on this so bear with me. What I'm looking to find out is a) is there a functionality in Python where I can call a method I have not defined ahead of time, and based on the method name, change the functionality of the method at runtime? b) if not, what is the "Pythonic" approach to the problem outlined below? Any recommendations on how to approach the problem differently are welcome. I've googled and read my Python reference pretty extensively and I've found some hints but nothing that really answered my questions, so here I am :-) I did figure out that you can overload __getattr__ in a clas to define a new method at runtime, but I got stuck when I couldn't figure out how to have a method know what name it was originally called with. That's the basic question, see below for the context I'm asking the question in and *why* I want to do the above :-) ----- The software product I work on has a socket-based API that can be accessed directly via telnet & manually typing commands, or by a set of Perl modules that wrap the socket functionality. I am looking to write a set of Python modules that match the same functionality. Basically you can telnet to a port and type something like item.list "param1=value1", "param2=value2" And it will return the results (if any) to you in a given format along with a response code, e.g. 200 OK or 400 ERROR. The Perl modules just wrap this so that instead of the above, you can do something like this: $MySocketServer = new SocketServer(Host=>'127.0.0.'1, Port=>'9999'); if (! $MySocketServer->ListItem(itemName=>$item_name)) { print "failed to retrieve list"; print "reason: " . $MySocketServer->GetErrorMsg(); exit; } The ListItem() method handles the work of communicating across the socket, waiting for the response, and determine the success/failure based on the return code. The part where it gets interesting is that our Perl modules don't actually have a ListItem() method. Instead, there is a generalized "_api_func()" method that looks at the name of the method you called (using Autoload I believe, for any Perlheads out there), and bases the action taken on the name. In the example above, for instance, it sees that you called ListItem(), so it transforms that to item.list and makes the parameters of the method the parameters that are passed to item.list via the socket server. Then it takes the response back from the socket to determine the function return code. If there are any results such as a list of items, they are then able to be accessed through a reference to a hash of the results, and there is a GetResultRef accessor function. In essence, our Perl modules are an incredibly lightweight, simplistic wrapper for the socket-based API, and almost all of the work is offloaded to the API implementation server-side. I welcome any suggestions, feedback, sample code, documentation, whitepapers etc. The only thing I don't want to have to do is go and define a separate method for every single one of the possible permutations of socket commands if I can avoid it! ----- Thanks in advance, -Jay From cam.ac.uk at mh391.invalid Thu Jun 14 06:55:15 2007 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Thu, 14 Jun 2007 11:55:15 +0100 Subject: How can I capture all exceptions especially when os.system() fail? Thanks In-Reply-To: References: <1181782036.646379.28510@g37g2000prf.googlegroups.com> Message-ID: Gabriel Genellina wrote: > En Wed, 13 Jun 2007 21:47:16 -0300, mike escribi?: > >> Following piece of code can capture IOError when the file doesn't >> exist, also, other unknown exceptions can be captured when I press >> Ctrl-C while the program is sleeping(time.sleep). Now the question is: >> when I run the non-exist command, the exception cannot be captured. > >> So far so good, then I changed the code to run a non-exist command >> "wrong_command_test"(commented the open and sleep lines), then the >> script printed: >> sh: wrong_command_test: command not found >> well Done > > That's because it is not an exception, it is an error message coming > from your shell, not from Python. Of course if you use subprocess.check_call() instead of os.system(), it will become an exception (CalledProcessError). -- Michael Hoffman From bbxx789_05ss at yahoo.com Sun Jun 24 14:42:27 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: Sun, 24 Jun 2007 11:42:27 -0700 Subject: Accessing variable from a function within a function In-Reply-To: References: Message-ID: <1182710547.921409.212050@w5g2000hsg.googlegroups.com> On Jun 24, 11:55 am, "Nathan Harmston" wrote: > Hi, > > I m playing around with extended euclids algorithm from Knuth. I m > trying to build a function with a function inside it. > > def exteuclid(m,n): > a,a1,b,b1,c,d = 0,1,1,0,m,n > def euclid(c,d): > q = c /d > r = c % d > if r == 0: > print a,b > return d > else: > print a1,a,b1,b,c,d,q,r > t = b1 > b = t - q * b > a = t - q * a > c,d,a1,b1 = d,r,a,b > return euclid(c,d) > return euclid(c,d) > > Unfortunately this doesnt work since a,a1,b,b1 arent declared in the > function. Is there a way to make these variables accessible to the > euclid function. Or is there a better way to design this function? > > Many Thanks in advance, > > Nathan ef outer(): a = 10 def inner(): print a return inner f = outer() f() --output:-- 10 From deets at nospam.web.de Wed Jun 13 04:17:24 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 13 Jun 2007 10:17:24 +0200 Subject: How to create a tuple quickly with list comprehension? References: <1181722446.984694.242700@q19g2000prn.googlegroups.com> Message-ID: <5d9ngkF32j8imU1@mid.uni-berlin.de> markacy wrote: > On 13 Cze, 09:45, "fdu.xia... at gmail.com" wrote: >> Hi all, >> >> I can use list comprehension to create list quickly. So I expected that I >> can created tuple quickly with the same syntax. But I found that the >> same syntax will get a generator, not a tuple. Here is my example: >> >> In [147]: a = (i for i in range(10)) >> >> In [148]: b = [i for i in range(10)] >> >> In [149]: type(a) >> Out[149]: >> >> In [150]: type(b) >> Out[150]: >> >> Is there a way to create a tuple like (1, 2, 3, 4, 5, 6, 7, 8, 9) >> quickly? I already I can use tuple() on a list which is created by list >> comprehension to get a desired tuple. >> >> Regards, >> >> Xiao Jianfeng > > You should do it like this: > >>>> a = tuple([i for i in range(10)]) >>>> type(a) > >>>> print a[0] > 0 >>>> print a[9] > 9 >>>> print a > (0, 1, 2, 3, 4, 5, 6, 7, 8, 9) No need to create the intermediate list, a generator expression works just fine: a = tuple(i for i in range(10)) Diez From sjmachin at lexicon.net Sun Jun 10 05:43:40 2007 From: sjmachin at lexicon.net (John Machin) Date: Sun, 10 Jun 2007 19:43:40 +1000 Subject: read xml file from compressed file using gzip In-Reply-To: <1181452004.347078.241840@q19g2000prn.googlegroups.com> References: <1181278784.312152.99910@r19g2000prf.googlegroups.com> <466AE729.8070602@web.de> <1181452004.347078.241840@q19g2000prn.googlegroups.com> Message-ID: <466BC7CC.1080709@lexicon.net> On 10/06/2007 3:06 PM, flebber wrote: > On Jun 10, 3:45 am, Stefan Behnel wrote: >> flebber wrote: >>> I was working at creating a simple program that would read the content >>> of a playlist file( in this case *.k3b") and write it out . the >>> compressed "*.k3b" file has two file and the one I was trying to read >>> was maindata.xml >> The k3b format is a ZIP archive. Use the zipfile library: >> >> file:///usr/share/doc/python2.5-doc/html/lib/module-zipfile.html >> >> Stefan > > Thanks for all the help, have been using the docs at python.org and > the magnus t Hetland book. Is there any docs tha re a little more > practical or expressive as most of the module documentation is very > confusing for a beginner and doesn't provide much in the way of > examples on how to use the modules. > > Not criticizing the docs as they are probably very good for > experienced programmers. > Somebody else has already drawn your attention to the/a tutorial. You need to read, understand, and work through a *good* introductory book or tutorial before jumping into the deep end. > class GzipFile([playlist_file[decompress[9, 'rb']]]); Errr, no, the [] are a documentation device used in most computer language documentation to denote optional elements -- you don't type them into your program. See below. Secondly as Stefan pointed out, your file is a ZIP file (not a gzipped file), they're quite different animals, so you need the zipfile module, not the gzip module. > os.system(open("/home/flebber/tmp/maindata.xml")); The manuals say quite simply and clearly that: open() returns a file object os.system's arg is a string (a command, like "grep -i fubar *.pl") So that's guaranteed not to work. From the docs of the zipfile module: """ class ZipFile( file[, mode[, compression[, allowZip64]]]) Open a ZIP file, where file can be either a path to a file (a string) or a file-like object. The mode parameter should be 'r' to read an existing file, 'w' to truncate and write a new file, or 'a' to append to an existing file. """ ... and you don't care about the rest of the class docs in your simple case of reading. A class has to be called like a function to give you an object which is an instance of that class. You need only the first argument; the second has about a 99.999% chance of defaulting to 'r' if omitted, but we'll play it safe and explicit: import zipfile zf = zipfile.ZipFile('/home/flebber/oddalt.k3b', 'r') OK, some more useful docs: """ namelist( ) Return a list of archive members by name. printdir( ) Print a table of contents for the archive to sys.stdout. read( name) Return the bytes of the file in the archive. The archive must be open for read or append. """ So give the following a try: print zf.namelist() zf.printdir() xml_string = zf.read('maindata.xml') zf.close() # xml_string will be a string which may or may not have line endings in it ... print len(xml_string) # If you can't imagine what the next two lines will do, # you'll have to do it once, just to see what happens: for line in xml_string: print line # Wasn't that fun? How big was that file? Now do this: lines = xml_text.splitlines() print len(lines) # number of lines print len(lines[0]) # length of first line # Ummm, maybe if it's only one line you don't want to do this either, # but what the heck: for line in lines: print line HTH, John From torriem at chem.byu.edu Mon Jun 18 22:38:00 2007 From: torriem at chem.byu.edu (Michael Torrie) Date: Mon, 18 Jun 2007 20:38:00 -0600 Subject: GUI apps in Windows with native widgets? In-Reply-To: References: Message-ID: <1182220680.22166.2.camel@enterprise> On Tue, 2007-06-19 at 04:13 +0200, Gilles Ganault wrote: > Hello > > I'd like to write a GUI app in Python exclusively for Windows. > Apparently, development of PythonWin has stopped a long time ago. > > Is there another thin wrapper to write apps in Windows? I'd rather not > have to ship eg. WxWidgets, GTK+, or QT. Well shipping wxWidgets isn't a big deal. If you are already requiring python be installed, then a wxWidgets dll is trivial. Even better, if you are using py2exe, then the wxWidgets dll and module will all be wrapped cleanly in the exe, so I think it's a clear winner. Users needn't know anything about wxWidgets or have to install it. Bundling wxWidgets in your python app adds a couple of megabytes to the size. Certainly you're not going to want to do native win32 GUI development, even in python. wxWidgets is an order of magnitude better for doing this, methinks. > > Thank you. From kyosohma at gmail.com Mon Jun 25 10:38:01 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Mon, 25 Jun 2007 07:38:01 -0700 Subject: Capturing and sending keys {Esperanto} In-Reply-To: References: Message-ID: <1182782281.180299.260650@u2g2000hsc.googlegroups.com> On Jun 25, 8:26 am, AJK wrote: > Hello there! > > I've been googleing yet, and suppose it's hopeless to try, but better ask it... > > I want to write a program which turns Cx to ?, cx to ? et al WHILE > TYPING. (i.e. converting Esperanto x-system to real hats, for those > who know about this.) Therefore I though will need to capture the last > 2 typed characters (from any application), send a double backspace and > after that send the correct letters (back to the same application)... > > However, it seems inpossible to capture those letters, and maybe to > send them too... > > Or am I wrong? > > Greetings, > > LaPingvino > > (project:http://code.google.com/p/iksilo/- SVN Repository is free > viewable, project is GPL) > > -- > ?ar Dio tiel amis la mondon, ke Li donis Sian solenaskitan Filon, por > ke ?iu, kiu fidas al li, ne pereu, sed havu eternan vivon. > -Johano 3:16, La sankta Biblio- > > ?oju ?iam, pre?u sen?ese, pri ?io donu dankon. > -1 Tesalonikanoj 5:16-18a, La sankta Biblio- I've never done this before, but theoretically, you should be able to have a separate process monitor what you're typing and maybe do edits in real time. At least, I assume that that is how MS Word works. I have messed a little with sendkeys though. Here's the examples I found on the net: http://mail.python.org/pipermail/python-list/1999-May/003244.html http://aspn.activestate.com/ASPN/Python/Cookbook/Recipe/65107 http://msdn.microsoft.com/library/default.asp?url=/library/en-us/script56/html/4b032417-ebda-4d30-88a4-2b56c24affdd.asp The msdn one is just the MS docs for Sendkeys. One other alternative would be to type it all out and then run a script to parse your document and basically just do a search and replace. Hopefully that helps your out a little at least. Mike From stuffduff at cox.net Wed Jun 20 10:22:22 2007 From: stuffduff at cox.net (stuffduff) Date: Wed, 20 Jun 2007 14:22:22 -0000 Subject: SIGSEGV gcmodule.c:241 closing python after module import Message-ID: <1182349342.952030.35230@q69g2000hsb.googlegroups.com> Hi, I have a python extension that works fine while it is running, but when I exit python I get this error: GNU gdb Red Hat Linux (6.5-15.fc6rh) Copyright (C) 2006 Free Software Foundation, Inc. GDB is free software, covered by the GNU General Public License, and you are welcome to change it and/or distribute copies of it under certain conditions. Type "show copying" to see the conditions. There is absolutely no warranty for GDB. Type "show warranty" for details. This GDB was configured as "i386-redhat-linux-gnu"...Using host libthread_db library "/lib/libthread_db.so.1". (gdb) run Starting program: python2.4 ... Program received signal SIGSEGV, Segmentation fault. [Switching to Thread -1208243504 (LWP 12884)] collect (generation=2) at Modules/gcmodule.c:241 241 Modules/gcmodule.c: No such file or directory. in Modules/gcmodule.c (gdb) bt #0 collect (generation=2) at Modules/gcmodule.c:241 #1 0x080e1ec5 in PyGC_Collect () at Modules/gcmodule.c:1196 #2 0x080da88a in Py_Finalize () at Python/pythonrun.c:353 #3 0x08055176 in Py_Main (argc=0, argv=0xbfb8dae4) at Modules/main.c: 513 #4 0x08054962 in main (argc=-1208273400, argv=0x812ed68) at Modules/python.c:23 I haven't figured out what it is trying to collect. Is there a way to tell? Thanks, Sean From yucetekol at gmail.com Mon Jun 4 01:52:26 2007 From: yucetekol at gmail.com (yuce) Date: Mon, 04 Jun 2007 05:52:26 -0000 Subject: excel library without COM In-Reply-To: <1180918791.467050.186520@r19g2000prf.googlegroups.com> References: <1180918791.467050.186520@r19g2000prf.googlegroups.com> Message-ID: <1180936346.272773.162540@q66g2000hsg.googlegroups.com> i think this one works pretty nice: http://www.python.org/pypi/xlrd Happy hacking, Yuce On Jun 4, 3:59 am, james_027 wrote: > Hi, > > is there any library to help me write excel files without using win > com? because i'll be working on linux platform. At the same time I > could want to perform some formatting, merging of cells. adding sheets > and etc ... > > Thanks > james From tjreedy at udel.edu Tue Jun 19 11:14:00 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 19 Jun 2007 11:14:00 -0400 Subject: Python's "only one way to do it" philosophy isn't good? References: <1181368143.874341.273140@r19g2000prf.googlegroups.com> Message-ID: "Douglas Alan" wrote in message news:lcvedlf3t8.fsf at gaffa.mit.edu... | "Terry Reedy" writes: | | > |>oug writes: | | >> Scheme has a powerful syntax extension mechanism | | > I did not and do not see this as relevant to the main points of my | > summary above. The main point of my original post was that the quoted slam at Python was based on a misquote of Tim Peters and a mischaracterization of Python and that it was out-of-place in the quoted discussion of physics methods and that it added nothing to that discussion and should better have been omitted. *All of this has nothing to do with Scheme.* At the end, I added as a *side note* the irony that the purported author was the co-developer of Scheme, another 'minimalist algorithm language (Wikipedia's characterization) with more uniform syntax than Python and like Python, also with one preferred way to scan sequences (based on my memory of Scheme use in the original SICP, co-authored by the same purported quote author, and also confirmed by Wikipedia). I do not consider it a slam at Scheme to compare it with Python and see some similarities. Nor is it a slam at Scheme to suggest that it could just as well have been the subject of an unfair slam, if only the slammer were not its co-developer ;-) | [Steele quote deleted] | Do you now see how Scheme's syntax extension mechanism is relevant? No. This just partly explains why Scheme gets away with being minimalist. I explicitly referred to the core language as delivered and as used in SICP. tjr From exarkun at divmod.com Fri Jun 8 22:22:39 2007 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Fri, 8 Jun 2007 22:22:39 -0400 Subject: Could someone show me a sample how to flush the socket sending buffer? Thanks a lot. In-Reply-To: <1181342190.374220.21800@z28g2000prd.googlegroups.com> Message-ID: <20070609022239.30678.1860935621.divmod.quotient.12934@ohm> On Fri, 08 Jun 2007 15:36:30 -0700, mike wrote: >I have called the setsockopt() to set no delay after connecting like >this way: > > s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > s.connect(('192.168.10.1', 21980)) > s.setsockopt(socket.SOL_TCP, socket.TCP_NODELAY, 0) > s.send("abc at abc.com\n") > s.send("123 at hbc.com\n") > ...... > >but still, the server can only receive the first line, and keep >waiting for the second line. So, in my mind the second line is still >in the sending buffer, and not reach the server side. There is no buffer you can flush. Also, you forgot to check the return value of the send method. It is important. You might want to look at the sendall method. Or you might want to check out Twisted. Jean-Paul From robin at reportlab.com Wed Jun 27 10:49:57 2007 From: robin at reportlab.com (Robin Becker) Date: Wed, 27 Jun 2007 15:49:57 +0100 Subject: 16bit hash Message-ID: <46827915.7040403@chamonix.reportlab.co.uk> Is the any way to get an efficient 16bit hash in python? -- Robin Becker From nagle at animats.com Sun Jun 10 21:51:55 2007 From: nagle at animats.com (John Nagle) Date: Mon, 11 Jun 2007 01:51:55 GMT Subject: Python optimization (was Python's "only one way to do it" philosophy isn't good?) In-Reply-To: References: Message-ID: <%U1bi.26649$JZ3.8120@newssvr13.news.prodigy.net> Steve Howell wrote: > --- John Nagle wrote: > >>With this, the heavy optimizations are possible. >>Strength reduction. Hoisting >>common subexpressious out of loops. Hoisting >>reference count updates out of >>loops. Keeping frequently used variables in >>registers. And elimination of >>many unnecessary dictionary lookups. >> > To the extent that some of these optimizations could > be achieved by writing better Python code, it would > nice for optimization tools to have a "suggest" mode. > For example, if I code a Fourier series and duplicate > the subexpression n*f*t, it would be nice for a tool > to tell me that I should refactor that expression. > Something like this: > > n*f*t should be refactored out of this expression, > assuming muliplication has no desired side effects for > n, f, and t. Too labor-intensive. These are well understood optimizations that can be done quite well automatically. The problem is Python's gratutious dynamism - it's hard to tell, when examining code, if something can be patched by other code elsewhere. Where "setattr" is allowed, the compiler has to assume side effects almost everywhere. John Nagle From duncan.booth at invalid.invalid Thu Jun 28 07:42:57 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 28 Jun 2007 11:42:57 GMT Subject: problem with hack using multiple inheritance for plugins References: <1183026288.857294.91620@q69g2000hsb.googlegroups.com> <1183028051.940679.145680@q69g2000hsb.googlegroups.com> Message-ID: "massimo s." wrote: > Now I know that: > - every sane Python class should return after > type(self) Wrong. Only old style classes are 'instance' type, and you should never be using an old style class unless you have a very good reason for it. Always use 'object' (or another builtin type if appropriate) as a base class. From tjreedy at udel.edu Wed Jun 27 13:58:14 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 27 Jun 2007 13:58:14 -0400 Subject: Reversing a string References: Message-ID: "Scott" wrote in message news:cYWdncuhLL6PCx_bnZ2dnUVZ_o2vnZ2d at comcast.com... | Yeah I know strings == immutable, but question 1 in section 7.14 of "How to | think like a computer Scientist" has me trying to reverse one. >>> 'this is a test'[::-1] 'tset a si siht' From Graham.Dumpleton at gmail.com Thu Jun 28 01:19:06 2007 From: Graham.Dumpleton at gmail.com (Graham Dumpleton) Date: Thu, 28 Jun 2007 05:19:06 -0000 Subject: Changing default output object for Message-ID: <1183007946.484215.316140@x35g2000prf.googlegroups.com> I am sure someone has probably thought of this and there are good reasons why it is a bad idea or not possible, but, is there any technical reason why one couldn't somehow replace PRINT_ITEM byte code, with combination of byte codes which inserted in a reference to a file like object and then invoked PRINT_ITEM_TO byte code instead. In other words, the aim is allow users code to use 'print' but change where the output goes when no target file is provided. I do know that one can replace sys.stdout with another file object in the simple case, or in the more complicated case with a file like object that determines where to redirect output based on the calling thread identity or some over criteria, but wanted to see if some one could do something without modifying sys.stdout. One particular example where I thought this might be interesting is to allow in a web templating system where Python code blocks can be embedded in markup, the use of the 'print' statement without a user having to know that they really need to direct output to a special file object, eg. 'print >> response'. Procedure might thus be to load Python code snippets and compile to byte code. Fixup byte code to change PRINT_ITEM to PRINT_ITEM_TO with other byte codes added to insert appropriate reference to file like object being supplied through data only passed to code object when executed. Cache code for ongoing use. Invoke code object as required, supplying reference to file object for output. In some template systems such as in web.py they replace sys.stdout with a magic object which based on the identity of the thread making calls to the methods of sys.stdout, will redirect the output back to a registered response object, but instead of doing it this way, could byte code manipulation provide another way. Anyway, just curious as to whether it would be possible or not and if someone has an example of doing it using byteplay or similar would love to see what is required. Graham From steven at REMOVE.THIS.cybersource.com.au Fri Jun 22 02:17:15 2007 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 22 Jun 2007 06:17:15 GMT Subject: Python's "only one way to do it" philosophy isn't good? References: <1181368143.874341.273140@r19g2000prf.googlegroups.com> <7x3b0nmkk6.fsf@ruckus.brouhaha.com> Message-ID: On Thu, 21 Jun 2007 15:25:37 -0400, Douglas Alan wrote: > You are imagining something very different from what is proposed. > Lisp-like macros don't allow "anything goes". Provided people avoid doing anything "which would be considered very rude" (your own words). Python already allows me to shoot myself in the foot, if I wish. I'm comfortable with that level of freedom. I'm not necessarily comfortable with extensions to the language that would allow me the freedom to shoot myself in the head. I would need to be convinced of the advantages, as would many other people, including the BDFL. It isn't clear exactly what functionality a hypothetical Python macro system would include, let alone whether the benefits would outweigh the costs, so I think it is very important for proponents of such a macro system to justify precisely why it is valuable before expecting others to go off and spend potentially thousands of man-hours turning Python into a shadow of Lisp/Scheme. (It took Lisp half a century and millions of dollars of corporate funding to reach where it is now. Anyone who thinks it is a trivial task to turn Python into Lisp "only better" is deluded -- one can't merely bolt on macros onto the existing Python compiler.) -- Steven. From newsgroups at nospam.demon.co.uk Wed Jun 27 04:08:02 2007 From: newsgroups at nospam.demon.co.uk (Douglas Woodrow) Date: Wed, 27 Jun 2007 09:08:02 +0100 Subject: Python's "only one way to do it" philosophy isn't good? References: <7x3b0nmkk6.fsf@ruckus.brouhaha.com> <1182750077.570603.160240@q69g2000hsb.googlegroups.com> <7xir9cbm0g.fsf@ruckus.brouhaha.com> <7xejjzmk7u.fsf@ruckus.brouhaha.com> <7xy7i7xjl5.fsf@ruckus.brouhaha.com> Message-ID: <5N0C7KBirhgGFwUp@woodrowhorsfall.plus.com> On Wed, 27 Jun 2007 01:45:44, Douglas Alan wrote >A chaque son gout I apologise for this irrelevant interruption to the conversation, but this isn't the first time you've written that. The word "chaque" is not a pronoun. http://grammaire.reverso.net/index_alpha/Fiches/Fiche220.htm -- Doug Woodrow From lists at asd-group.com Fri Jun 1 22:29:07 2007 From: lists at asd-group.com (NeBlackCat) Date: Sat, 02 Jun 2007 10:29:07 +0800 Subject: Detecting an active exception In-Reply-To: References: Message-ID: <4660D5F3.7070807@asd-group.com> Thanks Duncan - that does clear things up for me on how sys.exc_info() it actually works! But it does seem that there is no way to test "am I currently running in the scope of handling of an exception", which is what I need. If there was, I could then rely on sys.exc_info() to examine the exception. I'm implementing something which has to do one thing if called during exception handling, and another otherwise (and there's no way to explicitly pass a flag to indicate the situation). I'm surprised by there apparently not being such a test, I wonder if I should do a PEP to ask for this feature. If anyone does know a way to do it in the current implementation, even by stack examining, I'd love to hear it! :-) Cheers - John Duncan Booth wrote: > "NeBlackCat (lists)" wrote: > > >> Depending on what you read, sys.exc_info() is supposed to return >> (None,None,None) when there is no active exception, but it seems that >> it returns info about the last exception when there isn't one >> currently active. >> >> For example: >> >> try: >> a = a + 1 >> except: >> pass >> >> print sys.exc_info() >> >> produces: >> , > instance at 0x00B5E508>, >> >> Where the traceback object identifies the offending a=a+1 line (of >> course). >> >> Is there another way of doing this? Note that I can't rely on using >> sys.exc_clear() in any solution, unfortunately. >> > > I think you have misunderstood the definition of when an exception is > 'currently active'. When an exception is caught, it remains currently > active so long as you are in the same function, or in a function which it > calls (i.e. so long as the current scope is still active). When you return > from that function the exception is no longer active and the previous > exception becomes active (or None if there has not been one or you have > used sys.exc_clear()). > > Try this: > --------- t.py ------------- > import sys > > def f(): > try: > a = a + 1 > except: > pass > > g() > print "f", sys.exc_info() > > def g(): > print "g", sys.exc_info() > > def h(): > f() > print "h", sys.exc_info() > > h() > ---------------------------- > The output is: > > g (, UnboundLocalError("local variable > 'a' referenced before assignment",), ) > f (, UnboundLocalError("local variable > 'a' referenced before assignment",), ) > h (None, None, None) > > As you can see the exception remains 'currently active' only until the > function in which it was caught returns. > From felciano at gmail.com Fri Jun 22 20:26:46 2007 From: felciano at gmail.com (felciano) Date: Fri, 22 Jun 2007 17:26:46 -0700 Subject: Python plain-text database or library that supports joins? In-Reply-To: <1182547204.703919.62440@x35g2000prf.googlegroups.com> References: <1182532691.182581.110940@m37g2000prh.googlegroups.com> <1182547204.703919.62440@x35g2000prf.googlegroups.com> Message-ID: <1182558406.122090.62210@e9g2000prf.googlegroups.com> > > i don't think that using flat text files as a database is common these > days. if you need relational database features what stops you from > using rdbms? if the only reason for that is some legacy system then > i'd still use in-memory sqlite database for all relational operations. > import, process, export back to text if you need to. > These are often one-off operations, so those import + export steps are non-trivial overhead. For example, most log files are structured, but it seems like we still use scripts or command line tools to find data in those files. I'm essentially doing the same thing, only with operations across multiple files (e.g. merge records these two files based on a common key, or append a column based on a look up value). I may end up having to go to DB, but that seems like a heavyweight jump for what are otherwise simple operations. Maybe this is the wrong forum for the question. I prefer programming in Python, but the use cases I'm looking is closer to shell scripting. I'd be perfectly happy with a more powerful version of GNU textutils that allowed for greater flexibility in text manipulation. HTH, Ramon From gagsl-py2 at yahoo.com.ar Tue Jun 26 21:19:25 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 26 Jun 2007 22:19:25 -0300 Subject: urllib interpretation of URL with ".." References: <467cc85f$0$3039$9b622d9e@news.freenet.de> <4681765c$0$424$a729d347@news.telepac.pt> Message-ID: En Tue, 26 Jun 2007 17:26:06 -0300, sergio escribi?: > John Nagle wrote: > >> In Python, of course, "urlparse.urlparse", which is >> the main function used to disassemble a URL, has no idea whether it's >> being used by a client or a server, so it, reasonably enough, takes >> option >> 1. > >>>> import urlparse >>>> base="http://somesite.com/level1/" >>>> path="../page.html" >>>> urlparse.urljoin(base,path) > 'http://somesite.com/page.html' >>>> base="http://somesite.com/" >>>> urlparse.urljoin(base,path) > 'http://somesite.com/../page.html' > > For me this is a bug and is very annoying because I can't simply trip ../ > from path because base could have a level. I'd say it's an annoyance, not a bug. Write your own urljoin function with your exact desired behavior - since all "meaningful" .. and . should have been already processed by urljoin, a simple url = url.replace("/../","/").replace("/./","/") may be enough. -- Gabriel Genellina From stefan.behnel-n05pAM at web.de Wed Jun 27 13:07:29 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Wed, 27 Jun 2007 19:07:29 +0200 Subject: Reversing a string In-Reply-To: References: Message-ID: <46829951.2090104@web.de> Scott wrote: > So how on earth would be the best way to: Write a function that takes a > string as an argument and outputs the letters backward, one per line. Homework? Anyway, what about: for c in string[::-1]: print c Stefan From clarence1126 at gmail.com Fri Jun 22 16:29:06 2007 From: clarence1126 at gmail.com (Clarence) Date: Fri, 22 Jun 2007 20:29:06 -0000 Subject: Ten years on.... Message-ID: <1182544146.098432.113660@m37g2000prh.googlegroups.com> I've been waiting for a month to post this (yesterday), and then I missed it. Oh, well, it's funny and deserves to be republished on its ten-year-and-one-day anniversary. BTW, a member of the ANSI C committee once told me that the only thing rand is used for in C code is to decide whether to pick up the axe or throw the dwarf, and if that's true I guess "the typical libc rand" is adequate for all but the most fanatic of gamers . -- Tim Peters, 21 June 1997. "Belated-but-still-sincerely-admiring-of-Tim-Peters"-ly yrs, Clarence From sbellon at sbellon.de Sun Jun 24 15:04:11 2007 From: sbellon at sbellon.de (Stefan Bellon) Date: Sun, 24 Jun 2007 21:04:11 +0200 Subject: Accessing variable from a function within a function References: <1182710547.921409.212050@w5g2000hsg.googlegroups.com> Message-ID: <20070624210411.3374d072@cube.tz.axivion.com> On Sun, 24 Jun, 7stud wrote: > ef outer(): > a = 10 > def inner(): > print a > > return inner > > > f = outer() > f() > > --output:-- > 10 > >>> def outer(): ... a = 10 ... def inner(): ... a = a + 1 ... print a ... return inner ... >>> f=outer() >>> f() Traceback (most recent call last): File "", line 1, in ? File "", line 4, in inner UnboundLocalError: local variable 'a' referenced before assignment -- Stefan Bellon From spe.stani.be at gmail.com Sat Jun 2 07:22:20 2007 From: spe.stani.be at gmail.com (SPE - Stani's Python Editor) Date: Sat, 02 Jun 2007 04:22:20 -0700 Subject: PythonCard or Dabo? In-Reply-To: <2fv163d2lv8gd9g3qqfbh91a7hraqbbi7v@4ax.com> References: <1174326003.145538.113010@y80g2000hsf.googlegroups.com> <2fv163d2lv8gd9g3qqfbh91a7hraqbbi7v@4ax.com> Message-ID: <1180783340.405317.89630@w5g2000hsg.googlegroups.com> On Jun 2, 7:20 am, Bill Maxwell wrote: > On 19 Mar 2007 10:40:03 -0700, kyoso... at gmail.com wrote: > > ...>You might want to submit this to the wxpython news-group. > > ... > > What is the name of this newsgroup? I can't seem to locate it on my > news server. > > Thanks, > > Bill You probably mean wxPython-users mailing list. You can find more info here: http://www.wxpython.org/maillist.php Another alternative are GUI designers such as wxGlade or XRCed, both of which ship with SPE (http://pythonide.stani.be). Dabo is especially usefull (but not limited to) developping database applications as it is an open source alternative to Visual Fox pro. Stani -- http://www.stani.be From psaffrey at googlemail.com Mon Jun 11 17:56:41 2007 From: psaffrey at googlemail.com (psaffrey at googlemail.com) Date: Mon, 11 Jun 2007 14:56:41 -0700 Subject: bgl Python on Mac OS X Message-ID: <1181599001.291926.102970@w5g2000hsg.googlegroups.com> I'm trying to build this. I've downloaded the boost libraries (version 1.34) and run configure, make and sudo make install without errors. Then I've downloaded bgl-python (0.9) and, as instructed, found the bjam executable from the boost hierarchy, copied it somewhere convenient and run it in the bgl-python directory. That gave me this error: Unable to load Boost.Build: could not find "boost-build.jam" --------------------------------------------------------------- Attempted search from /Users/pzs/incoming/bgl-python-0.9 up to the root and in these directories from BOOST_BUILD_PATH and BOOST_ROOT: /usr/ share/boost-build. Please consult the documentation at 'http://www.boost.org'. So I set $BOOST_ROOT to be the root of the boost 1.34 directory and tried bjam again. This time I get: error: Could not find parent for project at '.' error: Did not find Jamfile or project-root.jam in any parent directory. Any ideas? Peter From steven at REMOVE.THIS.cybersource.com.au Wed Jun 20 02:23:12 2007 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 20 Jun 2007 06:23:12 GMT Subject: Q: listsort and dictsort - official equivalents? References: <1182302544.4202.40.camel@delta.sgr-a.net> Message-ID: On Wed, 20 Jun 2007 02:57:30 +0200, BJ?rn Lindqvist wrote: > It's not true that the sort must complete (or that the whole file must > be read for that matter) That would be a really good trick. How are you supposed to know which item comes first until you've seen them all? -- Steven. From e0427417 at student.tuwien.ac.at Thu Jun 7 10:21:01 2007 From: e0427417 at student.tuwien.ac.at (Mathias Panzenboeck) Date: Thu, 07 Jun 2007 16:21:01 +0200 Subject: Bragging about Python In-Reply-To: References: Message-ID: <46681369$0$12126$3b214f66@tunews.univie.ac.at> Steve Howell schrieb: > --- "pinkfloydhomer at gmail.com" > wrote: > >> Is there a resource somewhere on the net that can be >> used to quickly >> and effectively show Python's strengths to >> non-Python programmers? >> Small examples that will make them go "Wow, that >> _is_ neat"? >> > > 15 small programs here: > > http://wiki.python.org/moin/SimplePrograms > IMHO a few python goodies are missing there. e.g. generator functions: # generic fibonacci without upper bound: def fib(): parent_rabbits, baby_rabbits = 1, 1 while True: yield baby_rabbits parent_rabbits, baby_rabbits = baby_rabbits, parent_rabbits + baby_rabbits # only calculate and print the first 100 fibonacci numbers: from itertools import islice for baby_rabbits in islice(fib(),100): print 'This generation has %d rabbits' % baby_rabbits From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Tue Jun 19 09:23:53 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Tue, 19 Jun 2007 15:23:53 +0200 Subject: Python IDE References: <1182249585.535675.143460@m36g2000hse.googlegroups.com> <1182259143.375798.283620@k79g2000hse.googlegroups.com> Message-ID: <5dq3n9F359hp0U1@mid.individual.net> BartlebyScrivener wrote: > VIM *clap-clap* BTW, are there tutorials on the more arcane vim functions that come in handy with Python? Regards, Bj?rn -- BOFH excuse #168: le0: no carrier: transceiver cable problem? From willmaier at ml1.net Thu Jun 28 17:07:01 2007 From: willmaier at ml1.net (Will Maier) Date: Thu, 28 Jun 2007 16:07:01 -0500 Subject: process stdin grab In-Reply-To: <6151cc730706281301y255e2cefo8d3e2a1f191ee5a0@mail.gmail.com> References: <6151cc730706281301y255e2cefo8d3e2a1f191ee5a0@mail.gmail.com> Message-ID: <20070628210701.GP30401@lass.lfod.us> On Thu, Jun 28, 2007 at 08:01:18PM +0000, Seltzer wrote: > I need to send commands to a process that i did not start. > (mplayer specifically) I have the PIP of the process, and thats > about all. I assume you mean 'PID'. This is somewhat offtopic, but mplayer supports receiving commands from a FIFO: mplayer -quiet -slave -idle -input file=/home/you/.mplayer/fifo Then you can write commands (like 'loadfile song.ogg') to the fifo. Doing this in Python is as trivial as opening, writing to, and closing a file object. > Any ideas on how to do this in python? i need only to write to its > stdin, not read any information from it, and i don't really need > to know if my command worked for now, so error handling isn't > really an issue. I don't know of any magic to write to a running program's stdin. -- [Will Maier]-----------------[willmaier at ml1.net|http://www.lfod.us/] From Pieter.Potgieter at deneldynamics.co.za Tue Jun 5 04:43:04 2007 From: Pieter.Potgieter at deneldynamics.co.za (Pieter Potgieter) Date: Tue, 5 Jun 2007 10:43:04 +0200 Subject: Please help on Binary file manipulation Message-ID: Hi all I have a binary file of about 600kbytes - I want to break it up in file chunks of 1085 bytes - every file must have a new file name. The data is binary video frames (370 frames) - I want to play the data back into an embedded system frame/file by file. I am a complete Python newby - but have C/C++ skills. Please supply/help me with an snippet or example Thanks Pieter ******************************************************************************************************* Disclaimer: The information contained in this communication is confidential and may be legally privileged. It is intended solely for the use of the individual or entity to whom it is addressed and others authorised to receive it. Any review, retransmission, dissemination, copying, disclosure or other use of, or taking of any action in reliance upon, this information by person or entities other then the intended recipient is prohibited. If you have received this message in error, please notify the sender immediately by e-mail, facsimile or telephone and return and/or destroy the original message and all copies from any computer. Denel (Pty) Ltd exercises no editorial control over e-mail messages originating in the organisation and does not accept any responsibility for either the contents of the message or any copyright laws that may have been violated by the person sending this message. Denel (Pty) Ltd is neither liable for the proper and complete transmission of the information contained in this communication nor any delay in its receipt. This message should not be copied or used for any purpose other than intended, nor should it be disclosed to any other person. ******************************************************************************************************* -------------- next part -------------- An HTML attachment was scrubbed... URL: From http Fri Jun 22 11:05:02 2007 From: http (Paul Rubin) Date: 22 Jun 2007 08:05:02 -0700 Subject: "assert" annoyance References: <7xmyys368j.fsf_-_@ruckus.brouhaha.com> <87y7ictlka.fsf@benfinney.id.au> Message-ID: <7xr6o4yqqp.fsf@ruckus.brouhaha.com> Ben Finney writes: > > So I have some assert statements in my code to verify the absence of > > some "impossible" conditions. They were useful in debugging and of > > course I left them in place for "real" runs of the program. Umpteen > > hours into a run, an assertion failed, and of course since failure > > was "impossible", I didn't catch the exception so the whole program > > crashed. > > This is exactly the sort of check which is best done as unit > tests. The program has no 'assert' cruft in it, and the tests can be > as comprehensive as needed without having any impact on the actual > running program. I don't understand what you're trying to say here. The code was tested before I ran it with real data. The asserts triggered because there was a real problem, so removing them would not have been the right thing to do. On the other hand, the code had already been tested without discovering the problem. The problem could not have been found without running the program for hours, not something one would normally do in a unit test, and also it involved an unexpected error from a remote program (a 3GB process had run out of memory). Unit tests are not a magic wand that discover every problem that a program could possibly have. From doulos05 at gmail.com Thu Jun 21 11:03:22 2007 From: doulos05 at gmail.com (JonathanB) Date: Thu, 21 Jun 2007 08:03:22 -0700 Subject: Conceptualizing Threading In-Reply-To: References: <1182433877.742774.321760@p77g2000hsh.googlegroups.com> Message-ID: <1182438202.794266.279170@g4g2000hsf.googlegroups.com> > You described how threads introduce a problem in your program -- that of > generating a sequence of sequential identifiers -- but you didn't describe > the problem that threads are solving in your program. Maybe you don't > need them at all? What led you to threading in the first place? > > Jean-Paul Well, the problem I thought they would solve is ensuring everyone got a sequential number. But I suppose they wouldn't solve that, since from what I gather thread access is somewhat arbitrary. So then, here is the crux of the issue. Worst case scenario, this program could be accessed by 5-10 people at a time and I need each one to have the current information. There are two places I know of that there might be multi-access problems. 1) This program is so that we can track one team passing assignments to another. Right now I have the names of everyone in team 2 in a list. People from team one launch this program and the program grabs a pointer (stored in a separate file). If person A launches the program and person B launches the program before person A assigns an order, they will both have the same pointer, so both orders will go to the same person. 2) Each assignment has a distinct identifier, which increments by 1 for each assignment (SR001001, SR001002, etc). Either these can be assigned manually (the current method), or they can be assigned automatically. If they are assigned manually, I need a way to show them the most recent number (that would be easy), if they are assigned automatically I need a way to save the number and pass the incremented number along (just like the pointer). But I have the same problem here as above. If two people launch the program at roughly the same time, they will pull the same data. Since these assignments tend to come in spurts, concurrent access is likely to be a problem. So, given those parameters (the rest of this program is a breeze, there's a class for each person on Team 2 and the class holds some info about them and a dictionary of assignments with the assignment number for the key and a value of [assigner, numberAssigned], the only other tricky thing for me has been logging because I've never had to do much of it before), how can I prevent these problems? The only thing that jumps out at me is a server/client model where a server runs and compiles all the entries, spitting back the result to each individual client. That way, all the working code lives in the server, ensuring that the working thread always has the right information, while the clients only pass data between the user and the server. But I guess that isn't technically multi-threading is it. From showell30 at yahoo.com Tue Jun 12 18:51:07 2007 From: showell30 at yahoo.com (Steve Howell) Date: Tue, 12 Jun 2007 15:51:07 -0700 (PDT) Subject: Python's "only one way to do it" philosophy isn't good? In-Reply-To: <466f0c2c$0$4157$ba624c82@nntp02.dk.telia.net> Message-ID: <300305.76286.qm@web33511.mail.mud.yahoo.com> --- "Anders J. Munch" <2007 at jmunch.dk> wrote: > > Converting tail-recursion to iteration is trivial, > and perfectly reasonable for > a human to do by hand. You add an outer "while > True"-loop, the recursive call > becomes a tuple assignment, and other code paths end > with a break out of the > loop. Completely mechanical and the resulting code > doesn't even look that bad. > I have to ask the stupid question. If a human can do this completely mechanically, why can't a machine? ____________________________________________________________________________________ Get the Yahoo! toolbar and be alerted to new email wherever you're surfing. http://new.toolbar.yahoo.com/toolbar/features/mail/index.php From venner at gmail.com Fri Jun 22 11:43:46 2007 From: venner at gmail.com (Eric) Date: Fri, 22 Jun 2007 15:43:46 -0000 Subject: newbie question: parsing street name from address In-Reply-To: <1182463419.846372.314550@d30g2000prg.googlegroups.com> References: <1182433644.485185.197690@w5g2000hsg.googlegroups.com> <1182451414.139267.7910@w5g2000hsg.googlegroups.com> <1182463419.846372.314550@d30g2000prg.googlegroups.com> Message-ID: <1182527026.794658.4110@w5g2000hsg.googlegroups.com> On Jun 21, 6:03 pm, John Machin wrote: > On Jun 22, 4:43 am, Eric wrote: > > > > > On Jun 21, 9:47 am, cjl wrote: > > > > P: > > > > I am working on a project that requires geocoding, and have written a > > > very simple geocoder that uses the Google service. > > > > I would like to be able to extract the name of the street from the > > > addresses in my data, however they vary significantly. Here a some > > > examples: > > > > 25 Main St > > > 2500 14th St > > > 12 Bennet Pkwy > > > Pearl St > > > Bennet Rd and Main st > > > 19th St > > > > As you can see, sometimes I have the house number, and sometimes I do > > > not. Sometimes the street name is a number. Sometimes I simply have > > > the names of intersecting streets. > > > > I would like to be able to parse the above into the following: > > > > Main St > > > 14th St > > > Bennet Pkwy > > > Pearl St > > > Bennet Rd > > > Main St > > > 19th St > > > > How might I approach this complex parsing problem? > > > > -CJL > > > You might be able to use consistencies in your data to make this > > simpler. If the examples you have there are representative, it looks > > like what you should do is look for a word like 'St' or 'Rd' and then > > return that word and the previous word. > > The OP's data already contains > [corner|cnr [of]] Foo Rd and|& Bar St > and real world data will contain things like > 1234 John F Kennedy Memorial Drive > 456 Broadway > > As Paul wrote, "Parsing street addresses is a very complex parsing > problem", even when you restrict yourself to one mostly-English- > speaking country. Software written under such restrictions rapidly > breaks down elsewhere (Rue de la Paix, Wilhelmstrasse, Avenida 9 de > Julio, etc) and blows up altogether when street names aren't used in > postal addresses (e.g. Japan). No doubt that address parsing is, in general, a very difficult problem. However, it may not be necessary for him to solve the general problem. If his dataset is more limited in formats then his problem is much simpler. From evan at yelp.com Tue Jun 12 19:20:11 2007 From: evan at yelp.com (Evan Klitzke) Date: Tue, 12 Jun 2007 16:20:11 -0700 Subject: Pattern Classification Frameworks? In-Reply-To: References: Message-ID: On 6/12/07, Steven Bethard wrote: > In fact, a wide variety of classifiers are used in text classification, > including Bayesian approaches, support vector machines, conditional > random fields, etc. > > > Are there any other frameworks I should be aware of? > > I have used (but not recently) Orange: > > http://www.ailab.si/orange > > I haven't used, but have been meaning to try, PyML: > > http://pyml.sourceforge.net/ > > A more recent addition (whose documentation needs work) is: > > http://montepython.sourceforge.net/ > > And here's a Summer of Code project to build an ML library: > > http://projects.scipy.org/scipy/scipy/wiki/MachineLearning > > These are all general-purpose machine learning frameworks. So they can > be applied to pretty much any classification problem (including the text > classification problems you're looking at). You just need to pick out a > set of relevant features to describe your data, and feed those features > along with your chosen labels to a machine learning algorithm. > > STeVe Thanks Steven (and Diez), the projects you pointed me to look like great places to start. -- Evan Klitzke From josiah.carlson at sbcglobal.net Sat Jun 2 03:19:57 2007 From: josiah.carlson at sbcglobal.net (Josiah Carlson) Date: Sat, 02 Jun 2007 07:19:57 GMT Subject: interesting take on python OO In-Reply-To: <1180640052.617845.172400@m36g2000hse.googlegroups.com> References: <1180640052.617845.172400@m36g2000hse.googlegroups.com> Message-ID: 7stud wrote: > http://www.evolt.org/article/OO_programming_the_Python_way/18/449/ > > lol I would have to agree. I could spend time talking about how bad that article was, but instead I will offer useful advice for the new Python programmer. For new users of Python and/or object-oriented programming, stick with the Python Tutorial included with the Python distribution, and/or check out http://www.ibiblio.org/obp/thinkCS/python/english/ . There are some pieces that were obviously translated directly from Java, but it has a lot of good stuff. - Josiah From horpner at yahoo.com Mon Jun 11 13:56:25 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Mon, 11 Jun 2007 17:56:25 GMT Subject: *Naming Conventions* References: <1180909218.939713.112010@q69g2000hsb.googlegroups.com> <1180990280.960271.235550@h2g2000hsg.googlegroups.com> <466699e9$0$2308$426a74cc@news.free.fr> <1181578963.585174.106330@n4g2000hsb.googlegroups.com> Message-ID: On 2007-06-11, Marius Gedminas wrote: > On Jun 6, 3:18 pm, Neil Cerutti wrote: >> > Since 'i' and 'j' are canonically loop indices, I find it >> > totally confusing to use them to name the iteration variable - >> > which is not an index. >> >> Certainly i and j are just as generic, but they have the >> advantage over 'item' of being more terse. > > Python programmers usually prefer readability over terseness. > Finding a variable named 'i' that is not an integer index would > be surprising to me. Terseness and readability can go together in some circumstances, though. But every case should be handled with taste and the application experience, obviously. In a situation where 'i' might be misleading I wouldn't use it. -- Neil Cerutti From anthony_raj at persistent.co.in Thu Jun 21 10:09:34 2007 From: anthony_raj at persistent.co.in (Anthony Raj) Date: Thu, 21 Jun 2007 19:39:34 +0530 Subject: Problem with using ConfigParser.py Message-ID: <8816A57AF3B542A8AC3B12F4E56DB6B0@persistent.co.in> Hi Folks, Having a very strange problem in using python with apache/mod_python. [conf.py attached] >>> from ast.conf import conf >>> c = conf() >>> a = c.readPath('sandbox') >>> len (a) >>> 30 The same code when run thru the a web script gives following error - >>>> [Errno 13] Permission denied: '/home/ast/ast-linux.conf' Mod_python error: "PythonHandler mod_python.publisher" Traceback (most recent call last): File "/usr/lib/python2.4/site-packages/mod_python/apache.py", line 299, in HandlerDispatch result = object(req) File "/usr/lib/python2.4/site-packages/mod_python/publisher.py", line 213, in handler published = publish_object(req, object) File "/usr/lib/python2.4/site-packages/mod_python/publisher.py", line 412, in publish_object return publish_object(req,util.apply_fs_data(object, req.form, req=req)) File "/usr/lib/python2.4/site-packages/mod_python/util.py", line 439, in apply_fs_data return object(**args) File "/var/www/html/ast-sandbox/testConf.py", line 9, in index path = c.readPath('sandbox') File "/usr/lib/python2.4/ast/conf.py", line 40, in readPath self.vars = self.conf.options(target) File "/usr/lib/python2.4/ConfigParser.py", line 241, in options raise NoSectionError(section) NoSectionError: No section: 'sandbox' >>>>> WebScript - ---- import sys from ast.conf import conf def index(req, **kw): sys.stdout = req req.content_type = 'text/html' c = conf() path = c.readPath('sandbox') print path ---- The configuration file is the standard format used by ConfigParser module. The permission for the ast-linux.conf file is the same as the user/group defined in httpd.conf. [root at CVS ast-sandbox]# ls -l /home/ast/ast-linux.conf -rw-rw-rw- 1 777 ast 7936 Jun 21 11:11 /home/ast/ast-linux.conf Any pointers would help. TIA ~Anthony DISCLAIMER ========== This e-mail may contain privileged and confidential information which is the property of Persistent Systems Pvt. Ltd. It is intended only for the use of the individual or entity to which it is addressed. If you are not the intended recipient, you are not authorized to read, retain, copy, print, distribute or use this message. If you have received this communication in error, please notify the sender and delete all copies of this message. Persistent Systems Pvt. Ltd. does not accept any liability for virus infected mails. -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: conf.py URL: From showell30 at yahoo.com Tue Jun 12 19:38:21 2007 From: showell30 at yahoo.com (Steve Howell) Date: Tue, 12 Jun 2007 16:38:21 -0700 (PDT) Subject: Python's "only one way to do it" philosophy isn't good? In-Reply-To: Message-ID: <926685.62883.qm@web33506.mail.mud.yahoo.com> --- Steven D'Aprano wrote: > On Tue, 12 Jun 2007 15:51:07 -0700, Steve Howell > wrote: > > > > > --- "Anders J. Munch" <2007 at jmunch.dk> wrote: > >> > >> Converting tail-recursion to iteration is > trivial, > >> and perfectly reasonable for > >> a human to do by hand. You add an outer "while > >> True"-loop, the recursive call > >> becomes a tuple assignment, and other code paths > end > >> with a break out of the > >> loop. Completely mechanical and the resulting > code > >> doesn't even look that bad. > >> > > > > I have to ask the stupid question. If a human can > do > > this completely mechanically, why can't a machine? > > > They can and do -- some compilers optimize > tail-recursion into iteration. > > Python doesn't, as a deliberate design decision, > because to do so would > lose traceback information. > Ok, that didn't occur to me. What does occur to me, though, is that tracebacks for recursive algorithms can get kind of, well, recursive, so I wonder if there's a tradeoff somewhere. ____________________________________________________________________________________ Looking for a deal? Find great prices on flights and hotels with Yahoo! FareChase. http://farechase.yahoo.com/ From josiah.carlson at sbcglobal.net Sat Jun 9 19:05:11 2007 From: josiah.carlson at sbcglobal.net (Josiah Carlson) Date: Sat, 09 Jun 2007 23:05:11 GMT Subject: Hooking exceptions outside of call stack In-Reply-To: References: <001f01c7aab4$71153940$240110ac@Muse> Message-ID: Warren Stringer wrote: > Am still trying to hook a NameError exception and continue to run. After a > few more hours of searching the web and pouring over Martelli's book, the > closest I've come is: [snip] > Is there a way of intervening as `exec cmd in globals, locals` attempts to > translate 'c' into an object? I thought that trapping a NameError might > work. But now, I'm not so sure. You can always muck around with the function's globals (if the operation is happening inside some function...) >>> def foo(): ... print a ... >>> d = {'a':1} >>> >>> foo = type(foo)(foo.func_code, d, foo.func_name, foo.func_defaults, foo.func_closure) >>> a Traceback (most recent call last): File "", line 1, in ? NameError: name 'a' is not defined >>> foo() 1 >>> With a little work, you can 'merge' your namespace-like object with the module globals that normally exist for a function. However, I would say again, you shouldn't be doing this kind of thing in production code. - Josiah From horpner at yahoo.com Wed Jun 13 08:15:18 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Wed, 13 Jun 2007 12:15:18 GMT Subject: Python's "only one way to do it" philosophy isn't good? References: <1181368143.874341.273140@r19g2000prf.googlegroups.com> <7xy7irxjom.fsf@ruckus.brouhaha.com> <466f0c2c$0$4157$ba624c82@nntp02.dk.telia.net> Message-ID: On 2007-06-12, Anders J. Munch <2007 at jmunch.dk> wrote: > Paul Rubin wrote: >> Steven D'Aprano writes: >>>> Not tail calls, in general, no. >>> Sorry, how does that work? You're suggesting that there is an >>> algorithm which the compiler could follow to optimize away >>> tail-recursion, but human beings can't follow the same >>> algorithm? >>> >>> Now I'm confused. >> >> The usual compiler method is to translate the code into >> continuation-passing style and thereby gain tail-recursion >> optimization automagically. > > There's no need to go into CPS just to optimise tail-recursion. > After all, compilers were optimising tail-calls decades before > Appel's work on SML/NJ. > > Converting tail-recursion to iteration is trivial, and > perfectly reasonable for a human to do by hand. For simple recursive tail calls, yeah, it can be. Translating a tail-recursive Factorial function into a while loop is easy. But tail-call optimization technically works for any tail-call, including mutual recursion, and non-recursive tail-calls. You can't reasonably hand-optimize away the stack frame for all tail-calls. def foo(x) bar(x) The only way to hand-optimize the call to bar is to inline it yourself. -- Neil Cerutti Will the highways on the Internet become more few? --George W. Bush From DustanGroups at gmail.com Thu Jun 14 16:51:35 2007 From: DustanGroups at gmail.com (Dustan) Date: Thu, 14 Jun 2007 20:51:35 -0000 Subject: a_list.count(a_callable) ? In-Reply-To: <1181853479.914070.217270@i13g2000prf.googlegroups.com> References: <1181850818.567840.251090@x35g2000prf.googlegroups.com> <1181853479.914070.217270@i13g2000prf.googlegroups.com> Message-ID: <1181854295.034397.231090@d30g2000prg.googlegroups.com> On Jun 14, 3:37 pm, Dustan wrote: > map and filter are basically obsolete after the introduction of list > comprehensions It is probably worth noting that list comprehensions do not require that you write a new function; they take any expression where appropriate. For more information on list comprehensions, see: http://docs.python.org/tut/node7.html#SECTION007140000000000000000 Generator expressions are the same, except syntactically they have round brackets instead of square, and they return a generator instead of a list, which allows for lazy evaluation. From __peter__ at web.de Sat Jun 9 05:03:08 2007 From: __peter__ at web.de (Peter Otten) Date: Sat, 09 Jun 2007 11:03:08 +0200 Subject: Case-Insensitive Sorting of Multi-Dimensional Lists References: <020e01c7a94c$a7970750$0f01a8c0@desktop9> <1181316575.800182.167640@m36g2000hse.googlegroups.com> <87tztivzt0.fsf@benfinney.id.au> Message-ID: Ben Finney wrote: > mosscliffe writes: > >> I have tried the following, for a one dimensional list and it works, >> but I can not get my head around this lambda. How would this be >> written, without the lamda ? >> >> mylist = ['Fred','bill','PAUL','albert'] >> >> mylist.sort(key=lambda el: el.lower()) > > Here's a hint: > > >>> "FoO".lower() > 'foo' > >>> str.lower("FoO") > 'foo' But be aware that you lose both the ability to override and duck-typing: >>> print r # derived from str Upper East Side >>> print s # unicode M?nchen >>> r.lower(), str.lower(r) ('Lower East Side', 'upper east side') >>> s.lower(), str.lower(s) Traceback (most recent call last): File "", line 1, in TypeError: descriptor 'lower' requires a 'str' object but received a 'unicode' Peter From attn.steven.kuo at gmail.com Mon Jun 4 00:45:08 2007 From: attn.steven.kuo at gmail.com (attn.steven.kuo at gmail.com) Date: Sun, 03 Jun 2007 21:45:08 -0700 Subject: example: 40286 -> 68204 In-Reply-To: <1180916590.000664.249810@z28g2000prd.googlegroups.com> References: <1180916590.000664.249810@z28g2000prd.googlegroups.com> Message-ID: <1180932308.558055.42370@h2g2000hsg.googlegroups.com> On Jun 3, 5:23 pm, Shihpin wrote: > Hi all, > > Is there a fuction that reverse the digits of a number? > > Many thanks, > > Shihpin Lin One can use int, str and a slice: print int(str(40286)[::-1]) -- Hope this helps, Steven From http Fri Jun 29 23:05:10 2007 From: http (Paul Rubin) Date: 29 Jun 2007 20:05:10 -0700 Subject: Python's "only one way to do it" philosophy isn't good? References: <1182750077.570603.160240@q69g2000hsb.googlegroups.com> <7xir9cbm0g.fsf@ruckus.brouhaha.com> <7xejjzmk7u.fsf@ruckus.brouhaha.com> <7xy7i7xjl5.fsf@ruckus.brouhaha.com> <1182872972.417776.78650@o11g2000prd.googlegroups.com> <1182873568.454491.302860@e9g2000prf.googlegroups.com> <7xps3iy73h.fsf@ruckus.brouhaha.com> Message-ID: <7x1wfudtw9.fsf@ruckus.brouhaha.com> Douglas Alan writes: > But that's a library issue, not a language issue. The technology > exists completely within Lisp to accomplish these things, and most > Lisp programmers even know how to do this, as application frameworks > in Lisp often do this kind. The problem is getting anything put into > the standard. Standardizing committees just suck. Lisp is just moribund, is all. Haskell has a standardizing committee and yet there are lots of implementations taking the language in new and interesting directions all the time. The most useful extensions become de facto standards and then they make it into the real standard. From google at gakman.com Tue Jun 19 08:18:04 2007 From: google at gakman.com (google at gakman.com) Date: Tue, 19 Jun 2007 12:18:04 -0000 Subject: static python classes ? In-Reply-To: <1182255355.491845.44770@i13g2000prf.googlegroups.com> References: <1182254405.901790.189190@p77g2000hsh.googlegroups.com> <1182255355.491845.44770@i13g2000prf.googlegroups.com> Message-ID: <1182255484.172960.38850@n15g2000prd.googlegroups.com> > > the python equivalent of what's called in most OOP languages "static > > classes", can you give me a hint ? > > Look for @staticmethod inhttp://docs.python.org/lib/built-in-funcs.html Woops... I misread... -- Gerald Kaszuba http://geraldkaszuba.com From ed at leafe.com Fri Jun 8 09:33:30 2007 From: ed at leafe.com (Ed Leafe) Date: Fri, 8 Jun 2007 09:33:30 -0400 Subject: wxPython / Dabo demo shell ? In-Reply-To: <4866bea60706080559m55a80f50he95c910eb90f90ed@mail.gmail.com> References: <4646a$466901e6$83aef404$30670@news2.tudelft.nl> <4866bea60706080559m55a80f50he95c910eb90f90ed@mail.gmail.com> Message-ID: On Jun 8, 2007, at 8:59 AM, Chris Mellon wrote: > The shell in the wxPython demo (but apparently not in the dabo demo, > as per Ed's email) is from the wx.py package. It's quite trivial to > add to your own applications, documentation is at > http://www.wxpython.org/PyManual.html I may be wrong, but I believe that the OP was interested in the overall frame, contents, and inner workings of the wxPython demo application (and DaboDemo), not the PyShell interpreter. -- Ed Leafe -- http://leafe.com -- http://dabodev.com From saint at spammer.impiccati.it Tue Jun 26 06:06:13 2007 From: saint at spammer.impiccati.it (Gian Uberto Lauri) Date: Tue, 26 Jun 2007 12:06:13 +0200 Subject: The Modernization of Emacs: terminology buffer and keybinding References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182272495.990807.99110@a26g2000pre.googlegroups.com> <87tzt3ihev.fsf@kobe.laptop> <1182370216.961241.6960@n60g2000hse.googlegroups.com> <85zm2ufjpb.fsf@lola.goethe.zz> <1182372592.803332.288260@u2g2000hsc.googlegroups.com> <1182549094.366282.286740@m37g2000prh.googlegroups.com> <87bqf7fwmg.fsf@telesippa.clsnet.nl> <1182553682.197778.138500@g37g2000prf.googlegroups.com> Message-ID: <87r6nzc9nu.fsf@mail.eng.it> >>>>> "n" == nebulous99 writes: n> On Jun 22, 6:32 pm, Cor Gest wrote: >> > HOW IN THE BLOODY HELL IS IT SUPPOSED TO OCCUR TO SOMEONE TO >> ENTER > THEM, GIVEN THAT THEY HAVE TO DO SO TO REACH THE HELP THAT >> WOULD TELL > THEM THOSE ARE THE KEYS TO REACH THE HELP?! >> >> What's your problem ? >> >> Ofcourse a mere program-consumer would not look what was being >> installed on his/her system in the first place ... So after some >> trivial perusing what was installed and where : WOW Look, MA ! >> .... it's all there! >> >> lpr /usr/local/share/emacs/21.3/etc/refcard.ps or your >> install-dir........^ ^ or your >> version.............................^ n> So now we're expected to go on a filesystem fishing expedition n> instead of just hit F1? One small step (backwards) for a man; one n> giant leap (backwards) for mankind. :P Waring, possible ID TEN T detected! There's a program called find, not this intuitive but worth learning It could solve the problem from the root with something like find / -name refcard.ps -exec lpr {} \; 2> /dev/null This line requires some brain and some learning, true, but the documents should be on your HD, unless you avoided installing the man to save space. About the brain, you should have received like me a standard issue one at least (or maybe a better one). >> But then again buying the GNU-book from 'O Reilly would have solved >> it in the utmost nicest possible of ways anyway. n> So much for the "free" in "free software". If you can't actually n> use it without paying money, whether for the software or for some n> book, it isn't really free, is it? GNU books ARE free, and come in both printed and electronic form. No excuses. BTW, buing a GNU book is a good way to finance FSF. And from your too-lazy (ID TEN T like) point of view even freedom itself is not free, since its defence has a cost. -- /\ ___ /___/\_|_|\_|__|___Gian Uberto Lauri_____ //--\| | \| | Integralista GNUslamico \/ e coltivatore diretto di Software A Cesare avrei detto di scrivermi a fnvag at rat.vg From MI5Victim at mi5.gov.uk Fri Jun 8 08:56:48 2007 From: MI5Victim at mi5.gov.uk (MI5Victim at mi5.gov.uk) Date: 8 Jun 2007 12:56:48 GMT Subject: MI5 Persecution: Question and Answer 27/9/95 (2076) Message-ID: In article bu765 at torfree.net "Mike Corley" writes: >>> ##: There were also a few other things said at the trial >>> ##: relating to this which I won't repeat here; it was in the papers >>> ##: at the time anyway. This quote and others said by and about this >>> ##: witness were repeating things that had been said by and about >>> ##: me at around that time. When, where and by whom ? Let's have some details that can be checked. I'm not going to repeat them. They're hurtful to me because they contained abuse that was directed against me by someone else at the time and which got picked up and thrown again in the trial. It is a matter of record but I won't repeat it here. >>> PM: >Who's character is being assassinated? It isn't clear from the post. >>> PM: >Are we talking about Grenville Janner? I thought he was a spook >>> PM: >himself? He's certainly able to hold his own on the issue you cite. >>> ##: Mine, mainly. The reason for putting that episode at the top >>> ##: of the posting is that they tried to kill two birds with one stone >>> ##: at the Beck trial - they simultaneously put words into the mouth >>> ##: of their invented "witness" to smear Janner, and repeated exactly, >>> ##: word-for-word, stuff which had been said by and about me. Why would "they" wish to assassinate your character? Well, let's put it this way - just because this is the first time it's happened in this way, from these people, on this scale, doesn't mean that it hasn't happened before, on a lesser scale. At university there were people who quite overtly hated me and would have wished something nasty to happen to me. Because of where I went making the wrong sort of enemies is pretty deadly. "They" would wish to assassinate my character because it had all been done before, and because they knew I would not be able to react in any other way than I'd reacted previously. >>> ##: They invaded my home with their bugs, they repeated what I >>> ##: was saying in the privacy of my home, and they laughed that it >>> ##: was "so funny", that I was impotent and could not even communicate >>> ##: what was going on. Who did this? Our friends on BBC television, >>> ##: our friends in ITN, last but not least our friends in Capital >>> ##: Radio in London and on Radio 1. Please give details of when, where and by whom these comments were made, so that they can be checked. This was four, five years ago... sorry, I don't remember. I can remember individual incidents, words which were repeated by different people at different times in different locations. Around the end of 1992 Private Eye rtan a front-cover with John and Norma Major, with the title "Major's support lowest ever" and John saying to Norma "Come back norma" on the front cover. What can you read in to that? Not a lot, seems like standard fare for PE. The first time I saw it I was in the pub with some people from work. One was expressing doubts to the other (let's call the first one Simon, shall we? and the second one Phil?) about whether what was going on was right. Phil's answer was that if Private Eye was doing it then it must be ok, "they're usually right". A few days later, again near work, there were some students laughing in the street, "Were you COMING BACK later? But I thought you said you were COMING BACK ha ha ha?" Play on words, you see. Not very nice, either. I had start medication soon afterwards. Clever people, these chaps who think up PE titles. Just slightly lacking in any sense of morality. >>> ##: How did they do this? I'll give you an example. About a year ago, >>> ##: I was listening to Chris Tarrant (Capital Radio DJ among other >>> ##: pursuits) on his radio morning show, when he said, talking about >>> ##: someone he didn't identify, "you know this bloke? he says we're >>> ##: trying to kill him. We should be done for attempted manslaughter" >>> ##: which mirrored something I had said a day or two before. >>> ##: Now that got broadcast to the whole of London - if any recordings >>> ##: are kept of the shows then it'll be there. What was the date of the broadcast ? Out of 2 million plus listeners, why should you be the only one that Tarrant was allegedly referring to ? Sometyime in spring 1994. I can't remember the date, I heard the broadcast in the car - I was going into the office from London that day and just happened to snap on the radio, and hey presto! Mr Tarrant gives us the benefit of his excellent understanding. >>> ##: That's exactly what we did. We went to a competent, professional >>> ##: detective agency in London, paid them over 400 quid to debug our house. >>> ##: They found nothing. What was the name of the detective agency and their address ? I don't see why I should tell you that, but they're in Yellow Pages; they're a well-established outfit. >>> PM: >What? Spend a quarter mil. a year to amuse themselves? And why not >>> PM: >change every now and again? Why keep watching you? (Unless you _are_ >>> PM: >doing something, and I don't think you are, though you may have some >>> PM: >deep, dark secret in your past.) >>> >>> ##: See the above. Is there a deep dark secret in your past ? Apart from "it's all happened before in a different way", no. >>> ##: In a couple of cases people have even known my name - when I was in >>> ##: London over Easter somebody (no idea who they were, just some bloke with >>> ##: his girlfriend) called me by name - quite clearly, and my name is >>> ##: distinctive. Is your name truly Mike Corley, or are you using it as an alias ? It's an alias. I'm not English by ethnic origin. If someone manages to pronounce my name as well as that guy did then they must have been really trying. >>> ##: There's a little story behind this. First of all, in 1992 I worked >>> ##: for a company where the people made clear they knew what was going on, >>> ##: first of all directly (the very first evening I was there I went out to >>> ##: the pub with them and the Technical Director said to another guy, >>> ##: "is this the bloke who's been on TV?" "yeah, I think so") Have you appeared, or been reported by name on TV ? When, where and by whom ? No. Never. Not directly. >>> ##: Also, in summer 1992 I went on a trip abroad to Europe by coach, What was the name of the coach company and your date of departure ? It was a national express coach. At dover we boarded a ferry for Holland somewhere. The company that organized the trip went out of business some time ago, so they won't have records of passengers - so we can't get any corroboration from anyone else that way. We tried all that last summer, ran into a brick wall. The other thing is in summer 1992 I was visibly ill, so other people in the party might remember that more than anyone getting at me on the coach trip. >>> ##: >>Yes, this gets me. I think the answer is that I was set up by >>> ##: >>someone. I was very aware when this started back in 1990 that I >>> ##: >>was being painted as a "threat" to which people had to "react" Why were you being painted as a "threat"; is this related to a "deep,dark, secret" ? Aaaarrrrgh. I think I should make clear that that's their created justification rather than the real reason. They started harassing first and then came up with the reasons for it. >>> >>> ##: I think I know who set me up. Who ? Someone who knew me some time ago. Someone who would have been able to talk this little campaign into existence. >>> ##: The bloke can't even control his own mind without medicine. Is this true ? What is the medication and dosage ? Yes, I'm afraid so. Sulpiride, 200mg a day. It's designed to stop people coming up with the sort of ideas you've heard here for the last few weeks. Give him a higher dose!! In the long term it causes tardive dyskinesia, tardive dementia and general nasty stuff to your brain. So it's three years of sulpiride talking to you here. >-- >john heelan 2076 From michele.simionato at gmail.com Tue Jun 5 23:57:11 2007 From: michele.simionato at gmail.com (Michele Simionato) Date: Wed, 06 Jun 2007 03:57:11 -0000 Subject: web development without using frameworks In-Reply-To: References: <20d6f8950706051201mba83194hcbc4d17cd2439cd@mail.gmail.com> Message-ID: <1181102231.507973.12400@p77g2000hsh.googlegroups.com> On Jun 5, 9:24 pm, Christoph Haas wrote: > On Tue, Jun 05, 2007 at 03:01:01PM -0400, Chris Stewart wrote: > > I'm interested in learning web based python without the use of fancy frameworks > > that are out there. I'm having a hard time coming up with resources and > > examples for this. Does anyone have anything that could be helpful? > > I'd say the only decent ways are either using a full-featured framework > (I favor Pylons) or write plain CGIs. IMO there is a third way: use wsgiref and/or paste. Michele Simionato From bbands at gmail.com Mon Jun 11 17:02:26 2007 From: bbands at gmail.com (BBands) Date: Mon, 11 Jun 2007 21:02:26 -0000 Subject: with as a reserved word In-Reply-To: References: <1181574196.682123.291010@a26g2000pre.googlegroups.com> <1181589497.399747.185440@z28g2000prd.googlegroups.com> Message-ID: <1181595746.068127.4830@g37g2000prf.googlegroups.com> On Jun 11, 12:47 pm, Fredrik Lundh wrote: > estimating what "a lot" is isn't trivial, but it's worth noting that a > search for "lang:python \swith\W" over at google's code search only > brings up about 200 cases, and most of those are found in comments and > string literals. and in Zope. Well then, it would seem that the problems will be minimal. Good. I'll have a look a the gnuplot.py code and post heads-up note to their list. Thanks, jab From jakobsb04 at ru.is Sat Jun 2 14:31:40 2007 From: jakobsb04 at ru.is (Jakob Svavar Bjarnason) Date: Sat, 2 Jun 2007 18:31:40 -0000 Subject: Strange behavior in Windows Message-ID: <8B637660DDD59A40AA725C926CFC3D46035E39E4@nike.hir.is> Greetings. I have been trying to switch to Python from other languages such as Perl and now I have a newbie question. I have been trying to run a setup script to install a python library. To do that I need to run "c:> python setup.py install" but the strange thing is is that when it runs the command: >>> from distutils import log I get the error ONLY while in cmd. If I run this from the interactive shell that comes with IDLE it works. But if I go into the interactive shell in the Windows shell cmd then I get: ImportError: cannot import log Any ideas on how I can fix this Vinsamlega athugi? a? uppl?singar ? t?lvup?sti ?essum og vi?hengi eru eing?ngu ?tla?ar ?eim sem p?stinum er beint til og g?tu innihaldi? uppl?singar sem eru tr?na?arm?l. Sj? n?nar: http://www.ru.is/trunadur Please note that this e-mail and attachments are intended for the named addresses only and may contain information that is confidential and privileged. Further information: http://www.ru.is/trunadur From zaperaj at gmail.com Fri Jun 22 01:51:27 2007 From: zaperaj at gmail.com (zaperaj at gmail.com) Date: Thu, 21 Jun 2007 22:51:27 -0700 Subject: Error while installing Python2.5.1 In-Reply-To: References: <1182413023.924197.302390@o11g2000prd.googlegroups.com> <1182479927.467515.216720@g37g2000prf.googlegroups.com> Message-ID: <1182491487.062013.92940@x35g2000prf.googlegroups.com> So how do i overcome this problem?? How do i access my distribution repositories(if any) or installation media? From jim.tuttle at gmail.com Wed Jun 6 09:26:13 2007 From: jim.tuttle at gmail.com (anthro398) Date: Wed, 06 Jun 2007 06:26:13 -0700 Subject: Who uses Python? In-Reply-To: <1180985830.288414.208850@q69g2000hsb.googlegroups.com> References: <1180985830.288414.208850@q69g2000hsb.googlegroups.com> Message-ID: <1181136373.564647.191170@h2g2000hsg.googlegroups.com> On Jun 4, 3:37 pm, walterbyrd wrote: > I mean other than sysadmins, programmers, and web-site developers? > > I have heard of some DBAs who use a lot of python. > > I suppose some scientists. I think python is used in bioinformatics. I > think some math and physics people use python. > > I suppose some people use python to learn "programming" in general. > Python would do well as a teaching language. > > I would think that python would be a good language for data analysis. > > Anything else? Finance? Web-analytics? SEO? Digital art? I use Python to automate GIS vector and raster processing, to generate and translate metadata, and to build repository ingest objects to feed a digital archive. I'm a librarian and coordinate a federally funded research project, http://www.lib.ncsu.edu/ncgdap/ We also have another Python developer in the library who use it to process data and metadate for various library catalog functions. From roy at panix.com Wed Jun 27 08:58:59 2007 From: roy at panix.com (Roy Smith) Date: Wed, 27 Jun 2007 08:58:59 -0400 Subject: Too many 'self' in python.That's a big flaw in this language. References: <1182942154.185461.89620@e9g2000prf.googlegroups.com> <1182946294.941781.115350@n2g2000hse.googlegroups.com> Message-ID: faulkner wrote: > http://www.voidspace.org.uk/python/weblog/arch_d7_2006_12_16.shtml#e584 I looked the "Selfless Python" idea described there, and I think it's a REALLY bad idea. It's a clever hack, but not something I would ever want to see used in production code. Sure, it saves a little typing, but it invokes a lot of magic and the result is essentially a new language and everybody who uses this code in the future will have to scratch their heads and figure out what you did. Programs get written once. They get read and maintained forever, by generations of programmers who haven't even been hired by your company yet. Doing some clever magic to save a few keystrokes for the original programmer at the cost of sowing confusion for everybody else in the future is a bad tradeoff. From larry.bates at websafe.com Fri Jun 1 20:23:34 2007 From: larry.bates at websafe.com (Larry Bates) Date: Fri, 01 Jun 2007 19:23:34 -0500 Subject: Using PIL to find separator pages In-Reply-To: References: <4660406F.7070506@websafe.com> Message-ID: Steve Holden wrote: > Larry Bates wrote: >> Steve Holden wrote: >>> Larry Bates wrote: >>>> I have a project that I wanted to solicit some advice >>>> on from this group. I have millions of pages of scanned >>>> documents with each page in and individual .JPG file. >>>> When the documents were scanned the people that did >>>> the scanning put a colored (hot pink) separator page >>>> between the individual documents. I was wondering if >>>> there was any way to utilize PIL to scan through the >>>> individual files, look at some small section on the >>>> page, and determine if it is a separator page by >>>> somehow comparing the color to the separator page >>>> color? I realize that this would be some sort of >>>> percentage match where 100% would be a perfect match >>>> and any number lower would indicate that it was less >>>> likely that it was a coverpage. >>>> >>>> Thanks in advance for any thoughts or advice. >>>> >>> I suspect the easiest way would be to select a few small patches of each >>> image and average the color values of the pixels, then normalize to hue >>> rather than RGB. >>> >>> Close enough to the hue you want (and you could include saturation and >>> intensity too, if you felt like it) across several areas of the page >>> would be a hit for a separator. >>> >>> regards >>> Steve >> >> Steve, >> >> I'm completely lost on how to proceed. I don't know how to average color >> values, normalize to hue... Any guidance you could give would be greatly >> appreciated. >> >> Thanks in advance, >> Larry > > I'd like to help but I don't have any sample code to hand. Maybe someone > who does could give you more of a clue. Let's hope so, anyway ... > > regards > Steve I think I've come up with something that will work. I use PIL Image.getcolors() to get colors and take the top 10 colors of my background page. I then calculate the average of the R, G, B components. That becomes my reference. Then I read a page and make the same calculation. I then calculate the absolute value of the difference of R, G, B of the two values. Sum those together gives something like the average difference between the two average colors (at least that is what I think it does). This seems to give me small numbers when the pages are the same and large numbers when they are different. It isn't super fast but it is working. Thanks for pushing me in the right direction. -Larry From jensthiede at gmail.com Fri Jun 15 23:35:47 2007 From: jensthiede at gmail.com (Jens Thiede) Date: Fri, 15 Jun 2007 20:35:47 -0700 Subject: Looking for a wxPython GUI builder In-Reply-To: References: Message-ID: <1181964947.369982.320630@c77g2000hse.googlegroups.com> On Jun 16, 3:18 am, Dick Moores wrote: > How about SPE? > > Any others? > > And which ones do people > actually use? Commercial or Freeware. > > Thanks, > > Dick Moores There's Boa Constructor... (http://boa-constructor.sourceforge.net/ Screenshots). I haven't actually used it though. From jjl at pobox.com Wed Jun 6 16:52:35 2007 From: jjl at pobox.com (John J. Lee) Date: Wed, 06 Jun 2007 20:52:35 GMT Subject: Basic Auth for simple web server References: <46657315$0$10618$4fafbaef@reader2.news.tin.it> Message-ID: <87abvc4xg8.fsf@pobox.com> Marco Aloisio writes: > Hi, I'm a Python newbie; > I have to write a simple webserver, and I need to > implement a basic authentication as specified in the RFC2617. > I wonder if there is a Python library for doing that. twisted.web2 is one. John From Eric_Dexter at msn.com Wed Jun 20 18:49:55 2007 From: Eric_Dexter at msn.com (Eric_Dexter at msn.com) Date: Wed, 20 Jun 2007 15:49:55 -0700 Subject: subprocess.popen question In-Reply-To: References: <1182353267.200998.43900@w5g2000hsg.googlegroups.com> Message-ID: <1182379795.144599.22520@n60g2000hse.googlegroups.com> On Jun 20, 1:46 pm, "Gabriel Genellina" wrote: > En Wed, 20 Jun 2007 12:27:47 -0300, Eric_Dex... at msn.com > escribi?: > > > I am trying to modify a programming example and I am coming up with > > two problems... first is that I can't seem to pass along the > > arguments to the external command (I have been able to do that with > > the old module and cmd is the command I wish to try) all the output > > seems to be returned as one line (at least when I run the program in > > spe). > > > import subprocess > > from os import system > > cmd = """gawk -f altertime.awk -v time_offset=4 -v > > outfile="testdat.sco" "i1.sco" """ > > #subprocess.Popen. > > last_line = subprocess.Popen(['gawk.exe'], > > stdout=subprocess.PIPE).communicate()[0] > > You build what appears to be the desired command line, but execute > gawk.exe instead. > Better split the arguments beforehand: > cmd = ["gawk", "-f", "altertime.awk", "-v", "time_offset=4", "-v", > "outfile=testdat.sco", "i1.sco"] > Now, what do you want to do with the output? Printing it line by line? > output = subprocess.Popen(cmd, stdout=subprocess.PIPE).communicate()[0] > lines = output.splitlines() > for line in lines: > print line > > -- > Gabriel Genellina I had one test where I had cmd in place of gawk and one everything was in place of gawk.. I haven't tried what you have listed yet (I am getting ready to go to work so may have to wait until tommorow to try it) THanks for the help From martin at v.loewis.de Thu Jun 28 13:28:06 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Thu, 28 Jun 2007 19:28:06 +0200 Subject: 16bit hash In-Reply-To: References: <46833DC0.3050503@v.loewis.de> Message-ID: <4683efa6$0$23885$9b622d9e@news.freenet.de> > I'm trying to create UniqueID's for dynamic postscript fonts. According > to my resources we don't actually need to use these, but if they are > required by a particular postscript program (perhaps to make a print run > efficient) then the private range of these ID's is 4000000<=UID<=4999999 > ie a range of one million. > > So I probably really need an 18 bit hash I don't fully understand the example, but ISTM that "no, you don't need a hash at all. You need a unique identification". > The data going into the font consists of > > fontBBox '[-415 -431 2014 2033]' > charmaps ['dup (\000) 0 get /C0 put',......] > metrics ['/C0 1251 def',.....] > bboxes ['/C29 [0 0 512 0] def',.......] > chardefs ['/C0 {newpath 224 418 m 234 336 ......def}',......] > > ie a bunch of lists of strings which are eventually joined together and > written out with a template to make the postscript definition. And the UniqueID should be unique within this file, right? Why don't you just use a serial number then? Regards, Martin From aleax at mac.com Fri Jun 15 10:40:32 2007 From: aleax at mac.com (Alex Martelli) Date: Fri, 15 Jun 2007 07:40:32 -0700 Subject: dynamically generated runtime methods & reflection References: <467277fc$0$21230$426a74cc@news.free.fr> Message-ID: <1hzqn43.3l62fu518knjN%aleax@mac.com> Bruno Desthuilliers wrote: > Josiah Carlson a ?crit : > (snip) > > Well, the particular operation is typically called 'currying a > > function', > > > it's not 'currying' but 'partial application'. > > Currying is somehow the reverse of partial : it's a way of building a > multiple-args function from single-args functions. > Wikipedia says "currying or Sch?nfinkelisation[1] is the technique of transforming a function that takes multiple arguments into a function that takes a single argument" -- and FWIW I agree with Wikipedia in this case; the reverse (going from single-arg to multiple-args) would be "uncurrying", though I don't think I've ever used that term myself. functools.partial's name may be more precise (because it can, e.g., go from a function taking 3 arguments to one taking 2 -- not just from N down to 1) but your 'pedantic' remark seems pedantically wrong:-). Alex From gagsl-py2 at yahoo.com.ar Wed Jun 13 16:01:38 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 13 Jun 2007 13:01:38 -0700 Subject: In C extension .pyd, sizeof INT64 = 4? In-Reply-To: <466efcdf$0$13674$9b622d9e@news.freenet.de> References: <1181642594.963433.132750@g37g2000prf.googlegroups.com> <466efcdf$0$13674$9b622d9e@news.freenet.de> Message-ID: <1181764898.324494.3290@x35g2000prf.googlegroups.com> On 12 jun, 17:06, "Martin v. Lo"wis" wrote: > > What *is*INT64? It's not a builtin type of standard C, it isn't > defined by Microsoft C, and it isn't predefined by Python. > > So it must be something that you have defined, and apparently > incorrectly. How did you define it? It is defined in basetsd.h, included by winnt.h; the OP should not redefine it, and that also explains why I could compile my test program without any problem. -- Gabriel Genellina From WThomas at gsmc.org Fri Jun 15 11:48:01 2007 From: WThomas at gsmc.org (Wiley Thomas) Date: Fri, 15 Jun 2007 10:48:01 -0500 Subject: No subject Message-ID: <6F773C5D529B0148AE6EB025F9871F4701D39EE2@gsmcmail01.corp.gsmc.org> I'm trying to write a script to open a file on our (windows) network. The file is located on a machine that is not part of the domain and requires a separate user id and password to access. I tried using urllib2 and the password_manager to authenticate but as some point urllib2 sees I'm trying to access a local file and passes it off to os. The error message I get is: "WindowsError: [Error 1326] Logon failure: unknown user name or bad password: From orsenthil at gmail.com Mon Jun 25 10:06:04 2007 From: orsenthil at gmail.com (Phoe6) Date: Mon, 25 Jun 2007 07:06:04 -0700 Subject: New Thread- Supporting Multiline values in ConfigParser Message-ID: <1182780364.650693.10430@w5g2000hsg.googlegroups.com> Hi, Am starting a new thread as I fear the old thread which more than a week old can go unnoticed. Sorry for the multiple mails. I took the approach of Subclassing ConfigParser to support multiline values without leading white-spaces, but am struct at which position in _read I should modify to accomodate the non-leading whitespace based multiline values. I can guess, this portion in the _read function will require change, any change to this affects the whole of parsing. :-( Can someone who has done this before or understands ConfigParser better help me? # Section I am talking about if line[0].isspace() and cursect is not None and optname: value = line.strip() if value: cursect[optname] = "%s\n%s" % (cursect[optname], value) # _read method def _read(self, fp, fpname): cursect = None optname = None lineno = 0 e = None while True: line = fp.readline() if not line: break lineno = lineno + 1 # comment or blank line? if line.strip() == '' or line[0] in '#;': continue if line.split(None, 1)[0].lower() == 'rem' and line[0] in "rR": # no leading whitespace continue # continuation line print "line:%s\tcursect:%s\toptname:%s"% (line,cursect,optname) if line[0].isspace() and cursect is not None and optname: value = line.strip() if value: cursect[optname] = "%s\n%s" % (cursect[optname], value) # a section header or option header? else: # is it a section header? mo = self.SECTCRE.match(line) if mo: sectname = mo.group('header') if sectname in self._sections: cursect = self._sections[sectname] elif sectname == ConfigParser.DEFAULTSECT: cursect = self._defaults else: cursect = {'__name__':sectname} self._sections[sectname] = cursect # So sections can't start with a continuation line optname = None elif cursect is None: raise ConfigParser.MissingSectionHeaderError(fpname, lineno, line) # an option line? else: mo = self.OPTCRE.match(line) if mo: optname, vi, optval = mo.group('option','vi','value') if vi in ('=',':') and ';' in optval: # ';' is a comment delimiter only if it follows # a spacing character pos = optval.find(';') if pos != -1 and optval[pos-1].isspace(): optval = optval[:pos] optval = optval.strip() # allow empty values if optval == '""': optval = '' optname = self.optionxform(optname.rstrip()) cursect[optname] = optval else: if not e: e = ConfigParser.ParsingError(fpname) e.append(lineno, repr(line)) if e: raise e -- Senthil From krzysztof.wlodarczyk at mobiltek.pl Wed Jun 20 06:50:07 2007 From: krzysztof.wlodarczyk at mobiltek.pl (=?UTF-8?B?S3J6eXN6dG9mIFfFgm9kYXJjenlr?=) Date: Wed, 20 Jun 2007 12:50:07 +0200 Subject: Python/C API bug (multithreading) In-Reply-To: References: Message-ID: <4679065F.2030400@mobiltek.pl> Nick Craig-Wood pisze: > Krzysztof W?odarczyk wrote: > >> I think I've found a bug in Python/C API and multithreading. >> > > You don't state your python version. > > There is an old bug about a similar issue :- > > http://mail.python.org/pipermail/python-dev/2005-May/053840.html > http://sourceforge.net/tracker/index.php?func=detail&aid=1163563&group_id=5470&atid=105470 > > >> >>This is apparantly fixed in 2.4.2 despite the absence of anentry in the NEWS for that release. >> Python 2.4.1 and 2.4.4 - the same problem exists :( >> Is there any simple way to fix this damned bug?? >> > > Locking, locking and more locking ;-) > > damn true brother, thx -- Krzysztof W?odarczyk Centrum Technologii Mobilnych Mobiltek S.A. e-mail: krzysztof.wlodarczyk at mobiltek.pl mobile: 502-525-035 This email is confidential and is intended for receipt solely by the individual or entity to which it is addressed. Any review, use, retention, distribution or disclosure by others is strictly prohibited. If you are not the intended recipient (or authorized to receive for the recipient), please contact the sender by reply email and delete all copies of this message. Thank you. From steve at laniels.org Wed Jun 20 17:22:03 2007 From: steve at laniels.org (Stephen R Laniel) Date: Wed, 20 Jun 2007 17:22:03 -0400 Subject: PEP 3107 and stronger typing (note: probably a newbie question) In-Reply-To: References: <1182369568.941307.316260@p77g2000hsh.googlegroups.com> Message-ID: <20070620212203.GA2837@slaniel-laptop.itasoftware.com> On Wed, Jun 20, 2007 at 09:41:09PM +0100, Michael Hoffman wrote: > If you asked Java programmers why you couldn't turn *off* Java's static > type checking if you wanted to, you'd probably get a similar response. Perhaps it would help for me to explain what I'd like. Under both Perl and Python, I've found myself having/wanting to write things like so: def my_func( int_arg, str_arg ): try: int_arg = int( int_arg ) str_arg = str( str_arg ) except ValueError: sys.stderr.write( "Args are not of the right type\n" ) sys.exit(1) Granted, in a dynamic language we won't always (maybe "won't often") have a situation where the types are known this well at compile time. But sometimes we will. And it would be nice to catch these before the program even runs. So my question is: would bolting on "static type checking when we can, no type checking when we can't" be too much to ask? My reason for asking initially was that the PEP adds all kinds of information to the function prototype -- e.g. (quoting from there) def foobar( a: Integer, b: Sequence ) -> String: so why not, I reasoned, use this information at compile time? Of course I understand the virtue of writing code with good doctests, etc. But my question is why we can't get some more static typing as well. Given the tools that'll be in Python 3.0, that doesn't seem unreasonable to ask. Apparently it is unreasonable. I'm sorry I asked. -- Stephen R. Laniel steve at laniels.org Cell: +(617) 308-5571 http://laniels.org/ PGP key: http://laniels.org/slaniel.key From ken at seehart.com Fri Jun 22 17:00:02 2007 From: ken at seehart.com (Ken Seehart) Date: Fri, 22 Jun 2007 14:00:02 -0700 Subject: C wrappers and the proxy dilemma Message-ID: <467C3852.9020606@seehart.com> Anyone who has wrapped C or C++ libraries has encountered the proxy dilemma. A long time ago, I naively thought that I could start by deriving my high level python class from the c-python type, but this leads to many difficult problems because several of the underlying methods return the low level objects. After reading up on the subject, I learned that the "correct" solution is to use composition rather than inheritance. It makes sense, but it is nevertheless rather annoying. An excellent example of this is the wxPython library, which uses composition (proxies) and even solves the OOR (original object return) problem that is associated with this kind of proxy oriented solution. Conclusion: There is no really good solution to this kind of thing that doesn't get messy. Wrapping C or C++ in python becomes difficult whenever you have methods that return (or take as arguments) instances of the objects that you are trying to wrap in high level python. Any solution seems to add more overhead than is desirable (in terms of both programmer time and run time). This problem comes up over and over again, so perhaps it is even worth a PEP if a change to the python language would facilitate a more convenient solution to this nagging problem. First, mentally set aside the idea of using composition. I understand the set of problems that it solves, but it also creates a new set of problems (such as function call overhead on every method call). I also understand why composition is better than inheritance. But in order to contemplate this proposal, it is necessary to temporarily set aside the composition idea. This proposal involves taking another look at something slightly more akin to the inheritance approach that we all gave up on before. Okay, so here is a somewhat radical proposal: Add a writable __overload__ attribute to low level python type. This would be assigned a python 'type' instance (or None to have no effect). The effect is to place __overload__ at the /beginning /of the __mro__ of the low level type, making it possible to directly alter the behavior of the base python type without using inheritance. This means that instances of the base type acquire the attributes of our high level python class. It is important that the __overload__ type is checked /before /the actual type. Yeah, it sounds a bit scary at first. A bit too loose maybe. So the type definition should have to explicitly enable this feature to prevent people from doing bad things. But dwelling too much on the scariness seems somewhat non-pythonic. It is more important that we can do really good things than that we prevent ourselves from going out of our way to do bad things (as long as it is not too /easy /to do bad things). So here are some of the benefits: 1. Eliminates the duality between proxy objects and low level objects. 2. Increased speed on methods whose syntaxes are not being altered (because no wrapper is needed). 3. Much less work than writing wrappers for every method (even if such a task is partially automated). Usage example: from foolib import c_foo class Foo(c_foo): """Overload of c_foo""" def __new__(typ, *args, **kwargs): return c_foo(*args, **kwargs) def __init__(self, parrot_state): c_foo.__init__(self) self.parrot_state = parrot_state def myfunc(self): return 5 * self.juju(self.parrot_state) # juju method is defined in foolib # This makes all c_foo instances into Foo instances: Poof! c_foo.c_footype.__overload__ = Foo x = Foo('not dead yet') # actually creates a c_foo instance that looks like a Foo instance # c_foo.Add is defined in foolib and takes c_foo instances x.Add(Foo('strange')) x.Add(Foo('missing')) # c_foo.GetChildren is defined in foolib and returns c_foo instances for y in x.GetChildren(): print y.myfunc() # Wow, I am magically accessing Foo.myfunc Yeah I know, that's an infinitely recursive inheritance; but that's okay, we just implement the __overload__ feature such that the MRO thingy will do the right thing for us. The semantics will be that Foo is derived from c_foo, and all instances of c_foo behave as if the are instances of Foo. I used the term "radical" earlier, to describe this idea. What I meant was that it seems to violate some basic Object Oriented principles. However, when evaluating solutions I try not to apply any principles too dogmatically. Theory is only relevant when it has /practical /consequences. So I recommend not quoting theory without also defending the relevance of the theory to the case in point. IMO, anything that eliminates thousands of lines of boilerplate code is worth bending theory a little. Is it possible to get the same syntactic/semantic results without changing python? - Ken -------------- next part -------------- An HTML attachment was scrubbed... URL: From JoeSalmeri at hotmail.com Tue Jun 5 19:23:45 2007 From: JoeSalmeri at hotmail.com (Joe Salmeri) Date: Tue, 5 Jun 2007 19:23:45 -0400 Subject: PATH or PYTHONPATH under Windows ??? References: <90155$4665db45$d443bb3a$16812@news.speedlinq.nl> Message-ID: Modify the PATHEXT environment variable to include .py; For example the default one on Windows XP is: PATHEXT=.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH; Modify it so it says: PATHEXT=.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.py Now you can run python programs from your cmd prompt by just typing in the script name (with or without the .py) Instead of adding directories to your path so that you can easily run programs (like python) try this instead. Use notepad to create a file named alias. Add lines to that file for the shortcuts you want. For instance here is the shortcut I have for Python p = P:\SW\python\python.exe $* Modify the shortcut on the start menu for the command prompt from %SystemRoot%\system32\cmd.exe /k doskey /macrofile=P:\SW\JoeUtil\Alias to %SystemRoot%\system32\cmd.exe /k doskey /macrofile=\alias Now when you use that shortcut for the command prompt it will run doskey which will load your alias file. With the above setup you can just type p at the cmd prompt to get the interactive python prompt. Since I have two versions of python installed right now I have another alias setup pold = P:\SW\python.2.4.2\python.exe $* This allows me to compare differences between the two versions of python. "Stef Mientki" wrote in message news:90155$4665db45$d443bb3a$16812 at news.speedlinq.nl... > hello, > > after cleaning up a PC, Python can't find any libraries anymore. > But happily I've still one PC, where Python is running perfect. > Now I always read about the environment variable "PYTHONPATH". > But on neither PC there exists a "PYTHONPATH". > > On the PC that works ok, > there is the standard "PATH" environment variable, > and indeed there are all the Python Library references. > > Please enlighten me. > > thanks, > Stef Mientki From grante at visi.com Tue Jun 5 17:19:19 2007 From: grante at visi.com (Grant Edwards) Date: Tue, 05 Jun 2007 21:19:19 -0000 Subject: how to print out each single char from a string in HEX format? References: <1180998219.005688.323200@r19g2000prf.googlegroups.com> <1181001782.216372.78410@r19g2000prf.googlegroups.com> <4665d1c9$0$52190$edfadb0f@dread11.news.tele.dk> Message-ID: <136bkqndsffpf80@corp.supernews.com> On 2007-06-05, Troels Thomsen wrote: > with the printf inspired solution you can set the precision like this: > >>>> a = "12\n34" >>>> for c in a: > ... print "%#04x" % ord(c), > ... > 0x31 0x32 0x0a 0x33 0x34 And if you just want to do the conversion w/o printing: >>> a = "12\n34" >>> ' '.join(('%#04x' % ord(c) for c in a)) '0x31 0x32 0x0a 0x33 0x34' >>> ' '.join(('%02x' % ord(c) for c in a)) '31 32 0a 33 34' -- Grant Edwards grante Yow! Vote for ME -- I'm at well-tapered, half-cocked, visi.com ill-conceived and TAX-DEFERRED! From steve at holdenweb.com Fri Jun 1 12:28:33 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 01 Jun 2007 12:28:33 -0400 Subject: unknown host In-Reply-To: <1180703347.753746.17070@o5g2000hsb.googlegroups.com> References: <1180703347.753746.17070@o5g2000hsb.googlegroups.com> Message-ID: abcd wrote: > I have a linux machine (ip = 10.10.10.8), which can ping other > machines on the same subnet...such as > > 10.10.10.1 > 10.10.10.2 > 10.10.10.5 > 10.10.10.6 > 10.10.10.254 > > If I use socket.gethostbyaddr() I get back results when ip is > 10.10.10.1 and 10.10.10.254 but for the other IP addresses > (10.10.10.5, .6, etc) I get back "unknown host". In fact I get > "unknown host" for the linux machine that I run the gethostbyaddr > from. > > If perform the same operation from a windows machine (ip = 10.10.10.5) > it returns data for the other IP addresses as expected. > > any ideas? > Probably the Windows hosts are resolving the addresses to names using WINS, a NetBIOS-over-TCP compatible naming service, while the Unix hosts are trying to use the DNS. If you could arrange for your hosts to register on the DNS automatically that might solve the problem. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden ------------------ Asciimercial --------------------- Get on the web: Blog, lens and tag your way to fame!! holdenweb.blogspot.com squidoo.com/pythonology tagged items: del.icio.us/steve.holden/python All these services currently offer free registration! -------------- Thank You for Reading ---------------- From duncan.booth at invalid.invalid Mon Jun 25 04:46:22 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 25 Jun 2007 08:46:22 GMT Subject: urllib interpretation of URL with ".." References: <467cc85f$0$3039$9b622d9e@news.freenet.de> Message-ID: "Martin v. L?wis" wrote: >> Is "urllib" wrong? > > I can't see how. HTTP 1.1 says that the parameter to the GET > request should be an abs_path; RFC 2396 says that > /../acatalog/shop.html is indeed an abs_path, as .. is a valid > segment. That RFC also has a section on relative identifiers > and normalization; it defines what .. means *in a relative path*. > > Section 4 is explicit about .. in absolute URIs: > # The syntax for relative URI is a shortened form of that for absolute > # URI, where some prefix of the URI is missing and certain path > # components ("." and "..") have a special meaning when, and only when, > # interpreting a relative path. > > Notice the "and only when": the browsers who modify above > URL before sending it seem to be in clear violation of > RFC 2396. Section 5.2 is also relevant here. In particular: > g) If the resulting buffer string still begins with one or more > complete path segments of "..", then the reference is > considered to be in error. Implementations may handle this > error by retaining these components in the resolved path (i.e., > treating them as part of the final URI), by removing them from > the resolved path (i.e., discarding relative levels above the > root), or by avoiding traversal of the reference. The common practice seems to be for client-side implementations to handle this using option 2 (removing them) and servers to use option 3 (avoiding traversal of the reference). urllib uses option 1 which is also correct but not as useful as it might be. From doug at alum.mit.edu Fri Jun 22 01:43:54 2007 From: doug at alum.mit.edu (Douglas Alan) Date: Fri, 22 Jun 2007 01:43:54 -0400 Subject: Python's "only one way to do it" philosophy isn't good? References: <1181368143.874341.273140@r19g2000prf.googlegroups.com> <7x3b0nmkk6.fsf@ruckus.brouhaha.com> Message-ID: "Terry Reedy" writes: > | It allows the community to develop language features in a modular way > | without having to sully the code base for the language itself. > [etc] > Some of the strongest opposition to adding macros to Python comes > from people like Alex Martelli who have had experience with them in > *multi-person production* projects. He claimed in various posts > that the net effect was to reduce productivity. So convince us (and > Guido!) that he is wrong ;-) I'm not convinced that Guido is wrong because I know that he has at least occasionally mused that he might someday consider a macro facility for Python. Alex Martelli, on the other hand, although an extremely smart guy, seems to me to often be over-opinionated and dismissive. Regarding being on a project where people used macros poorly, I've also been on projects where people did a poor job of OO design, and a non-OO design would have been better than the crappy OO design that was ultimately used. Does that mean that we should remove the OO features from Python? Paul Graham made it rich implementing Yahoo Stores in Lisp, and claims that heavy use of macros is one of the reasons that he was able to stay well-ahead of all the competition. So, maybe Paul and Alex can duke it out. Personally, I like Paul's style better. And he's made a lot more money using his theory of software design. > But I would prefer you somehow try to help make usable multi-arg and > predicate dispatch a reality. Alas, I can't stand programming in C, so there's no way I'm going to dive that deeply into the CPython code base. If I could help implement it in Python itself, using a good macro facility, sign me up! |>oug From bj_666 at gmx.net Mon Jun 4 03:17:26 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Mon, 04 Jun 2007 09:17:26 +0200 Subject: Dict naming, global vs local imports, etc. [was Re: *Naming Conventions*] References: <1180911610.702985.215970@q75g2000hsh.googlegroups.com> Message-ID: In <1180911610.702985.215970 at q75g2000hsh.googlegroups.com>, George Sakkis wrote: > While we're at it, although it's not strictly a naming convention > issue I still waste brain cycles on where to put the import statements > that are used only once or twice in a module. Should > (1) all imports be at the global scope at the top of the module, or > (2) be imported in the function or method they are actually used ? > > [?] > > Reasons for (2) > --------------- > - Point of import closer to point of use; easy to notice if a given > import is not used any more after refactoring. `pylint` reports unused imported names. I don't follow PEP8 only if it's not possible otherwise. But cyclic imports are bad anyway. :-) And if the import is *really* expensive and only needed in some special circumstances. Ciao, Marc 'BlackJack' Rintsch From oscartheduck at gmail.com Mon Jun 25 17:41:04 2007 From: oscartheduck at gmail.com (oscartheduck) Date: Mon, 25 Jun 2007 14:41:04 -0700 Subject: regular expressions eliminating filenames of type foo.thumbnail.jpg In-Reply-To: <1182750220.486035.298890@o11g2000prd.googlegroups.com> References: <1182746933.413693.103860@p77g2000hsh.googlegroups.com> <1182747645.092002.68800@x35g2000prf.googlegroups.com> <1182750220.486035.298890@o11g2000prd.googlegroups.com> Message-ID: <1182807664.730854.28160@g37g2000prf.googlegroups.com> I eventually went with: #!/usr/bin/env python from PIL import Image import glob, os, re size = 128, 128 def thumbnailer(dir, filenameRx): for picture in [ p for p in os.listdir(dir) if os.path.isfile(os.path.join( dir,p)) and filenameRx.match(p) if 'thumbnail' not in p]: file, ext = os.path.splitext(picture) im = Image.open (picture) im.thumbnail(size, Image.ANTIALIAS) im.save(file + ".thumbnail" + ext) jpg = re.compile(".*\.(jpg|jpeg)", re.IGNORECASE) thumbnailer(".", jpg) Thanks for the help! From jimbomaan at gmail.com Wed Jun 13 01:04:23 2007 From: jimbomaan at gmail.com (why?) Date: Wed, 13 Jun 2007 05:04:23 -0000 Subject: How to save python codes in files? Message-ID: <1181711063.512249.289520@x35g2000prf.googlegroups.com> Im working with Python 2.2 on my red hat linux system. Is there any way to write python codes in separate files and save them so that i can view/edit them in the future? Actually I've just started with python and would be grateful for a response. Thanx! From gnewsg at gmail.com Tue Jun 19 17:06:40 2007 From: gnewsg at gmail.com (billiejoex) Date: Tue, 19 Jun 2007 14:06:40 -0700 Subject: How can I know the name of "caller" In-Reply-To: References: <1182285024.048003.310120@n2g2000hse.googlegroups.com> Message-ID: <1182287200.071007.112170@g4g2000hsf.googlegroups.com> On 19 Giu, 22:50, Stefan Sonnenberg-Carstens wrote: > billiejoex schrieb: > > > > > Hi there, > > unfortunately, I'm compelled to apply a sort of monkey patching at the > > code of an existing libreary that I can't modify directly. > > Here's my question > > Having such code: > > > class test: > > > def caller(self): > > self.b() > > > def called(self): > > pass > > > ...(if it is possible) how can I get, from method "called", the name > > of function/method that called it (in this case "caller")? > > > Thanks in advance > > inspect.stack is your friend ;-)- Nascondi testo tra virgolette - > > - Mostra testo tra virgolette - Thank you man. That's what I was searching for. This should be production code. Is insepct.stack fast enough? Considering that I'd have to use inspect.stack inside a 'while' statement looping different times, I wouldn't slow down my application. From cam.ac.uk at mh391.invalid Wed Jun 20 08:29:47 2007 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Wed, 20 Jun 2007 13:29:47 +0100 Subject: DFW Pythoneers Meeting THIS Saturday In-Reply-To: <1182337167.504241.131530@m36g2000hse.googlegroups.com> References: <1182325553.232470.205970@q75g2000hsh.googlegroups.com> <1182337167.504241.131530@m36g2000hse.googlegroups.com> Message-ID: peter wrote: >> It says right in the subject line! DFW. If you don't know what DFW >> means, then it's probably not your local area. > > Precisely Precisely what? You complained that the OP didn't provide the location of the event, which he did. You also resorted to needless name-calling as a result of your mistake, which I don't think enhances the usefulness of this forum. What exactly are you trying to achieve? -- Michael Hoffman From jimxu at google.com Tue Jun 5 14:26:07 2007 From: jimxu at google.com (Yongjian Xu) Date: Tue, 5 Jun 2007 11:26:07 -0700 Subject: url encode In-Reply-To: References: Message-ID: <9c09a1210706051126m2ac4590fw49831c5a0b5072d1@mail.gmail.com> you can take a look urlib.quote or quote_plus methods. Jim On 6/5/07, Lee Jones wrote: > > Hello, > > > > I am trying to urlencode a string. In python the only thing I can see is > the urllib.urlencode(). But this takes a dictionary, and returns > "key=value", which is not what I want. I only want to url-encode a string. > Does any one know how to do this in python > > Thanks > > Lee > > > > > > Lee Jones, > > Software Developer > > *SecureTrading Ltd* > European Operations Centre > Parc Menai > Bangor > Gwynedd LL57 4BL > T: 01248 672 028 > F: 01248 672 099 > > www.securetrading.com > > > > -- > http://mail.python.org/mailman/listinfo/python-list > > -- Yongjian (Jim) Xu =========== Sysops -------------- next part -------------- An HTML attachment was scrubbed... URL: From len-l at telus.net Mon Jun 11 18:01:36 2007 From: len-l at telus.net (Lenard Lindstrom) Date: Mon, 11 Jun 2007 22:01:36 GMT Subject: Help with PAM and ctypes In-Reply-To: <1181219321.236803.111180@g4g2000hsf.googlegroups.com> References: <1181219321.236803.111180@g4g2000hsf.googlegroups.com> Message-ID: <4Djbi.21568$nx3.19208@edtnps89> Chris AtLee wrote: > Sorry for the repeat post...I'm not sure if my first post (on May > 30th) went through or > not. > > I've been trying to write a PAM module using ctypes. In the > conversation > function (my_conv in the script below), you're passed in a > pam_response** > pointer. You're supposed to allocate an array of pam_response's and > set > the pointer's value to the new array. Then you fill in the array with > appropriate data. > > I can't seem to get it working in python...The authenticate function > always > returns PAM_AUTHTOK_RECOVER_ERR (21), which I think means the response > doesn't make any sense. > > I've tried saving the response array outside of my_conv to make sure > it > doesn't get garbage collected, but that doesn't seem to help. > > Any pointers would be appreciated! > > Cheers, > Chris > [snip some code] > > conv_func = CFUNCTYPE(c_int, > c_int, POINTER(POINTER(pam_message)), > POINTER(POINTER(pam_response)), c_void_p) > > class pam_conv(Structure): > _fields_ = [ > ("conv", conv_func), > ("appdata_ptr", c_void_p) > ] > > pam_start = libpam.pam_start > pam_start.restype = c_int > pam_start.argtypes = [c_char_p, c_char_p, POINTER(pam_conv), > POINTER(pam_handle)] > > pam_authenticate = libpam.pam_authenticate > pam_authenticate.restype = c_int > pam_authenticate.argtypes = [pam_handle, c_int] > > if __name__ == "__main__": > import getpass, os, sys > @conv_func > def my_conv(nMessages, messages, pResponse, appData): > # Create an array of nMessages response objects > # Does r get GC'ed after we're all done? > r = (pam_response * nMessages)() The memory allocated to r is garbage collected immediately after my_conv returns. You need to allocate it explicitly using C's calloc or such. This assumes pam_start will free the memory for you. addr = calloc(sizeof(pam_response), nMessages) addr is the memory address as a Python integer. > pResponse.contents = cast(r, POINTER(pam_response)) pResponse.contents changes the actual value of pResponse, a value on the stack. You want to change the value of the pointer pResponse points to: pResponse[0] = cast(addr, POINTER(pam_response)) The cast creates a POINTER(pam_reponse) instance with value addr. > for i in range(nMessages): > if messages[i].contents.msg == "Password: ": > p = getpass.getpass() > pResponse.contents[0].resp_retcode = 0 > pResponse.contents[0].resp = p > return 0 > > handle = pam_handle() > c = pam_conv(my_conv, 0) > retval = pam_start("login", os.getlogin(), pointer(c), > pointer(handle)) > > if retval != 0: > print "Couldn't start pam session" > sys.exit(-1) > > retval = pam_authenticate(handle, 0) > if retval == 21: > print "Authentication information cannot be recovered" > sys.exit(-1) > > print retval > If you are going to do any serious ctypes coding consider joining the ctypes mailing list at sourceforge.net . -- Lenard Lindstrom From survivedsushi at yahoo.com Wed Jun 27 20:07:08 2007 From: survivedsushi at yahoo.com (Matthew Peter) Date: Wed, 27 Jun 2007 17:07:08 -0700 (PDT) Subject: Return name of caller function? In-Reply-To: <20070627203616.GA30323@slaniel-laptop.itasoftware.com> Message-ID: <778088.29493.qm@web35207.mail.mud.yahoo.com> > The code below doesn't do the trick for you? > > #!/usr/bin/python > import inspect > > def master(): > print "I am the master" > slave() > > def slave(): > stack = inspect.stack() > caller = stack[1][3] > print "I am the slave; my caller was %s" % caller > > def main(): > master() > > if __name__ == '__main__': > main() [..] Yes. That does work. I was testing with an aliased instance of function which was returning >>>a = slave >>>print a() Is regex'ing stack[1][4] the only way to return 'a' in this instance? ____________________________________________________________________________________ Be a PS3 game guru. Get your game face on with the latest PS3 news and previews at Yahoo! Games. http://videogames.yahoo.com/platform?platform=120121 From geoff.bache at pobox.com Mon Jun 11 09:10:40 2007 From: geoff.bache at pobox.com (geoffbache) Date: Mon, 11 Jun 2007 06:10:40 -0700 Subject: Threads, signals and sockets (on UNIX) In-Reply-To: References: <1181563003.508142.23870@g4g2000hsf.googlegroups.com> Message-ID: <1181567440.498489.96960@q66g2000hsg.googlegroups.com> On Jun 11, 2:08 pm, Jean-Paul Calderone wrote: > On Mon, 11 Jun 2007 04:56:43 -0700, geoffbache wrote: > > >> Twisted *should* be able to do this, as it uses non-blocking IO. > > >>http://twistedmatrix.com/trac/ > > >Thanks for the tip. I'll take a look if nobody has any better > >suggestions. > > Twisted is a pretty good suggestion in general. ;) > >It still seems to me that what I'm trying to do is essentially quite > >simple, and shouldn't require > >as large a tool as Twisted to fix it. Isn't Twisted basically for web > >applications? > > Twisted supports HTTP, but it does plenty of other things too. Generally > speaking, it's useful for any network application, plus some other stuff. > My application is only incidentally a network application. It doesn't have clients and servers as such, it just distributes its work via a grid engine and then lets these workers communicate back their results via sockets. > You're half right about this being simple though, and not needing Twisted > to solve the problem. The only thing you need to do to solve the problem > is avoid using either signals or threads. Interaction between the two is > very complicated and, as you've noticed, varies across platforms. Twisted > is solving the problem for you here by letting you do I/O without using > threads, making signals *almost* simple. > Yes, I would avoid signals or threads if I could, but it's tough. The program is supposed to "appear" to just be a batch process, so handling e.g. ctrl-C is essential. The standard SocketServer doesn't allow for this, so I need some other thread of control that will, or some means of "asynchronising" SocketServer internally. Or there's always the really hacky low tech solution which has a certain appeal : have the main thread check all the others for being alive and sleep in between... Geoff From kyosohma at gmail.com Sun Jun 24 19:11:44 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Sun, 24 Jun 2007 23:11:44 -0000 Subject: WX call a pywx program from a program, and return values In-Reply-To: <1182697378.006060.178900@n2g2000hse.googlegroups.com> References: <1182697378.006060.178900@n2g2000hse.googlegroups.com> Message-ID: <1182726704.549928.222580@q69g2000hsb.googlegroups.com> On Jun 24, 10:02 am, Marcpp wrote: > I need to call a pywx program(1) from an wxpy program(2) and return a > value to program(2). > Any example to do it? Yup. See links below: http://mail.python.org/pipermail/tutor/2005-May/038648.html http://www-pcmdi.llnl.gov/software-portal/cdat/tips_and_tricks/python_tips/passing_arguments.html http://aspn.activestate.com/ASPN/Mail/Message/wxPython-users/3508008 Mike From jstroud at mbi.ucla.edu Sun Jun 24 15:41:45 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sun, 24 Jun 2007 12:41:45 -0700 Subject: Accessing variable from a function within a function In-Reply-To: References: Message-ID: James Stroud wrote: > Nathan Harmston wrote: > def exteuclid(m,n): > x = 0,1,1,0,m,n > def euclid(c,d,x=x): > a,a1,b,b1,c,d = x > q = c /d > r = c % d > if r == 0: > print a,b > return d > else: > print a1,a,b1,b,c,d,q,r > t = b1 > b = t - q * b > a = t - q * a > c,d,a1,b1 = d,r,a,b > return euclid(c,d) > return euclid(c,d) > > James My answer above is wrong because c and d take the wrong default values. Also, you have some ambiguity in your code. Are nested calls to euclid supposed to have the original values of a, a1, b, & b1, or are they to take the original values 0, 1, 1, 0? This type of ambiguity is one reason why the interpreter does not like reference before assignment. This is my best guess at what you want because I'm not familiar with how euclid's algorithm works: def exteuclid(m,n): def euclid(a,a1,b,b1,c,d): q = c /d r = c % d if r == 0: print a,b return d else: print a1,a,b1,b,c,d,q,r t = b1 b = t - q * b a = t - q * a c,d,a1,b1 = d,r,a,b return euclid(a,a1,b,b1,c,d) return euclid(0,1,1,0,m,n) From http Tue Jun 26 17:17:23 2007 From: http (Paul Rubin) Date: 26 Jun 2007 14:17:23 -0700 Subject: Portable general timestamp format, not 2038-limited References: <1182544384.709759.235300@o11g2000prd.googlegroups.com> <20070625133843.9e25d0ab.steveo@eircom.net> <82b5l4-tvh.ln1@zoogz.gregorie.org> <7xbqf3lc7i.fsf@ruckus.brouhaha.com> <70c7l4-2gp.ln1@zoogz.gregorie.org> <7xlke6y6y1.fsf@ruckus.brouhaha.com> Message-ID: <7x645al8kc.fsf@ruckus.brouhaha.com> Martin Gregorie writes: > > Same one already given: http://cr.yp.to/proto/utctai.html > > Nope - you referenced leap seconds, not TAI and not that URL Oh whoops, I thought I put that url further up in the thread. I remember grumbling to myself about having to look for it twice. Maybe I'm just confused. Anyway it's pretty interesting stuff, as is the Wikipedia article someone else linked to. From bruno.42.desthuilliers at wtf.websiteburo.oops.com Mon Jun 11 04:37:26 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Mon, 11 Jun 2007 10:37:26 +0200 Subject: Python's "only one way to do it" philosophy isn't good? In-Reply-To: References: <1181368143.874341.273140@r19g2000prf.googlegroups.com> <1181475395.749525.185520@m36g2000hse.googlegroups.com> Message-ID: <466d09c7$0$30852$426a74cc@news.free.fr> Terry Reedy a ?crit : > wrote in message > news:1181475395.749525.185520 at m36g2000hse.googlegroups.com... > | > Terry Reedy wrote: > | > > In Python, you have a choice of recursion (normal or tail) > > [snip Stroud questions] > > | I'm afraid Terry is wrong here, at least if he meant that CPython had > | tail recursion *optimization*. > > NO!!! > I did not mean that or imply that in any way. I understand you didn't mean it, but since the whole point of tail-recursion is allowing optimisation (else tail-recursion is nothing else than a subset of recursion), you somehow implied it, even while that was not your intention. > | (and just for those who don't know yet, it's not a shortcoming, it's a > | design choice.) > > And I already noted in a followup that I am working on a Python Papers > paper explaining that choice, including Guido's claim that 'for statements > are better'. > > So frankly I am a little annoyed that you dragged my name into your answer > to Stroud when you should have succintly said 'No, Never', or better, > nothing at all, as someone else already did say that. Read more of the > tread before jumping in and acribing ignorance to people. > You're right on the fact that I should have read more of the thread before posting this (which I usually do), and I do apologize for this. But please note the second half of the sentence - which puts a strong precondition on the validity of the first part. From twisted0n3 at gmail.com Sun Jun 17 16:58:10 2007 From: twisted0n3 at gmail.com (Twisted) Date: Sun, 17 Jun 2007 20:58:10 -0000 Subject: The Modernization of Emacs In-Reply-To: <1182093200.598418.218620@e9g2000prf.googlegroups.com> References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> Message-ID: <1182113890.115491.168740@m36g2000hse.googlegroups.com> On Jun 17, 11:13 am, Xah Lee wrote: [snip] Whoa. Xah posted something I agree with wholeheartedly. Imagine that. From horpner at yahoo.com Tue Jun 5 09:00:15 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Tue, 05 Jun 2007 13:00:15 GMT Subject: Who uses Python? References: <1180985830.288414.208850@q69g2000hsb.googlegroups.com> Message-ID: On 2007-06-04, walterbyrd wrote: > I mean other than sysadmins, programmers, and web-site > developers? I manage the database application, data integration, and reporting for a financial aid office, and I use Python every day. Though I only seldom have to write new programs or update my old ones. I use it to shuffle and sort important files around, to convert reports into formats necessary for various import and export functions, to reconcile data between database systems, and to maintain little text databases for various business processes. The only "programming language" I use more often is Excel (VLOOKUP and Pivot Tables specifically). Python can replace any individual Excel application, but I use Excel for a bunch of one-timers, for which I find it more convenient. Python enters the picture when I find something that I need to do frequently, and with similar data inputs and outputs. -- Neil Cerutti From showell30 at yahoo.com Mon Jun 11 20:19:14 2007 From: showell30 at yahoo.com (Steve Howell) Date: Mon, 11 Jun 2007 17:19:14 -0700 (PDT) Subject: SimplePrograms challenge In-Reply-To: <1181605226.367359.235860@q19g2000prn.googlegroups.com> Message-ID: <729880.25774.qm@web33502.mail.mud.yahoo.com> --- John Machin wrote: > On Jun 12, 9:16 am, Steve Howell > wrote: > > > > > One more suggestion--maybe it could exercise a > little > > more of the CVS module, i.e. have something in the > > data that would trip up the ','.split() approach? > > The what approach?? Do you mean blah.split(',') ?? > Yes, of course. I obviously had ','.join() on my brain. :) ____________________________________________________________________________________ Choose the right car based on your needs. Check out Yahoo! Autos new Car Finder tool. http://autos.yahoo.com/carfinder/ From exarkun at divmod.com Mon Jun 11 20:58:01 2007 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Mon, 11 Jun 2007 20:58:01 -0400 Subject: A gotcha: Python pain point? In-Reply-To: Message-ID: <20070612005801.4947.1216485017.divmod.quotient.305@ohm> On Mon, 11 Jun 2007 16:54:10 -0700, James Stroud wrote: >Beorn wrote: >> Consider this example: >> >> >>> def funcs(x): >> ... for i in range(5): >> ... def g(): return x + i >> ... yield g >> > [snip] > >If this isn't classified as a bug, then someone has some serious >explaining to do. Why would it be desirable for a generator to behave >differently in two different contexts. Should I import this to see how >many principles this behavior violates? It follows logically from first principals. ;) You might disagree with those, but given them, it's hard to disagree with the conclusion. The first form forces the generator to run to completion before the list comprehension evaluates any iteration, and so the loop variable inside the generator is already 4, and so all functions yielded will return 5 when called. The second form lets the generator run lazily, so it has only reached the iteration which yielded a particular function by the time that function is called by the list comprehension, so each function yields a different value, because it is the continuing iteration of the generator which changes the values returned by the yielded functions. As far as explanations go, perhaps that's not a very good one (all I've done is describe the behavior, after all, and less concisely than the original Python did!) but maybe the translation into english will somehow help reveal how this behavior is consistent. For what it's worth, I agree that scoping in Python is not ideal and this is a good example of an area where that shortcoming causes surprises. Jean-Paul From kosh at aesaeion.com Fri Jun 29 23:15:00 2007 From: kosh at aesaeion.com (William Heymann) Date: Fri, 29 Jun 2007 21:15:00 -0600 Subject: Vista 64 + Python2.5 + wxpython 28 issue In-Reply-To: <468585BB.8090800@v.loewis.de> References: <003201c7ba21$8c77ff70$a567fe50$@com> <468585BB.8090800@v.loewis.de> Message-ID: <200706292115.00893.kosh@aesaeion.com> On Friday 29 June 2007, Martin v. L?wis wrote: > > There was no need for me to use 64 so I have switched back to 32 and > > works fine. > > > > Python is not ready for the 64 world yet ;) > > It's a matter of standpoint. 64 bit is not ready for the world, yet. > > Regards, > Martin I think you mean 64bit windows. 64bit linux has been working great. I use 64bit python and zope every day and they work very well and the ability to use more memory then 4G is very handy for my tests. From sergey at fidoman.ru Fri Jun 1 06:25:36 2007 From: sergey at fidoman.ru (Sergey Dorofeev) Date: Fri, 1 Jun 2007 14:25:36 +0400 Subject: subexpressions References: Message-ID: "Peter Otten" <__peter__ at web.de> wrote in message news:f3oret$sit$03$1 at news.t-online.com... > What syntax would you suggest for a lambda enhanced to cover your use > case? > I suppose you will end up with roughly the same number of characters, all > crammed in one line -- or broken into lines at a random position as it > happens with overambitious list comprehensions. Agree, this argument is strong. From dak at gnu.org Sat Jun 23 03:43:16 2007 From: dak at gnu.org (David Kastrup) Date: Sat, 23 Jun 2007 09:43:16 +0200 Subject: The Modernization of Emacs: terminology buffer and keybinding References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182272495.990807.99110@a26g2000pre.googlegroups.com> <87tzt3ihev.fsf@kobe.laptop> <1182370216.961241.6960@n60g2000hse.googlegroups.com> <85zm2ufjpb.fsf@lola.goethe.zz> <1182372592.803332.288260@u2g2000hsc.googlegroups.com> <1182373919.262388.100740@c77g2000hse.googlegroups.com> <85r6o6fhkb.fsf@lola.goethe.zz> <1182375045.626510.188170@m36g2000hse.googlegroups.com> <1182453375.531950.141460@m36g2000hse.googlegroups.com> <1182535516.594974.243910@q69g2000hsb.googlegroups.com> Message-ID: <85ejk3azjr.fsf@lola.goethe.zz> Falcolas writes: > On Jun 22, 11:28 am, Robert Uhl wrote: > >> It's Mac OS and Windows which are inconsistent. Emacs has been >> around since they were mere glimmers in the eye of Jobs & Gates... > > Inconsistent? I would have to disagree. They changed paradigms - > terminal text based interfaces to GUIs. You wouldn't expect a piece > of software built for a terminal to be backwards compatibility to > punch card interfaces, would you? You are aware that the ubiquitous standard terminal width of 80 columns has been chosen to match the 80-column punch card standard? > Why would a GUI based program limit itself to functionality as > defined by a terminal application? Emacs uses variable width fonts, can deal with a larger-than-8bit variety of GUI-based input events and can display images. Take a look at the screen shots for preview-latex illustrating WYSIWYG LaTeX editing in Emacs windows. So what is your problem? -- David Kastrup, Kriemhildstr. 15, 44793 Bochum From thomas at jollans.com Wed Jun 27 17:21:34 2007 From: thomas at jollans.com (Thomas Jollans) Date: Wed, 27 Jun 2007 23:21:34 +0200 Subject: listing the type of an object In-Reply-To: <71af3$4682d18c$d443bb3a$9028@news.speedlinq.nl> References: <71af3$4682d18c$d443bb3a$9028@news.speedlinq.nl> Message-ID: Stef Mientki wrote: > How can I list a type of an object instance ? > > I tried: > > class tLED (tDevice): > def some_proc(self): > print 'type(self)', type(self) > > But i gives me: > type(self) > > Moreover, I want even the type to be listed by it's ancestor, like this > > class tDevice: > def some_other_proc: > print 'type(self)', type(self) > Ahhh, history. At the moment (that is in 2.2 <= Python Version < 3.0 ), there are two types of classes: old-style classes are the default and a load of WTF?, which new-style classes make sense and behave like you (that is "one" in general and you, Stef, in particular) expect. As I'm too lazy to explain what all this is about, I'll point you to a page with a promising title: http://wiki.python.org/moin/NewClassVsClassicClass Thomas Jollans -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 260 bytes Desc: OpenPGP digital signature URL: From S.Mientki-nospam at mailbox.kun.nl Tue Jun 19 17:07:49 2007 From: S.Mientki-nospam at mailbox.kun.nl (Stef Mientki) Date: Tue, 19 Jun 2007 23:07:49 +0200 Subject: caseless dictionary howto ? In-Reply-To: References: <4dc64$46782a84$d443bb3a$4629@news.speedlinq.nl> Message-ID: <5c1e3$4678448d$d443bb3a$1513@news.speedlinq.nl> Evan Klitzke wrote: > On 6/19/07, Stef Mientki wrote: >> hello, >> >> I need to search a piece of text and make all words that are equal >> (except their case) also equal in their case, based on the first >> occurrence. >> So I'm using a dictionary to store names and attributes of objects. >> As as I need to search on the caseless name (so I've choosen lowercase), >> My dictionairy looks like this: >> >> self.procs [ "serial_hw_read" ] = ( "Serial_HW_Read", "F", "++", T) >> >> Is this really a good solution, >> or are there better ways ? > > Since you want an almost dictionary, you should create a new class > that inherits from dict and overloads the methods that you want to > change. > thanks, but still one question. Suppose I succeed in creating my own type, derived from dictionary, I would be able to add/set a key like this: self.procs [ "Serial_HW_Read" ] = ( "F", "++", T) and now I can query the dictionary by self.procs.has_key ( "serial_hw_read") but how do I get the original string "Serial_HW_Read" back ? thanks, Stef Mientki From bignose+hates-spam at benfinney.id.au Tue Jun 12 10:00:49 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 13 Jun 2007 00:00:49 +1000 Subject: Thunderbird access to this newsgroup References: <1181640420.561878.224690@x35g2000prf.googlegroups.com> Message-ID: <87d501w9v2.fsf@benfinney.id.au> Rostfrei writes: > What is the news server for this > newsgroup. Usenet newsgroups are redistributed over many servers worldwide. > If I ping comp.lang.python it is not resolved. That's right. It's the name of a Usenet newsgroup, not a host name. > For instance I had no problem configuring Eclipse news server. I > just entered news.eclipse.org as a news server address and after it > I can browse available groups. You can browse the groups available on that server, yes. To browse this group, you need to find a server that carries comp.lang.python. -- \ "The man who is denied the opportunity of taking decisions of | `\ importance begins to regard as important the decisions he is | _o__) allowed to take." -- C. Northcote Parkinson | Ben Finney From tdelaney at avaya.com Thu Jun 7 18:22:18 2007 From: tdelaney at avaya.com (Delaney, Timothy (Tim)) Date: Fri, 8 Jun 2007 06:22:18 +0800 Subject: Python 2.5.1 - sqlite3.dll issue In-Reply-To: <004401c7a93a$c1912260$0400000a@spooge> Message-ID: Josh Ritter wrote: > A number of our Windows customers have an issue with the sqlite3 > module included with Python 2.5.1 > > We've tracked the problem down to the sqlite3.dll included with the > Python > 2.5.1 distrubtion. It is stripped and thus cannot be relocated. This > causes the following exception on computers where something is already > loaded into the address the sqlite3.dll wants to use: > > File "sqlite3\__init__.pyc", line 24, in > File "sqlite3\dbapi2.pyc", line 27, in > ImportError: DLL load failed: Invalid access to memory location. > > I downloaded the latest sqlite3.dll from http://www.sqlite.org and > this fixes the problem. (This dll isn't stripped) Could you raise a bug report on SourceForge please? http://sourceforge.net/tracker/?group_id=5470&atid=105470&func=add Tim Delaney From kaldrenon at gmail.com Thu Jun 21 16:35:35 2007 From: kaldrenon at gmail.com (Kaldrenon) Date: Thu, 21 Jun 2007 20:35:35 -0000 Subject: The Modernization of Emacs: terminology buffer and keybinding In-Reply-To: <1182457914.940791.224080@n2g2000hse.googlegroups.com> References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182272495.990807.99110@a26g2000pre.googlegroups.com> <87tzt3ihev.fsf@kobe.laptop> <1182370216.961241.6960@n60g2000hse.googlegroups.com> <85zm2ufjpb.fsf@lola.goethe.zz> <1182372592.803332.288260@u2g2000hsc.googlegroups.com> <1182373919.262388.100740@c77g2000hse.googlegroups.com> <85r6o6fhkb.fsf@lola.goethe.zz> <1182375045.626510.188170@m36g2000hse.googlegroups.com> <1182453375.531950.141460@m36g2000hse.googlegroups.com> <1182456618.763414.219080@g4g2000hsf.googlegroups.com> <1182457914.940791.224080@n2g2000hse.googlegroups.com> Message-ID: <1182458135.048992.179340@p77g2000hsh.googlegroups.com> On Jun 21, 4:31 pm, Falcolas wrote: > Your statement holds true if, and only if, a user does not take full > advantage of the keyboard commands. But if we're talking about > experienced users in both cases, then that's not an issue, is it? Granted. I suppose my claim should have been more specifically about the means of interaction, and not about the tool being used. After all, Emacs 22.1 has fairly complete point-and-click support, even though I suspect more people use the keyboard as their primary input. From tcrane at REMOVETHISuiuc.edu Tue Jun 12 10:15:42 2007 From: tcrane at REMOVETHISuiuc.edu (T. Crane) Date: Tue, 12 Jun 2007 14:15:42 GMT Subject: file open default location References: <1181655985.895174.116540@o11g2000prd.googlegroups.com> Message-ID: >> As an aside, I forgot to mention above that I'm using Windows XP. Any >> other ideas or possible reasons that it would not choose my script >> location as the default location to save something? > > If you open a DOS window and run Python from there, it will write the > files > in whatever directory you were in when you typed the command. > > If you are running Python directly from Windows, or from an IDE, it's up > to the OS or the IDE to decide what your default directory is. Often it > will be the home directory from your user profile. I'm using ipython and running everything from there. On my wife's laptop the default save location is the home directory of her user profile, but on my work computer this is not the case. Therefore I assume that there's some setting somewhere that's causing ipython to send stuff to such a weird location. trevis From arkanes at gmail.com Wed Jun 27 11:09:57 2007 From: arkanes at gmail.com (Chris Mellon) Date: Wed, 27 Jun 2007 10:09:57 -0500 Subject: Python's "only one way to do it" philosophy isn't good? In-Reply-To: <1182955743.076746.114790@i38g2000prf.googlegroups.com> References: <7x3b0nmkk6.fsf@ruckus.brouhaha.com> <7xejjzmk7u.fsf@ruckus.brouhaha.com> <7xy7i7xjl5.fsf@ruckus.brouhaha.com> <1182872972.417776.78650@o11g2000prd.googlegroups.com> <7xtzsuy7fe.fsf@ruckus.brouhaha.com> <1182955743.076746.114790@i38g2000prf.googlegroups.com> Message-ID: <4866bea60706270809s5d6ce339n53afb3a73e65e6c9@mail.gmail.com> On 6/27/07, Andy Freeman wrote: > On Jun 26, 10:03 am, Paul Rubin wrote: > > > Map doesn't work on generators or iterators because they're not part > > > of the common lisp spec, but if someone implemented them as a library, > > > said library could easily include a map that handled them as well. > > > > Right, more scattered special purpose kludges instead of a powerful > > uniform interface. > > Huh? The interface could continue to be (map ...). > > Python's for statement relies on the fact that python is mostly object > oriented and many of the predefined types have an iterator interface. > Lisp lists and vectors currently aren't objects and very few of the > predefined types have an iterator interface. > > It's easy enough to get around the lack of objectness and add the > equivalent of an iterator iterface, in either language. The fact that > lisp folks haven't bothered suggests that this isn't a big enough > issue. > Is this where I get to call Lispers Blub programmers, because they can't see the clear benefit to a generic iteration interface? > The difference is that lisp users can easily define python-like for > while python folks have to wait for the implementation. > Yes, but Python already has it (so the wait time is 0), and the Lisp user doesn't. From ljz at asfast.com Sat Jun 9 07:18:43 2007 From: ljz at asfast.com (Lloyd Zusman) Date: Sat, 09 Jun 2007 07:18:43 -0400 Subject: Working with fixed format text db's References: <1181376260.193715.51330@q66g2000hsg.googlegroups.com> Message-ID: <87wsydl6jw.fsf@asfast.com> Frank Millman writes: > On Jun 8, 5:50 pm, Neil Cerutti wrote: >> Many of the file formats I have to work with are so-called >> fixed-format records, where every line in the file is a record, >> and every field in a record takes up a specific amount of space. >> >> [ ... ] > > We already have '%-12s' to space fill for a length of 12, but it is > not truly fixed-length, as if the value has a length greater than 12 > you need it to be truncated, and this construction will not do that. In this case, we can use '%-12.12s'. -- Lloyd Zusman ljz at asfast.com God bless you. From jwhite at casl.umd.edu Wed Jun 6 12:24:54 2007 From: jwhite at casl.umd.edu (Jason White) Date: Wed, 6 Jun 2007 12:24:54 -0400 Subject: creating lists based on parsed items Message-ID: <0138071BF1642F49BD9826823E668663DCA87A@ex2.casl.umd.edu> Hello all ... Sorry for jumping in and askig with 0 lurk-time. I am trying to do what (I think) should be fairly straightforward. I have a list of items that i want to sort into buckets. in item 1 of each line is the object I want to sort and in item 2 is the name of the bucket. I am making it dynamic however (so I don't know the bucket names in advance). I've spent a few hours in the archives and several sites (hate to consider my google search history against the term 'python' right now ... anyhoo ...) This is what I've pieced together so far. ## varName is the name of the bucket that I got out of the split line (comma separated) try: eval (varName + '.append("' + items[0] + '")') except NameError: ##print 'could not use ' + varName eval (varName + ' = []') print 'created ' + varName + 'as list' cmd2 = varName + '.append("' + items[0] + '")' print eval(cmd2) What I get back is: Traceback (most recent call last): File "./dict_2_slex.py", line 25, in ? eval (varName + ' = []') File "", line 1 noun = [] ^ Any help for a python newb?!? TIA, Jason -------------- next part -------------- An HTML attachment was scrubbed... URL: From dak at gnu.org Thu Jun 21 11:01:20 2007 From: dak at gnu.org (David Kastrup) Date: Thu, 21 Jun 2007 17:01:20 +0200 Subject: The Modernization of Emacs References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182370894.001918.36590@k79g2000hse.googlegroups.com> <1182372821.298343.316860@g4g2000hsf.googlegroups.com> <1182375321.067664.190780@o61g2000hsh.googlegroups.com> <86hcp1l6hb.fsf@lola.quinscape.zz> Message-ID: <86d4zpl5bz.fsf@lola.quinscape.zz> Lew writes: > Bjorn Borud writes: >>> so if the context was system administration, I'd vote for vi as >>> well. if the context was programming I'd vote Emacs. > > David Kastrup wrote: >> You know you can use something like >> C-x C-f /su::/etc/fstab RET >> (or /sudo::/etc/fstab) in order to edit files as root in a normal >> Emacs session? > > I've been using emacs for something like twenty years and never knew > that before. The package "tramp" will provide that (as well as editing files over ssh, scp, rsync, telnet, plink...). It is already preinstalled in Emacs 22.1, but can also be installed for earlier versions. -- David Kastrup From __peter__ at web.de Tue Jun 26 14:56:03 2007 From: __peter__ at web.de (Peter Otten) Date: Tue, 26 Jun 2007 20:56:03 +0200 Subject: problem mixing gettext and properties References: <1182880358.100599.139120@j4g2000prf.googlegroups.com> Message-ID: Andr? wrote: > I've encountered a problem using gettext with properties while using a > Python interpreter. > > Here's a simple program that illustrate the problem. > ============== > # i18n_test.py: test of gettext & properties > > import gettext > > fr = gettext.translation('i18n_test', './translations', > languages=['fr']) _ = fr.gettext # untested > help = _("Help me!") > > class Test_i18n(object): > def get(self): > __help = _("HELP!") > return __help > help_prop = property(get, None, None, 'help') > > test = Test_i18n() > > print help > print test.help_prop > #### end of file > > To run the above program, you need to have the strings translated and > the proper ".po" and ".mo" files created. (for those interested, I > can send the whole lot in a zip file) > > If I run the program as is, the output is: > Aidez-moi! > AIDE!!! > > Ok, let's try with the Python interpreter: > > ActivePython 2.4.2 Build 248 (ActiveState Corp.) based on > Python 2.4.2 (#67, Oct 30 2005, 16:11:18) [MSC v.1310 32 bit (Intel)] > on win32 > Type "help", "copyright", "credits" or "license" for more information. >>>> import i18n_test > Aidez-moi! > AIDE!!! > > # No surprise there so far. > >>>> print i18n_test.help > Aidez-moi! >>>> print i18n_test.test.help_prop > AIDE!!! >>>> i18n_test.help > 'Aidez-moi!' > > # all of the above are as expected; now for the first surprise > >>>> i18n_test.test.help_prop > Traceback (most recent call last): > File "", line 1, in ? > File "i18n_test.py", line 12, in get > __help = _("HELP!") > TypeError: 'str' object is not callable > > # and a second surprise where we try to repeat something that used to > work > >>>> print i18n_test.test.help_prop > Traceback (most recent call last): > File "", line 1, in ? > File "i18n_test.py", line 12, in get > __help = _("HELP!") > TypeError: 'str' object is not callable > > #============= > > Dare I say: "Help!" I really need to use the above at the > interpreter prompt. > > Andr? The _ builtin is set to the result of the last expression evaluated by the interpreter: >>> for i in range(3): ... i ... 0 1 2 >>> _ 2 >>> import __builtin__ >>> __builtin__._ 2 Therefore you get a name clash with _() as an alias for gettext(). Use module-global aliases instead, e. g. _ = fr.gettext in the above code. Peter From idoerg at gmail.com Wed Jun 13 20:40:12 2007 From: idoerg at gmail.com (idoerg at gmail.com) Date: Thu, 14 Jun 2007 00:40:12 -0000 Subject: Method much slower than function? Message-ID: <1181781612.939800.238890@q19g2000prn.googlegroups.com> Hi all, I am running Python 2.5 on Feisty Ubuntu. I came across some code that is substantially slower when in a method than in a function. ################# START SOURCE ############# # The function def readgenome(filehandle): s = '' for line in filehandle.xreadlines(): if '>' in line: continue s += line.strip() return s # The method in a class class bar: def readgenome(self, filehandle): self.s = '' for line in filehandle.xreadlines(): if '>' in line: continue self.s += line.strip() ################# END SOURCE ############## When running the function and the method on a 20,000 line text file, I get the following: >>> cProfile.run("bar.readgenome(open('cb_foo'))") 20004 function calls in 10.214 CPU seconds Ordered by: standard name ncalls tottime percall cumtime percall filename:lineno(function) 1 0.000 0.000 10.214 10.214 :1() 1 10.205 10.205 10.214 10.214 reader.py:11(readgenome) 1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects} 19999 0.009 0.000 0.009 0.000 {method 'strip' of 'str' objects} 1 0.000 0.000 0.000 0.000 {method 'xreadlines' of 'file' objects} 1 0.000 0.000 0.000 0.000 {open} >>> cProfile.run("z=r.readgenome(open('cb_foo'))") 20004 function calls in 0.041 CPU seconds Ordered by: standard name ncalls tottime percall cumtime percall filename:lineno(function) 1 0.000 0.000 0.041 0.041 :1() 1 0.035 0.035 0.041 0.041 reader.py:2(readgenome) 1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects} 19999 0.007 0.000 0.007 0.000 {method 'strip' of 'str' objects} 1 0.000 0.000 0.000 0.000 {method 'xreadlines' of 'file' objects} 1 0.000 0.000 0.000 0.000 {open} The method takes > 10 seconds, the function call 0.041 seconds! Yes, I know that I wrote the underlying code rather inefficiently, and I can streamline it with a single file.read() call instead if an xreadlines() + strip loop. Still, the differences in performance are rather staggering! Any comments? Thanks, Iddo From justpratik at gmail.com Fri Jun 8 00:48:45 2007 From: justpratik at gmail.com (justpratik) Date: Thu, 07 Jun 2007 21:48:45 -0700 Subject: have a look at my blog site for asp.net .. there is microsoft contest also ( u can win so much) Message-ID: <1181278125.044704.138550@x35g2000prf.googlegroups.com> hi please a have a look at my site http://justpratik.blogspot.com and there's link for contest so hurry before 15th june From grante at visi.com Mon Jun 25 16:50:13 2007 From: grante at visi.com (Grant Edwards) Date: Mon, 25 Jun 2007 20:50:13 -0000 Subject: Installing python under the linux References: <1182800785.231113.199750@n2g2000hse.googlegroups.com> <1182802267.969628.156960@o61g2000hsh.googlegroups.com> <13809uckt2dqv5a@corp.supernews.com> Message-ID: <1380ak5gl7jlja1@corp.supernews.com> On 2007-06-25, Grant Edwards wrote: > On 2007-06-25, vedrandekovic at v-programs.com wrote: > >>>> I have problem with installing Python on the Linux >>>> platform.Can you tell me step by step how can I install python >>>> on linux ( please detailed ) , because I don't know anything >>>> about linux and I really don't understand python documentation >>>> about installing python on linux. >>> >>> Python is usally already installed on most distros. In a >>> terminal window type "python" to see if something happens. >>> Also please provide what distro you are running. >> >> Probably my distro is "ubuntu" <--- I don't what is it, and ' >> want install/build python from source > > You probably already have Python installed. You most certainly have the basic python installed already. It's one of the required packates for Ubunto. If you want to do programming, you may want to install some extra stuff like Idle: http://www.onecore.net/how-topython-programming-under-ubuntu.htm Quoting from the page above: "Ubuntu comes up with the command line version of python pre-installed." I really do not recommend installing from source for somebody like you who knows nothing about Python or Linux. Can explain why you think you want to install Python from source instead of using the Python that's already installed on your computer? -- Grant Edwards grante Yow! Thank god!! ... It's at HENNY YOUNGMAN!! visi.com From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Fri Jun 8 16:19:31 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Fri, 08 Jun 2007 22:19:31 +0200 Subject: python integration References: Message-ID: <5ctrujF3258m2U1@mid.individual.net> Dee Asbury wrote: > I am looking for a method to integrate in Python, my problem is > that I do not want the summed up result. I need the result in the > form of a list (or array) with the x-values (or ranges) and the > volume beneath that section of the curve only. Why don't you then split up your integration interval, this gives you the area below the curve in the respective interval. Regards, Bj?rn -- BOFH excuse #307: emissions from GSM-phones From anamax at earthlink.net Wed Jun 27 10:49:03 2007 From: anamax at earthlink.net (Andy Freeman) Date: Wed, 27 Jun 2007 07:49:03 -0700 Subject: Python's "only one way to do it" philosophy isn't good? In-Reply-To: <7xtzsuy7fe.fsf@ruckus.brouhaha.com> References: <7x3b0nmkk6.fsf@ruckus.brouhaha.com> <1182750077.570603.160240@q69g2000hsb.googlegroups.com> <7xir9cbm0g.fsf@ruckus.brouhaha.com> <7xejjzmk7u.fsf@ruckus.brouhaha.com> <7xy7i7xjl5.fsf@ruckus.brouhaha.com> <1182872972.417776.78650@o11g2000prd.googlegroups.com> <7xtzsuy7fe.fsf@ruckus.brouhaha.com> Message-ID: <1182955743.076746.114790@i38g2000prf.googlegroups.com> On Jun 26, 10:03 am, Paul Rubin wrote: > > Map doesn't work on generators or iterators because they're not part > > of the common lisp spec, but if someone implemented them as a library, > > said library could easily include a map that handled them as well. > > Right, more scattered special purpose kludges instead of a powerful > uniform interface. Huh? The interface could continue to be (map ...). Python's for statement relies on the fact that python is mostly object oriented and many of the predefined types have an iterator interface. Lisp lists and vectors currently aren't objects and very few of the predefined types have an iterator interface. It's easy enough to get around the lack of objectness and add the equivalent of an iterator iterface, in either language. The fact that lisp folks haven't bothered suggests that this isn't a big enough issue. The difference is that lisp users can easily define python-like for while python folks have to wait for the implementation. Syntax matters. From see at signature.invalid Thu Jun 14 23:43:42 2007 From: see at signature.invalid (Douglas Wells) Date: Thu, 14 Jun 2007 23:43:42 -0400 (EDT) Subject: Convert to C/C++? References: <1181852202.897976.312280@j4g2000prf.googlegroups.com> Message-ID: In article <1181852202.897976.312280 at j4g2000prf.googlegroups.com>, SpreadTooThin writes: > I am wondering if someone who knows the implemention of python's time > could help converting this to c/c++.... First the obligatory sermon: If you are truly intending to utilize a UUID generator on a UNIX platform, I urge you to seek out and use a native implementation. Both Linux and FreeBSD distributions include such a capability, and there are also functions available in freely available libraries. Such a native function would offer several advantages over the code you are attempting to copy: 1) it could utilize the full capability of the clock rather than be limited to the microseconds precision in gettimeofday; 2) it is probably implemented utilizing a system locking function to provide a truly unique-per-system UID; 3) it would almost certainly incorporate a per-machine unique identifier, as called for by the spec, and which is missing from your prototype code; 4) it would have easier access to better pseudo-random number generators; 4) it would probably be coded better than the code you provide, which squanders quite a bit of precision (I haven't counted exactly, but I would guess about 10 bits worth); Also, it sounds as though you are not comfortable coding in C (as most of the information that you seek is straight-forwardly available from the Python and UNIX documentation), and there are numerous subtleties in the code that you must develop: 1) the management of endianness will require careful attention to your use of this function; 2) conversion to and from 64-bit numbers requires attention to the suffixes. With that said; Python doesn't define the time epoch except on UNIX platforms, but it's almost certainly the same as on UNIX. So, time.time() is equivalent to: double time_time (void) { struct timeval tv; gettimeofday (&tv, (void *) NULL); return tv.tv_sec + tv.tv_usec / 1e6); } random.randrange(value) is approximately equivalent to: long random_randrange (unsigned long stop) { return rand () % stop; } - with the caveats that: 1) you should choose a better pseudo-random number generator than rand(); 2) you should be sure to initialize the random function, e.g., via srand(); > nanoseconds = int(time.time() * 1e9) > # 0x01b21dd213814000 is the number of 100-ns intervals between the > # UUID epoch 1582-10-15 00:00:00 and the Unix epoch 1970-01-01 00:00:00. > self.timestamp = int(nanoseconds/100) + 0x01b21dd213814000L > self.clock_seq = random.randrange(1<<14L) # instead of stable storage > self.time_low = self.timestamp & 0xffffffffL > self.time_mid = (self.timestamp >> 32L) & 0xffffL > self.time_hi_version = (self.timestamp >> 48L) & 0x0fffL > self.clock_seq_low = self.clock_seq & 0xffL > self.clock_seq_hi_variant = (self.clock_seq >> 8L) & 0x3fL You should look up the definition of the various fields (e.g., clock_seq, time_low, time_mid) in a UUID specification, for example IETF RFC 4122. They have precise width requirements. > #print 'timestamp ', self.timestamp, self.time_low, self.time_mid, self.time_hi_version > #print 'clock_seq ', self.clock_seq, self.clock_seq_low, self.clock_seq_hi_variant > > vs unix gettimeofday.... > > int gettimeofday(struct timeval *tp, struct timezone *tzp); By the way, the UNIX gettimeofday function does not include timezone: the prototype of the second argument is "void *" and must be passed as NULL. Good luck, - dmw -- . Douglas Wells . Connection Technologies . . Internet: -sp9804- -at - contek.com- . From basilisk96 at gmail.com Sat Jun 9 08:16:08 2007 From: basilisk96 at gmail.com (Basilisk96) Date: Sat, 09 Jun 2007 12:16:08 -0000 Subject: interating over single element array In-Reply-To: References: <4Beai.13210$5j1.6184@newssvr21.news.prodigy.net> <1181345593.788652.275380@h2g2000hsg.googlegroups.com> Message-ID: <1181391368.112303.284890@q75g2000hsh.googlegroups.com> "Terry Reedy" wrote: > Any what if 'filelist' is any iterable other than a string or list? Your > code is broken, and unnecessarily so. So I would call the parameter > 'files' and test for isinstance(files, str) #or basestring. And wrap if it > is. Can you give an example of such an iterable (other than a tuple)? I'd certainly like to fix my 'fix' to work for a more general case. Regards, -Basilisk96 From bytter at gmail.com Sat Jun 23 10:08:19 2007 From: bytter at gmail.com (Bytter) Date: Sat, 23 Jun 2007 14:08:19 -0000 Subject: SIMD powered Python In-Reply-To: References: <1182554657.444684.268050@i13g2000prf.googlegroups.com> Message-ID: <1182607699.214626.85230@u2g2000hsc.googlegroups.com> Hi... True... But maybe in NumPy arrays that would be more feasible...? Cheers. Hugo Ferreira Marc 'BlackJack' Rintsch escreveu: > In <1182554657.444684.268050 at i13g2000prf.googlegroups.com>, Bytter wrote: > > > Is there any I&D ongoing about using SIMD [1] instructions, like SSE > > [2], to speed up Python, especially regarding functional features, > > like list comprehension, map and reduce, etc.. ? > > SIMD instruction sets know about "low level" data types, Python is about > objects. `map()`, `reduce()`, list comprehension work on arbitrary > iterables so how do you expect SIMD instructions handle this? Even simple > lists contain objects and those don't have to be of the same type. > > Ciao, > Marc 'BlackJack' Rintsch From detlev at die-offenbachs.de Sun Jun 3 06:10:25 2007 From: detlev at die-offenbachs.de (Detlev Offenbach) Date: Sun, 03 Jun 2007 12:10:25 +0200 Subject: ANN: eric4 4.0.0 release Message-ID: Hi, I am proud to announce the availability of the first official release of eric4. eric4 is the successor of the well known eric3 Python development environment. What is eric4? -------------- eric4 is an Integrated Development Environment for the Python (and Ruby) language. It comes with all batteries included. It has too many features to list here. For details please visit http://www.die-offenbachs.de/eric/index.html Regards, Detlev -- Detlev Offenbach detlev at die-offenbachs.de From showell30 at yahoo.com Tue Jun 12 18:43:32 2007 From: showell30 at yahoo.com (Steve Howell) Date: Tue, 12 Jun 2007 15:43:32 -0700 (PDT) Subject: SimplePrograms challenge In-Reply-To: <1181687126.349940.51420@n15g2000prd.googlegroups.com> Message-ID: <823895.93516.qm@web33503.mail.mud.yahoo.com> --- George Sakkis wrote: > > from itertools import count, ifilter > def sieve(): > seq = count(2) > while True: > p = seq.next() > seq = ifilter(p.__rmod__, seq) > yield p > > > I suspect that it violates your second rule though > :) > I'm genuinely torn. The elegance of the solution far outweighs its esotericness. And I certainly can't complain about the choice of the problem (finding primes), since I included a much more pedestrian solution to the same problem on the very page that we're talking about. I do feel, however, like I want to order solutions by how long they are in line numbers, and if I stick to that rule, I do think that the solution above, while elegant, might be a little advanced as the seventh example of Python's simplicity. Is there a way to broaden the problem somehow, so that it can be a longer solution and further down on the page, and so that I can continue to enforce my somewhat arbitrary rule of ordering examples by how long they are? (I fully confess that my ordering rule unfairly penalizes short-and-sweet limitations, but I hope that *all* solutions are short-and-sweet, and this one certainly fits the bill.) ____________________________________________________________________________________ Boardwalk for $500? In 2007? Ha! Play Monopoly Here and Now (it's updated for today's economy) at Yahoo! Games. http://get.games.yahoo.com/proddesc?gamekey=monopolyherenow From bignose+hates-spam at benfinney.id.au Thu Jun 21 22:02:35 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 22 Jun 2007 12:02:35 +1000 Subject: import mysteries References: Message-ID: <87wsxwvj9g.fsf@benfinney.id.au> David Abrahams writes: > I'm pretty comfortable with Python, but recently I'm constantly > finding mysterious issues with import. For example, looking at > > http://genshi.edgewall.org/browser/trunk/genshi/filters/transform.py > > the examples use the symbol 'HTML' but it's not defined locally, it's > not explicitly imported, and there's no import *. Yet doctest will > test this module and it passes with flying colors. It turns out HTML > is defined in genshi.input. How do I know that? I grepped for it. > How does it become available to this module? That's a mystery to me too. I can't see by looking at the module where this 'HTML' name comes from, and as you say there is no import of 'genshi.input'. Whatever the explanation, it's a violation of one of the strengths of Python: namespaces. Names that appear in the current namespace (as happens with 'from foo import *', and as seems to be happening here) are bad programming style, for exactly the reason that they make the code more difficult to understand. -- \ "bash awk grep perl sed, df du, du-du du-du, vi troff su fsck | `\ rm * halt LART LART LART!" -- The Swedish BOFH, | _o__) alt.sysadmin.recovery | Ben Finney From simonroses at granisla.com Fri Jun 29 03:46:04 2007 From: simonroses at granisla.com (Simon Roses Femerling) Date: Fri, 29 Jun 2007 09:46:04 +0200 Subject: Vista 64 + Python2.5 + wxpython 28 issue In-Reply-To: <46842727.6070202@v.loewis.de> References: <4684150e$0$24850$9b622d9e@news.freenet.de> <000001c7b9c5$e70a0d40$b51e27c0$@com> <46842727.6070202@v.loewis.de> Message-ID: <003201c7ba21$8c77ff70$a567fe50$@com> Hello Martin, Thanks for your reply. There was no need for me to use 64 so I have switched back to 32 and works fine. Python is not ready for the 64 world yet ;) Sincerely, SRF -----Original Message----- From: "Martin v. L?wis" [mailto:martin at v.loewis.de] Sent: jueves, 28 de junio de 2007 23:25 To: Simon Roses Femerling Cc: python-list at python.org Subject: Re: Vista 64 + Python2.5 + wxpython 28 issue > Is there any 64 version installer or do I need to build myself ? There are hardly AMD64 versions of *anything* but the base Python distribution. I strongly advise to use the 32-bit version on AMD64 (in fact, I see little reason to run Win64 at all unless you have more that 4GiB in the box, or unless you are developing a software product that you explicitly target for Win64). If you absolutely need to run 64-bit code, be prepared to compile everything for yourself, and be prepared that it won't work out of the box, and cost you many person days to fix and debug. Never forget to feed back the fixes you make to the respective authors of the open source software. Notice that you won't just need a 64-bit version of wxpython, but also such versions of all underlying libraries wxpython happens to be build on. Regards, Martin From spamtrap at library.lspace.org.invalid Sun Jun 10 07:41:47 2007 From: spamtrap at library.lspace.org.invalid (Shmuel (Seymour J.) Metz) Date: Sun, 10 Jun 2007 08:41:47 -0300 Subject: MI5 Persecution: Goldfish and Piranha 29/9/95 (5104) References: Message-ID: <466bf18b$1$fuzhry+tra$mr2ice@news.patriot.net> In , on 06/10/2007 at 04:57 AM, "Mike" said: >And this is here because ....??? 1. MI5 didn't take him down like they were supposed to 2. You didn't include followup-to in your header -- Shmuel (Seymour J.) Metz, SysProg and JOAT Unsolicited bulk E-mail subject to legal action. I reserve the right to publicly post or ridicule any abusive E-mail. Reply to domain Patriot dot net user shmuel+news to contact me. Do not reply to spamtrap at library.lspace.org From tjreedy at udel.edu Mon Jun 4 14:45:44 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 4 Jun 2007 14:45:44 -0400 Subject: c[:]() References: <1180504190.055427.173610@h2g2000hsg.googlegroups.com><1180504773.374529.161740@q66g2000hsg.googlegroups.com><1180878080.630213.258230@q75g2000hsh.googlegroups.com><1180886141.096451.68060@k79g2000hse.googlegroups.com> <00b301c7a690$25af37d0$240110ac@Muse> Message-ID: "Warren Stringer" wrote in message news:00b301c7a690$25af37d0$240110ac at Muse... |> "Marc 'BlackJack' Rintsch" wrote in message | > news:pan.2007.06.03.20.03.25.278011 at gmx.net... | > || Warren Stringer wanted to call the functions just for the side effects | > | without interest in the return values. So building a list of return | > | values which is immediately thrown away is a waste of time and memory. | > | > Also unnecessary: for f in callables: f() | | What do you mean? That if you want to call each of a sequence of proceedures (functions without a meaning return), as you have indicated and do so again, then the above is the simple, direct way to do so. Using 'c' instead of 'callables', as in the subject line, would reduce the number of characters [snip] | It sounds like list comprehension may be slower because it builds a list | that never gets used. A list comprenhension is for building a list that will be used. | I'm curious if eval statements are faster than def | statements? Any bytecode experts? Eval expressions (not statements) and def statements do different things and hence comparing their speed make no sense to me. In any case, speed comparisions that you really care about are best done on a particular target system. Terry Jan Reedy From DustanGroups at gmail.com Fri Jun 15 19:01:30 2007 From: DustanGroups at gmail.com (Dustan) Date: Fri, 15 Jun 2007 23:01:30 -0000 Subject: Should: "for k,v in **dictionary_instance" work? In-Reply-To: <1181935045.323196.287810@n2g2000hse.googlegroups.com> References: <1181935045.323196.287810@n2g2000hse.googlegroups.com> Message-ID: <1181948490.239959.147540@o61g2000hsh.googlegroups.com> On Jun 15, 2:17 pm, keithgabryel... at gmail.com wrote: > Does it make sense to provide this syntax for iterating key/value > pairs from a dictionary? > > for k,v in **dict(): > print k,v > > why is this not the same as: > > for k,v in dict().items(): > print k,v > > for that matter, why the heck doesn't a dictionary default to > returning a tuple > k,v pair from its iterator? > > Pax, Keith > > Ps, I'm sure someone has thought of these things before, probably been > answered before, but I'm sure I didn't find reference to them when i > searched. The answer is simply for history and for clarity. From jstroud at mbi.ucla.edu Mon Jun 11 17:14:51 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Mon, 11 Jun 2007 14:14:51 -0700 Subject: userinteraction for a webspider In-Reply-To: <1492f$466be2e9$58422645$19939@news.usenext.de> References: <1492f$466be2e9$58422645$19939@news.usenext.de> Message-ID: Chris wrote: > hi guys, > > i would like to to write a little spider, where, occasionally, the user > has to interact. For example show a log-in page or something similar > (since everyone has those verification letter/number pics), or send a > message by hand. > > I had the idea of the script relaying the page to localhost but i > thought there might be an easier way... > > Thanks for your help > > Chris There are sweatshops in developing countries that provide this service. James From arkanes at gmail.com Tue Jun 26 11:27:49 2007 From: arkanes at gmail.com (Chris Mellon) Date: Tue, 26 Jun 2007 10:27:49 -0500 Subject: Problem with wxPython In-Reply-To: References: Message-ID: <4866bea60706260827j69f3a338g74a5445ed3bb5d60@mail.gmail.com> On 6/26/07, Ali wrote: > Hi > > I'm not sure if this is the right place to post, pardon me if it's not. > I'm having a problem with an application written with wxpython. The frame > seems only to refresh when moving my mouse of it, though i frequently call: > frame.Refresh(True). In fact, that line is called by another thread, right > after having modified some of the frames attributes. > In general, the wxpython-users list is a better source of wxPython answers than c.l.p. wxPython gui elements are not threadsafe unless otherwise indicated. Don't make calls against gui objects from other threads. This includes Refresh(). You can make this call in a threadsafe manner using wx.CallAfter like so: wx.CallAfter(frame.Refresh, True) From stefan.behnel-n05pAM at web.de Mon Jun 18 12:51:21 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Mon, 18 Jun 2007 18:51:21 +0200 Subject: Parsing HTML, extracting text and changing attributes. In-Reply-To: References: <1182175239.122827.4150@g4g2000hsf.googlegroups.com> Message-ID: <4676B809.2010307@web.de> Jay Loden wrote: > Someone else mentioned lxml but as I understand it lxml will only work if > it's valid XHTML that they're working with. No, it was meant as the OP requested. It even has a very good parser from broken HTML. http://codespeak.net/lxml/dev/parsing.html#parsing-html Stefan From simonyau at gmail.com Tue Jun 5 18:14:18 2007 From: simonyau at gmail.com (Simon Yau) Date: Tue, 05 Jun 2007 22:14:18 -0000 Subject: which "GUI module" you suggest me to use? In-Reply-To: References: Message-ID: <1181081658.609776.44820@j4g2000prf.googlegroups.com> On Jun 5, 2:57 pm, ZioMiP wrote: > Hi to all... > > I'm actually using Tkinter for my GUI... but I need to "put a piece of a > web-page in a widget" how can I do? > > which GUI module do you suggest me to use for do that? > > or which GUI module do you suggest me to use at all? > > I'm acutally using Windows Xp but I also use Linux... > > I know that WxPython work only under Windows and PyGTK work only under > Linux... there's some other modules? Maybe you can try Tkhtml. It supports both Windows and Linux. Simon From jadamson at partners.org Wed Jun 27 13:32:45 2007 From: jadamson at partners.org (Joel J. Adamson) Date: Wed, 27 Jun 2007 13:32:45 -0400 Subject: The Modernization of Emacs: terminology buffer and keybinding References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182272495.990807.99110@a26g2000pre.googlegroups.com> <87tzt3ihev.fsf@kobe.laptop> <1182370216.961241.6960@n60g2000hse.googlegroups.com> <85zm2ufjpb.fsf@lola.goethe.zz> <1182372592.803332.288260@u2g2000hsc.googlegroups.com> <1182549094.366282.286740@m37g2000prh.googlegroups.com> <87bqf7fwmg.fsf@telesippa.clsnet.nl> <1182553682.197778.138500@g37g2000prf.googlegroups.com> <87r6nzc9nu.fsf@mail.eng.it> <1182904631.083783.170640@o61g2000hsh.googlegroups.com> <87ir9924l5.fsf@mail.eng.it> <1182942279.999992.200250@q75g2000hsh.googlegroups.com> <4682570a.76573817@news.readfreenews.net> <1182955382.783515.167290@n60g2000hse.googlegroups.com> Message-ID: <87odj1joaq.fsf@W0053328.mgh.harvard.edu> Twisted writes: > On Jun 27, 8:26 am, g... at mail.ru (Timofei Shatrov) wrote: >> >For which you need an interpreter. Such as Ghostscript. Which is a >> >pain to install and a bigger one to configure, even on Windoze. >> >> Lie. Ghostscript works out of the box on Windows. > > You're joking. First of all I am not a liar, and secondly, Ghostscript > and Ghostview are tricky to set up correctly. I know -- I've done it a > time or three. There's an arcane GUI configurator that isn't > exceptionally well designed, and once it's working it still wonks out > on maybe 1 in 10 .ps and .eps files you come across ... It's become clear that you have a different conception of what consitutes "working" software. > better than being able to view none of them, mind you. Nonetheless > there's a world of difference between the GS tools and say Adobe > Acrobat Reader in terms of setup and use; the latter you just run an > installer and then find a pdf to double-click; no other steps > necessary and it works every time. Of course, Adobe stuff is > proprietary, and acrord supports some types of evil DRM... It's also become clear that you have a different conception of what constitutes using a computer. Joel -- Joel J. Adamson Biostatistician Pediatric Psychopharmacology Research Unit Massachusetts General Hospital Boston, MA 02114 (617) 643-1432 (303) 880-3109 *Joel's guide to sending attachments: 1. put all the files you want to send in a folder and archive the folder using tar, then compress it with gzip or bzip2 2. please send me .pdf, .html, or text in place of Word documents: http://www.gnu.org/philosophy/sylvester-response.html *Did you know there's a FREE alternative to using word processors? http://www.edafe.org/latex/ http://en.wikipedia.org/wiki/LaTeX http://nitens.org/taraborelli/latex From dfabrizio51 at gmail.com Mon Jun 4 10:57:16 2007 From: dfabrizio51 at gmail.com (chewie54) Date: Mon, 04 Jun 2007 14:57:16 -0000 Subject: wxPython splitwindow with interpreter on bottom Message-ID: <1180969036.773130.219700@n4g2000hsb.googlegroups.com> Hi all, Does anyone know of an example of wxPython source code that shows how to put a python shell (interpreter) in a bottom window with a graphical application in the top window? Thanks, From aleax at mac.com Sun Jun 24 00:11:42 2007 From: aleax at mac.com (Alex Martelli) Date: Sat, 23 Jun 2007 21:11:42 -0700 Subject: is this a valid import sequence ? References: <4f97$467c254d$d443bb3a$9522@news.speedlinq.nl> <137qo1egg4v1k04@corp.supernews.com> <1i0694u.1n6evsntoei0wN%aleax@mac.com> Message-ID: <1i06hm3.1ii0h87p707f2N%aleax@mac.com> Steven D'Aprano wrote: ... > >> It's never _wrong_ to use the global statement, even if it is strictly > >> unnecessary for the Python compiler. > > > > So, repeat that global statement ninetyseven times -- that's not > > "wrong", either, in exactly the same sense in which it's not "wrong" to > > have it once -- the Python compiler will not complain. And by repeating > > it over and over you make it less likely that a reader could miss it, so > > it's even more "self-documenting" and "easier to read", right? > > No, repeating it ninety-seven times doesn't make it easier to read, it > makes it *harder* to read, and I'm sure I don't need to explain why. You do, if you claim you're consistent in your "never _wrong_" assertion. How many totally useless repetitions are "never wrong"? I claim: ZERO; even ONE totally useless statement is one too many. You appear to want to put the bar elsewhere, but then it's not clear WHERE. > > "Perfection is reached, not when there is no longer anything to > > add, but when there is no longer anything to take away", as Antoine de > > Saint-Exupery wrote. > > That's debatable. Why does Python have decorators when there was already a > perfectly usable syntax for setting a method to function(method)? And > let's not even mention x += 1 etc. A decorator "takes away" some redundancy and repetition from an important idiom: @deco def somefunction ... ... stands for def somefunction ... ... somefunction = deco(somefunction) where 'somefunction' needed to be repeated THREE times. Similarly, though not quite as dramatically, somevariable += whatever can stand for somevariable = somevariable + whatever again taking away one (now needless) repetition. (Actually, the existence of inplace addition for some types makes += even more useful, as it polymorphically resolves to "what it _should_" resolve to:-). In sharp and enormous contrast, the construct you're defending ADDS useless repetition -- a statement that carries NO relevant information whatsoever, and in particular needlessly repeat a variable name. How can you SERIOUSLY claim ANY equivalence between constructs that REMOVE redundancy, and your defense of one that ADDS it?! > > Since that global statement is utterly useless > > (it's impossible to read and understand any substantial amount of Python > > code without realizing that accessing a variable not locally assigned > > means you're accessing a global, so the "self-documenting" character > > claimed for that redundancy is quite fallacious), > > Sure, in the *specific* example given, the body of the function was so > short that it would be a pretty poor developer who didn't know it was a > global. > > But in a more substantial function, one using lots of variables, it might > not be clear which were global and which weren't unless you studied the > code, line-by-line. If a function is so long and complicated, and in particular uses so many variables, that you lose track of what variables are local and which ones global, then adding a 'global' statement (or more) is tantamount to putting a bandaid over a large, gaping wound that's bleeding copiously and unarrestably. Forget such pitiful attempts at half-hearted kludgey "remedies", and refactor mercilessly -- that one, huge, hopelessly confused and confusing function, MUST become a (hopefully small) set of small, shiny, crystal-clear ones. In this sense, the presence of a totally useless "global" statement, which may have been used in the vain hope of effecting such unworkable "remedy", is yet another red flag waving -- it may indicate the programmer suspects he's overflowed the boundaries of good taste and maximum sensible complication, while lacking the guts to do the refactoring such a situation desperately calls for. > > it IS perfectly > > suitable to take away, and so it's at least a serious imperfection. It > > violates Occam's Razor, by multiplying entities (specifically > > statements) without necessity. It's just about as bad as sticking a > > semicolon at the end of every statement (to make it "self-documenting" > > that the statement ends there), parentheses around the conditions in if > > and while statements and the argument in return statements (to make it > > "self-documenting" where those expressions start and end), and a few > > other less common ways to waste pixels, screen space, readers' attention > > spans, and everybody's time. > > I'm not going to defend *any* of those practices. But I don't think > explicitly stating that a name is global, even when strictly unnecessary, > is in the same category. In practice, I wouldn't do so for a function that > was as short as the one the Original Poster used. I think it's an even more horrible practice than all others I list (except for my later note on comments that lie). Not only would I never use it, but I would never tolerate it in any way, shape, or form: I would not pass a code review for any code using it, if a book used it or defended it I would recommend to all potential readers to avoid the book, if I was teaching a programming course and a student used it I would fail the student, if I was interviewing a programming candidate and the candidate used it I would not hire thre candidate, and so on, and so forth. > But consider also something like this: > > def func(): > x, y = 1, 2 > z = x + y > # lots more code doing many things here > # some of which involve w > return z + w > > Let's pretend that there is sufficient code in there that it isn't obvious > at a glance that w is a global, okay? If there's too much code before the FIRST use of w, so that it's not obvious that w is never set before use (and thus must be global), then 'func' is too big and complicated. > There's a off-by-one error in the code, which we fix: > > def func(): > x, y = 1, 2 > z = x + y > # lots more code doing many things here > # some of which involve w > w = w + 1 > return z + w > > "UnboundLocalError". Oops. > > Now, I cheerfully admit that this scenario is contrived. Some people might > even argue that it is good for newbies to run into this error sooner > rather than later, but for those who don't think so, defensively inserting > a global statement might help prevent the issue from coming up. Do you realize what you're advocating? A 'global w' would make that "w = w + 1" (better expressed as "w += 1", of course) into a POLLUTION OF THE GLOBAL NAMESPACE -- instead of an error easily identified by the runtime (and easily fixed by removing that silly statement and using insread a "return z + w + 1"), now thanks to the "defensively inserting" you're ADVOCATING, you're having an exceedingly subtle shift into the semantics of your whole program, including future calls to func and any other function that uses that horridly-named 'w' (single-letter global names are hardly a defensible practice, either). If the coder has no clue as to whether w is local or global, then that coder MOST DEFINITELY has no business whatsoever in REBINDING the (global!) name w. "defensively" (HA!) putting yourself into a position where you may end up rebinding global names WITHOUT KNOWING YOU'RE DOING SO, i.e. POLLUTING the global namespace, is an even stronger reason that I'd yet advanced for loathing those ``useless'' global statements, and strongly confirms my unbounded detestation of them. > I'm a big believer in letting newbies walk before running. I'd rather see > beginner programmers over-use global than under-use it. You're welcome to > disagree, but since UnboundLocalError seems to be one of the more > perplexing errors newbies suffer from, I think it is better for them to > avoid it until they've got a little more experience. I think encouraging newbies to overuse globals is a horrible practice, and if you're ever teaching to newbies you're seriously damaging their chance to learn to program decently, or at least ensuring they'll take a needlessly long time for that learning. And I've both taught and practiced programming at a huge variety of levels, as well as quite successfully, so I do NOT believe your opinions on this subject should carry exactly the same weight as mine -- to be frank, I believe that in this case your opinion has a NEGATIVE worth, and that by putting it in practice you're seriously hurting the people you think you're helping. Alex From james.p.turk at gmail.com Wed Jun 13 19:55:02 2007 From: james.p.turk at gmail.com (James Turk) Date: Wed, 13 Jun 2007 23:55:02 -0000 Subject: one-time initialization of class members In-Reply-To: References: <1181772494.803499.266690@o11g2000prd.googlegroups.com> Message-ID: <1181778902.547599.147960@q19g2000prn.googlegroups.com> On Jun 13, 6:54 pm, Steven Bethard wrote: > James Turk wrote: > > Hi, > > > I have a situation where I have some class members that should only be > > done once. Essentially my problem looks like this: > > > class Base(object): > > dataset = None > > > def __init__(self, param): > > if type(self).dataset is None: > > # code to load dataset based on param, expensive > > > class ChildClass1(Base): > > def __init__(self): > > Base.__init__(self, data_params) > > > class AnotherChildClass(Base): > > def __init__(self): > > Base.__init__(self, other_data_params) > > > This seems to work, initialization is only done at the first creation > > of either class. I was just wondering if this is the 'pythonic' way > > to do this as my solution does feel a bit hackish. > > What should happen with code like:: > > ChildClass1('foo') > ChildClass1('bar') > > The 'param' is different, but 'dataset' should only get set the first time? > > STeVe ChildClass doesn't take the parameter in it's constructor, it supplies it for the BaseClass. Every ChildClass of the same type should use the same dataset. From gagsl-py2 at yahoo.com.ar Wed Jun 6 17:48:06 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 06 Jun 2007 18:48:06 -0300 Subject: ftplib error- Large file References: <1181147997.268014.50550@i38g2000prf.googlegroups.com> Message-ID: En Wed, 06 Jun 2007 13:39:57 -0300, escribi?: > I'm using ftplib to transfer large files to remote sites. The process > seems to work perfectly with small files, but when the file gets to > large ~20GB I begin getting errors that sometimes seem to be non- > fatal, and other times the transfer does not complete. I've debugged > the hell out of the code, and can't figure out what is going on..is it > the remote site? Packet loss? > > > IOError: [Errno 104] Connection reset by peer You always have to consider a connection failure - it's just more likely to happen on a big file. The REST ftp command is used to restart the transfer from a certain offset. -- Gabriel Genellina From robin at reportlab.com Mon Jun 4 07:58:30 2007 From: robin at reportlab.com (Robin Becker) Date: Mon, 04 Jun 2007 12:58:30 +0100 Subject: pyhon 2.5.1 build fails Message-ID: <4663FE66.7030507@chamonix.reportlab.co.uk> I am getting an error while building python-2.5.1 on a freebsd 6.1 machine as a normal user ./configure --prefix=/home/me/mypython --enable-unicode=ucs2 seems to work fine, but make install fails whilst running Compiling /home/my/mypython/lib/python2.5/test/test_module.py ... Compiling /home/me/mypython/lib/python2.5/test/test_multibytecodec.py ... Sorry: UnicodeError: ("\\N escapes not supported (can't load unicodedata module)",) Compiling /home/me/mypython/lib/python2.5/test/test_multibytecodec_support.py ... I see there was a bug reported about this http://www.mail-archive.com/python-bugs-list at python.org/msg09544.html but I didn't really understand what the resolution was. I do not have any special PYTHONHOME or PYTHONPATH set. The install partially works and I have a running python without the unicodedata module. Looking in Modules I don't see any unicodedata.o so I guess it's not being built for some reason. -- Robin Becker From twisted0n3 at gmail.com Wed Jun 27 10:43:02 2007 From: twisted0n3 at gmail.com (Twisted) Date: Wed, 27 Jun 2007 14:43:02 -0000 Subject: The Modernization of Emacs: terminology buffer and keybinding In-Reply-To: <4682570a.76573817@news.readfreenews.net> References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182272495.990807.99110@a26g2000pre.googlegroups.com> <87tzt3ihev.fsf@kobe.laptop> <1182370216.961241.6960@n60g2000hse.googlegroups.com> <85zm2ufjpb.fsf@lola.goethe.zz> <1182372592.803332.288260@u2g2000hsc.googlegroups.com> <1182549094.366282.286740@m37g2000prh.googlegroups.com> <87bqf7fwmg.fsf@telesippa.clsnet.nl> <1182553682.197778.138500@g37g2000prf.googlegroups.com> <87r6nzc9nu.fsf@mail.eng.it> <1182904631.083783.170640@o61g2000hsh.googlegroups.com> <87ir9924l5.fsf@mail.eng.it> <1182942279.999992.200250@q75g2000hsh.googlegroups.com> <4682570a.76573817@news.readfreenews.net> Message-ID: <1182955382.783515.167290@n60g2000hse.googlegroups.com> On Jun 27, 8:26 am, g... at mail.ru (Timofei Shatrov) wrote: > >For which you need an interpreter. Such as Ghostscript. Which is a > >pain to install and a bigger one to configure, even on Windoze. > > Lie. Ghostscript works out of the box on Windows. You're joking. First of all I am not a liar, and secondly, Ghostscript and Ghostview are tricky to set up correctly. I know -- I've done it a time or three. There's an arcane GUI configurator that isn't exceptionally well designed, and once it's working it still wonks out on maybe 1 in 10 .ps and .eps files you come across ... which is still better than being able to view none of them, mind you. Nonetheless there's a world of difference between the GS tools and say Adobe Acrobat Reader in terms of setup and use; the latter you just run an installer and then find a pdf to double-click; no other steps necessary and it works every time. Of course, Adobe stuff is proprietary, and acrord supports some types of evil DRM... From showell30 at yahoo.com Tue Jun 12 18:27:10 2007 From: showell30 at yahoo.com (Steve Howell) Date: Tue, 12 Jun 2007 15:27:10 -0700 (PDT) Subject: SimplePrograms challenge In-Reply-To: <87vedsua4o.fsf@merkury.smsnet.pl> Message-ID: <66273.23715.qm@web33508.mail.mud.yahoo.com> --- Rob Wolfe wrote: > Steven Bethard writes: > > > I'd hate to steer a potential new Python developer > > to a clumsier [...] > > [...] > But as far as HTML (not XML) is concerned this is > not very realistic solution. > I think both posted examples would be valuable on the page, with proper disclaimers. Feel free to post them: http://wiki.python.org/moin/SimplePrograms Without having used either library, it seems the older module is a bit more difficult to use for simple examples, but it is more robust in the face of real-world non-XML-compliant HTML, and it obviously more readibly usable for folks with older Python versions (which could even include newbies who are squatting on somebody else's machine). The newer module is easier to use in some cases, but it has the limitations of assuming some level of XML compliance and the availability of 2.5. Is there a third, better alternative out there somewhere? Also, is there a way to rewrite Rob's program so that it seems a little more straightforward, or was that necessary complexity even for the problem at hand? ____________________________________________________________________________________ No need to miss a message. Get email on-the-go with Yahoo! Mail for Mobile. Get started. http://mobile.yahoo.com/mail From tjreedy at udel.edu Sat Jun 9 03:40:42 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 9 Jun 2007 03:40:42 -0400 Subject: Python's "only one way to do it" philosophy isn't good? References: <1181368143.874341.273140@r19g2000prf.googlegroups.com> Message-ID: "WaterWalk" wrote in message news:1181368143.874341.273140 at r19g2000prf.googlegroups.com... | I've just read an article "Building Robust System" by Gerald Jay | Sussman. The article is here: | http://swiss.csail.mit.edu/classes/symbolic/spring07/readings/robust-systems.pdf | | In it there is a footprint which says: | "Indeed, one often hears arguments against building exibility into an | engineered sys- | tem. For example, in the philosophy of the computer language Python it | is claimed: For him to imply that Python is anti-flexibility is wrong. Very wrong.. He should look in a mirror. See below. | \There should be one|and preferably only one|obvious way to do | it."[25] Science does | not usually proceed this way: In classical mechanics, for example, one | can construct equa- | tions of motion using Newtonian vectoral mechanics, or using a | Lagrangian or Hamiltonian | variational formulation.[30] In the cases where all three approaches | are applicable they are | equivalent, but each has its advantages in particular contexts." And in those contexts, one would hope that the method with advantages is somehow the obvious way to do it. Otherwise beginners might become like Buriden's ass. So I dispute that science is as different as he claims. And I do not see any real value in the statement in that I do not see it saying anything useful to the reader, at least not in this snippet. | I'm not sure how reasonable this statement is and personally I like | Python's simplicity, power and elegance. So I put it here and hope to | see some inspiring comments. How much has Mr. Sussman actually programmed in Python and what actual problems did he find with the *implementation* of the philosophy? Without something concrete, the complaint is rather bogus. But here is what I find funny (and a bit maddening): G. J. Sussman is one of the inventers of the Lisp dialect Scheme, a minimalist language that for some things has only one way to do it, let alone one obvious way. Scheme would be like physics with only one of the three ways. After all, if they are equivalent, only one is needed. For example, consider scanning the items in a collection. In Python, you have a choice of recursion (normal or tail), while loops, and for statements. For statements are usually the obvious way, but the other two are available for personal taste and for specially situations such as walking a tree (where one might use recursion to write the generator that can then be used by for loops. In scheme, I believe you just have recursion. Since iteration and recursion are equivalent, why have both? Terry Jan Reedy From exhuma at gmail.com Tue Jun 12 05:34:49 2007 From: exhuma at gmail.com (exhuma.twn) Date: Tue, 12 Jun 2007 02:34:49 -0700 Subject: for ... else ? In-Reply-To: References: <1181622331.955264.31610@i38g2000prf.googlegroups.com> Message-ID: <1181640889.439145.60020@g37g2000prf.googlegroups.com> On Jun 12, 6:57 am, "Gabriel Genellina" wrote: > [...] > > for number in range(10,100): > is_prime = True > for divisor in range(2,number): > if number % divisor == 0: > is_prime = False > break > if is_prime: > print number, > > Next step: for loops have an optional "else" clause, that gets executed > whenever the loop exits normally (in this case, when divisor goes up to > number, and the break statement is never executed). So you don't need > is_prime: > > for number in range(10,100): > for divisor in range(2,number): > if number % divisor == 0: > break > else: > print number, > Oh my. Would it not be an idea to rename this "else" into a "finally"? As Gabriel points out, the else-block gets executed after the for loop exits *normally*. In that case, is the "else" not semantically misleading? I would surely misunderstand it if I saw it the first time. From bj_666 at gmx.net Tue Jun 12 16:34:07 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Tue, 12 Jun 2007 22:34:07 +0200 Subject: Simple Threading Example Doesn't Work (2.5.1) References: <1181676230.968353.63280@i38g2000prf.googlegroups.com> Message-ID: In <1181676230.968353.63280 at i38g2000prf.googlegroups.com>, Seun Osewa wrote: > I've tried to run several threading examples in Python 2.5.1 (with > Stackless) For example: > > import threading > > theVar = 1 > > class MyThread ( threading.Thread ): > > def run ( self ): > > global theVar > print 'This is thread ' + str ( theVar ) + ' speaking.' > print 'Hello and good bye.' > theVar = theVar + 1 > > for x in xrange ( 20 ): > MyThread().start() > > It doesn't work. It says there's an error in Queue.py in: > self.mutex=threading.Lock() > AttributeError: 'module' object has no attribute Lock > > The funny thing is that when I use the -O switch, it seems to work. > I'm baffled by this. What do you think is happening? Any chance that you have a module called `threading` that is not the one in the standard library? Perhaps you named the script above `threading.py`!? Ciao, Marc 'BlackJack' Rintsch From evan at yelp.com Fri Jun 22 13:57:02 2007 From: evan at yelp.com (Evan Klitzke) Date: Fri, 22 Jun 2007 10:57:02 -0700 Subject: howto run a function w/o text output? In-Reply-To: <1182531384.017220.218070@w5g2000hsg.googlegroups.com> References: <1182531384.017220.218070@w5g2000hsg.googlegroups.com> Message-ID: On 6/22/07, dmitrey wrote: > hi all, > I have a > y = some_func(args) > statement, and the some_func() produces lots of text output. Can I > somehow to suppress the one? > Thx in advance, D. In addition to the other solutions proposed, on a *nix system you can do os.close(1); os.close(2) to suppress output to stdout and stderr. -- Evan Klitzke From JohnRoth1 at jhrothjr.com Wed Jun 27 16:16:05 2007 From: JohnRoth1 at jhrothjr.com (John Roth) Date: Wed, 27 Jun 2007 13:16:05 -0700 Subject: Too many 'self' in python.That's a big flaw in this language. In-Reply-To: <1182942154.185461.89620@e9g2000prf.googlegroups.com> References: <1182942154.185461.89620@e9g2000prf.googlegroups.com> Message-ID: <1182975365.746344.69940@u2g2000hsc.googlegroups.com> On Jun 27, 5:02 am, "hide1... at gmail.com" wrote: > HI > I'm currently using Python. I find that a instance variable must > confined with self, > for example: > class a: > def __init__(self): > self.aa=10 > def bb(self): > print self.aa # See .if in c++,I could use aa to change that > variable > > That's a big inconvenience in coding ,especially when you have lot of > variable > If you method need 10 variables ,you have to type "self" for 10 times > and that also makes your variable longer. > > >From My point,I think this only help python interpreter to deside > > where to look for. > Is there anyone know's how to make the interpreter find instance name > space first? > Or any way to make programmer's life easier? Guido has already said that this will not change in Python 3.0 See PEP 3099. John Roth From pinkfloydhomer at gmail.com Tue Jun 19 09:47:40 2007 From: pinkfloydhomer at gmail.com (pinkfloydhomer at gmail.com) Date: Tue, 19 Jun 2007 13:47:40 -0000 Subject: Python and (n)curses In-Reply-To: <87myywyszg.fsf@benfinney.id.au> References: <1182211133.956524.160020@g4g2000hsf.googlegroups.com> <87y7igzapo.fsf@benfinney.id.au> <1182252362.643492.93890@n2g2000hse.googlegroups.com> <87myywyszg.fsf@benfinney.id.au> Message-ID: <1182260860.240519.3570@n60g2000hse.googlegroups.com> On Jun 19, 3:27 pm, Ben Finney wrote: > "pinkfloydho... at gmail.com" writes: > > Just to be more precise: curses is not a requirement, a > > multi-platform console library with a single API is. So are there > > alternatives to curses? Python-only or not. > You wouldn't happen to have an answer to this question? > > And as "peter" mentions, Python _could_ have such a library, > > abstracting away the implementation details of the particular > > platform. Can't see why that would be hard at all. > > And as "peter" mentions, it awaits only someone doing that work and > contributing it to Python. Those who can't see why it would be hard > are welcome to do so. > The classic answer. /David From cam.ac.uk at mh391.invalid Wed Jun 13 11:18:45 2007 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Wed, 13 Jun 2007 16:18:45 +0100 Subject: Optimizing constants in loops Message-ID: The peephole optimizer now takes things like if 0: do_stuff() and optimizes them away, and optimizes away the conditional in "if 1:". What if I had a function like this? def func(debug=False): for index in xrange(1000000): if debug: print index do_stuff(index) Could the "if debug" be optimized away on function invocation if debug is immutable and never reassigned in the function? When performance really matters in some inner loop, I usually move the conditional outside like this: def func(debug=False): if debug: for index in xrange(1000000): print index do_stuff(index) else: for index in xrange(1000000): do_stuff(index) It would be nice if this sort of thing could be done automatically, either by the interpreter or a function decorator. -- Michael Hoffman From mail at gedankenkonstrukt.de Thu Jun 14 06:50:06 2007 From: mail at gedankenkonstrukt.de (Thomas Wittek) Date: Thu, 14 Jun 2007 12:50:06 +0200 Subject: for web application development In-Reply-To: <1181812584.392929.232670@o11g2000prd.googlegroups.com> References: <1181812584.392929.232670@o11g2000prd.googlegroups.com> Message-ID: james_027: > My problem is looking for a web framework for python, that could > provide a natural way of developing web app. The three bigger Python web frameworks seem to be: - Django: http://www.djangoproject.com/ - TurboGears: http://www.turbogears.org/ - Pylons: http://pylonshq.com/ I only tried them briefly. Django has its own componentes for almost everything (templating, ORM, routing) and feels thus very integrated and solid. TurboGears tries to use independent components like Kid, SQLObject and CherryPy, which you can easily change to you own favorites. So you have more flexibility, but also a bit more complexity. Pylons is similar to TurboGears as it also uses independent components, that are by some people consideres more "modern". By default it uses SQLAlchemy for ORM and Routes for routing/dispatching. It also incorporates the Python WSGI standard for web apps. For me it felt least integrated of those frameworks but it may have the biggest future potentials. You may take a look at those comparisons: http://jesusphreak.infogami.com/blog/vrp1 http://www.ibm.com/developerworks/linux/library/l-django/ http://www.ibm.com/developerworks/linux/library/l-turbogears/ > I am avoiding to learn > template language as much as possible. You will need a templating language to put out your HTML. Of course that will not be a full programming language like PHP. -- Thomas Wittek http://gedankenkonstrukt.de/ Jabber: streawkceur at jabber.i-pobox.net From jan.m.danielsson at gmail.com Tue Jun 26 11:08:55 2007 From: jan.m.danielsson at gmail.com (Jan Danielsson) Date: Tue, 26 Jun 2007 17:08:55 +0200 Subject: Output XML buffer? In-Reply-To: <46809F28.1090801@web.de> References: <46803222$1@griseus.its.uu.se> <46809F28.1090801@web.de> Message-ID: <46812c07$1@griseus.its.uu.se> Stefan Behnel wrote: [---] > lxml.etree already implements that, BTW. > > http://codespeak.net/lxml Ok, thanks. I'll take a look at it. [---] > Some people propose just that if you really *want* a declaration. No need to > have it, though, as ET will create well-formed XML anyway. Yeah, I checked the specs, and found a '?' there (but not where I expected it to be). I just checked the first mention of the "header", and didn't see it marked as optional. However, I want it to be there, simply because it feels better. I'll check lxml out. -- Kind regards, Jan Danielsson From arkanes at gmail.com Wed Jun 6 11:45:36 2007 From: arkanes at gmail.com (Chris Mellon) Date: Wed, 6 Jun 2007 10:45:36 -0500 Subject: which "GUI module" you suggest me to use? In-Reply-To: References: <136bvigp2ps99bc@corp.supernews.com> Message-ID: <4866bea60706060845n43da02d5he49eca77ff92b127@mail.gmail.com> On 6/6/07, Samuel wrote: > On Wed, 06 Jun 2007 09:45:48 -0500, Chris Mellon wrote: > > > On 6/6/07, Samuel wrote: > > In the general case, wxWidgets wraps (not emulates) Gtk. I don't believe > > that there are any common controls left which are still emulated (maybe > > the list control? I'm not sure - I don't follow the bleeding edge of wx > > anymore). > > See my other response. Also, the fact that Gtk widgets are used does not > necessarily mean that the behavior is the same - you can still do all > kinds of weird stuff by hooking into the callbacks. Some of the > differences to Gtk were probably introduced to wx in order to have more > consistent behavior over different platforms. > This is true and in the specific case of triple click, wx does indeed report them to the application differently than gtk does. This doesn't, to my knowledge, interfere with text controls that don't try to handle the click, but it may result in inconsistent behavior with an app that adds triple click behavior to it's own text controls. > > wxPython (as opposed to wxWidgets, the C++ core) has a sizeable library > > of custom controls as part of its standard lib. Most of these are > > owner-drawn for various reasons and often won't appear native (Andrea > > Gavin, probably the most prolific custom control author, works primarily > > on Windows). > > This affects the C++ core as well. aMule (which is written in CPP) is one > particular complex example that exposes many of those problems when used > on Linux. > the aMule team makes heavy use of their own custom written controls - issues with it are not necessarily representative of the toolkit. The C++ core has very few controls which are entirely custom drawn, and those are generally controls which don't exist in the native platform. > >> > PyGTK works under Linux and Windows, but doens't use native widgets > >> > under Windows, so it won't look like a "normal" windows app. > >> > >> Gtk on Win32 can be themed to looked like Windows, AFAIK the Win32 > >> installer does this by default since a couple of months. > >> > >> > > That stretches the truth rather significantly. While the win32 theme > > does use the windows theme apis for drawing, it still has slightly > > different colors (especially window backgrounds and menus), and (more > > importantly) vastly and notably different behavior. > > Well, I have only tried Gaim on windows and could not tell the > difference. But then, I am not a regular Windows user. > > > Shortcuts are > > different, renderings are different, the Gtk drawing model is used > > instead of the windows one (leads to quite jarring repainting > > differences), different fonts, etc, etc. It looks okay in a screenshot > > but is clearly non-native and foreign in use. > > Sounds bad. It also sounds much like what I experienced with wx on Linux. > I regularly use wxGTK and wxPython under linux with gnome (it's my sole desktop at home - I only use windows at work). The differences are orders of magnitude in severity. One common problem is that people use incorrect (but working on Windows) code and don't test under linux, it can cause similar issues. The *toolkit* is very strong on all platforms. Individual apps are often much less strong, because relatively view developers have access and motivation to test heavily on all platforms. wx tries to make correct code work the same on all platforms, but it can't make incorrect code fail the same way on all platforms. And, of course, many people simply aren't familiar with or choose not to use the APIs that wx provides for whatever reason. Custom controls that don't use native fonts are fairly common, for example, even though wx provides APIs to retrieve the correct fonts and the use of them is encouraged - people just hardcode whatever they "know" the right font is on their native platform. From jstroud at mbi.ucla.edu Fri Jun 22 19:06:02 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Fri, 22 Jun 2007 16:06:02 -0700 Subject: newb: Scope Question In-Reply-To: <1182552834.987916.293260@a26g2000pre.googlegroups.com> References: <1182552834.987916.293260@a26g2000pre.googlegroups.com> Message-ID: johnny wrote: > Scope of ids: > When I print "ids", it's always empty string '', as I have intialized > before. That's not what I want. I want the ids to have > str(r['id']).join(',') > > if res: > ids = '' > for r in res['key']: > ids = str(r['id']).join(',') > > print("ids: %s" %(ids)) > 1. You do not need to "initialize" ids. 2. It looks as if res['key'] is empty. 3. Are you sure you don't mean "res[key]"? 4. "ids" and "(ids)" are equivalent. 5. Are you sure you don't want to indent the print statement? James From kyosohma at gmail.com Mon Jun 4 15:50:11 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Mon, 04 Jun 2007 12:50:11 -0700 Subject: get_traceback In-Reply-To: <1180977780.997361.133320@g37g2000prf.googlegroups.com> References: <1180977780.997361.133320@g37g2000prf.googlegroups.com> Message-ID: <1180986611.663566.213550@m36g2000hse.googlegroups.com> On Jun 4, 12:23 pm, half.ital... at gmail.com wrote: > Hi, > > Is there a function or idoim for returning an exception/traceback > rather than just printing it to stdout? I'm running a deamon where > stdout is going to /dev/null, and I'm not even watching it..until > now. All the functions I found in traceback and sys seemed only to > print the error rather than just returning it, so I resorted to this: > > def get_traceback(): > import traceback, tempfile > stdout = sys.stdout > > f = tempfile.TemporaryFile(mode='w+') > sys.stdout = f > > traceback.print_tb(sys.exc_info()[2]) > error = f.read() > f.close() > > sys.stdout = stdout > return error > > Whats the right function?!? Thanks. > > ~Sean I use the traceback module as you do and I usually have it email the traceback to me if there's an error. You could also have the script redirect stdout to a file object. Mike From rschroev_nospam_ml at fastmail.fm Mon Jun 4 13:38:43 2007 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Mon, 04 Jun 2007 17:38:43 GMT Subject: Python, Dutch, English, Chinese, Japanese, etc. In-Reply-To: <1180963963.036424.62850@q69g2000hsb.googlegroups.com> References: <1180958764.491893.130160@h2g2000hsg.googlegroups.com> <1180963963.036424.62850@q69g2000hsb.googlegroups.com> Message-ID: olive schreef: > Lol! > > What is a "sharp hair boss" ? Pointy-haired boss, see http://en.wikipedia.org/wiki/Pointy_Haired_Boss -- If I have been able to see further, it was only because I stood on the shoulders of giants. -- Isaac Newton Roel Schroeven From half.italian at gmail.com Wed Jun 6 03:51:47 2007 From: half.italian at gmail.com (half.italian at gmail.com) Date: Wed, 06 Jun 2007 07:51:47 -0000 Subject: Who uses Python? In-Reply-To: <46647a59$0$5860$da0feed9@news.zen.co.uk> References: <1180985830.288414.208850@q69g2000hsb.googlegroups.com> <46647a59$0$5860$da0feed9@news.zen.co.uk> Message-ID: <1181116307.775900.264570@q19g2000prn.googlegroups.com> On Jun 4, 1:47 pm, Mark Carter wrote: > walterbyrd wrote: > > Anything else? Finance? Web-analytics? SEO? Digital art? > > I played with NodeBox a little while ago:http://nodebox.net/code/index.php/Home > "NodeBox is a Mac OS X application that lets you create 2D visuals > (static, animated or interactive) using Python programming code and > export them as a PDF or a QuickTime movie. NodeBox is free and > well-documented." > > Pretty trippy stuff. Thanks for the link. Neato. From twisted0n3 at gmail.com Tue Jun 26 03:40:55 2007 From: twisted0n3 at gmail.com (Twisted) Date: Tue, 26 Jun 2007 07:40:55 -0000 Subject: The Modernization of Emacs: terminology buffer and keybinding In-Reply-To: <873b0fhokz.fsf@kobe.laptop> References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182272495.990807.99110@a26g2000pre.googlegroups.com> <87tzt3ihev.fsf@kobe.laptop> <1182370216.961241.6960@n60g2000hse.googlegroups.com> <85zm2ufjpb.fsf@lola.goethe.zz> <1182372592.803332.288260@u2g2000hsc.googlegroups.com> <1182549094.366282.286740@m37g2000prh.googlegroups.com> <87bqf7fwmg.fsf@telesippa.clsnet.nl> <1182553682.197778.138500@g37g2000prf.googlegroups.com> <873b0fhokz.fsf@kobe.laptop> Message-ID: <1182843655.378325.275610@q75g2000hsh.googlegroups.com> On Jun 25, 2:32 pm, Giorgos Keramidas wrote: > > So much for the "free" in "free software". If you can't actually use > > it without paying money, whether for the software or for some book, it > > isn't really free, is it? > > Please do not confuse the term 'free' in 'free software' with 'gratis'. > > 'Gratis', i.e. 'lacking a monetary price tag' is something *very* > different from the meaning of 'free' in 'free software'. Having to pay for the documentation, presumably because it's copyrighted, doesn't strike me as much more "free as in speech" than it is "free as in beer". Also being dependent on a particular publisher for access to required documentation violates "free as in no vendor lock-in", to boot. So anyone saying some "free" software is unusable without such-and-such an O'Reilly book can go peddle the software and the book somewhere where spammers are welcome. Being locked in to O'Reilly being just as bad as being locked in to Microsoft or Adobe. From roy at panix.com Thu Jun 28 10:56:59 2007 From: roy at panix.com (Roy Smith) Date: Thu, 28 Jun 2007 10:56:59 -0400 Subject: equality & comparison by default (was Re: Too many 'self' in python.That's a big flaw in this language.) References: <1182942154.185461.89620@e9g2000prf.googlegroups.com> <1i0cy8z.z94q5d1dxgexxN%aleax@mac.com> Message-ID: In article , "A.T.Hofkamp" wrote: > In object oriented programming, objects are representations of values, and the > system shouldn't care about how many instances there are of some value, just > like numbers in math. Every instance with a certain value is the same as every > other instance with the same value. Whether two things are equal depends on the context. Is one $10 note equal to another? It depends. If the context is a bank teller making change, then yes, they are equal. What's more, there are lots of sets of smaller notes which would be equally fungible. If the context is a district attorney showing a specific $10 note to a jury as evidence in a drug buy-and-bust case, they're not. It's got to be exactly that note, as proven by a recorded serial number. In object oriented programming, objects are representations of the real world. In one case, the $10 note represents some monetary value. In another, it represents a piece of physical evidence in a criminal trial. Without knowing the context of how the objects are going to be used, it's really not possible to know how __eq__() should be defined. Let me give you a more realistic example. I've been doing a lot of network programming lately. We've got a class to represent an IP address, and a class to represent an address-port pair (a "sockaddr"). Should you be able to compare an address to a sockaddr? Does 192.168.10.1 == 192.168.10.1:0? You tell me. This is really just the "does 1 == (1 + 0j)" question in disguise. There's reasonable arguments to be made on both sides, but there is no one true answer. It depends on what you're doing. From chowroc.z+l at gmail.com Thu Jun 21 23:49:10 2007 From: chowroc.z+l at gmail.com (Roc Zhou) Date: Fri, 22 Jun 2007 11:49:10 +0800 Subject: gettext and __doc__ for class methods? Message-ID: <7847e5160706212049y33fbd2a8q6c48fd1ecf85c29e@mail.gmail.com> from gettext import gettext as _ __doc__ = _("""module docstrings""") class test: __doc__ = _("""class docstrings""") def __setattr__(self, attr_name, value): _("""class method docstrings""") But I found when the module and class docstrings take effect(must use __doc__ to specify it), the class-method gettext docstrings takes no effect, only: def __setattr__(self, attr_name, value): """class method only english docstrings""" has effect. So any suggestions? Thanks. -------------- next part -------------- An HTML attachment was scrubbed... URL: From ryankaskel at gmail.com Tue Jun 5 09:39:17 2007 From: ryankaskel at gmail.com (Ryan K) Date: Tue, 05 Jun 2007 13:39:17 -0000 Subject: Embedding interactive interpreter Message-ID: <1181050757.146862.113550@g4g2000hsf.googlegroups.com> Hi. I am trying to embed an interactive interpreter in a C++ application. I need to capture the output of int PyRun_InteractiveOne(FILE *fp, const char *filename). Is redirecting sys.stdout and sys.stderr after initializing the interpreter the best way to do this? Thanks, Ryan From pruyu.chen at gmail.com Wed Jun 13 05:11:27 2007 From: pruyu.chen at gmail.com (Allen) Date: Wed, 13 Jun 2007 02:11:27 -0700 Subject: How to format a string from an array? Message-ID: <1181725887.936450.108920@n15g2000prd.googlegroups.com> a = range(256) I want to output the formated string to be: 00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f 10 11 12 13 14 15 16 17 18 19 1a 1b 1c 1d 1e 1f ........................................................................ f0 f1 f2 f3 f4 f5 6 f7 f8 f9 fa fb fc fd fe ff How to do it? From teroV at nowhere.invalid Mon Jun 18 14:28:21 2007 From: teroV at nowhere.invalid (TeroV) Date: Mon, 18 Jun 2007 21:28:21 +0300 Subject: Line Wrapping In-Reply-To: References: Message-ID: <4676cec6$0$1435$39db0f71@news.song.fi> Evan Klitzke wrote: > All, > > Mail messages should be wrapped at 78 characters (as suggested in RFC > 2822). I want my python batch scripts/cron jobs to enforce this > behavior, and format the mail that is sent out so that newline > characters are inserted as appropriate to keep line lengths at 78 > characters or less. I wrote a function to take a string and format it > in this manner, but it seemed a bit awkward and un-Python like (my > background is mostly C, and the function looks very much like C code). > I'd imagine that there's probably a short, succinct, more elegant > solution using regular expressions or some module that is unknown to > me. Does anyone have any clean, short solutions to this problem? > Does textwrap module has what you need? >>> import textwrap >>> textwrap.wrap('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 78) ['aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'] >>> textwrap.wrap('This is a very long String. A linewrap module has couple functions which might help you to accoplish your goal. HTH', 78) ['This is a very long String. A linewrap module has couple functions which might', 'help you to accoplish your goal. HTH'] From jan.m.danielsson at gmail.com Mon Jun 25 17:22:41 2007 From: jan.m.danielsson at gmail.com (Jan Danielsson) Date: Mon, 25 Jun 2007 23:22:41 +0200 Subject: Output XML buffer? Message-ID: <46803222$1@griseus.its.uu.se> Hello all, I'm using ElementTree to create an XHTML page (mod_python, blah, blah, blah). When I use ElementTree.tostring(root) to create a buffer which I want to return to the client, it doesn't include the XML prolog (obvisouly, since tostring is merely traversing the tree from the node I supply to it. I could simply prefix the tostring output with a string containing my "" schtick. But let's, for the sake of argument, say that I trust a library more to generate it for me, rather than hand coding it myself (not entirely true, but let's assume that is the case). -- Kind regards, Jan Danielsson From pythonwin.ru at gmail.com Thu Jun 7 13:06:54 2007 From: pythonwin.ru at gmail.com (pythonwin pythonwin) Date: Thu, 7 Jun 2007 23:06:54 +0600 Subject: pyExcelerator Protection insert_bitmap Message-ID: <71582220706071006g58080e43s790628fa8f937cc3@mail.gmail.com> Good evening! say, please, as in *.xls to insert an unscreened picture? example: image.py but a picture in OpenOficce is not represented :( OS - windows XP, debian etch pyExcelerator 0.6.3a-1 -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: image.py Type: text/x-python Size: 869 bytes Desc: not available URL: From tundra at tundraware.com Fri Jun 1 16:40:55 2007 From: tundra at tundraware.com (Tim Daneliuk) Date: Fri, 01 Jun 2007 15:40:55 -0500 Subject: [ANN]: 'twander' Cross-Platform File Manager Version 3.224 Released And Available Message-ID: 'twander' Version 3.224 is now released and available for download at: http://www.tundraware.com/Software/twander The last public release was 3.210. This release fixes a number of bugs and adds a variety of useful new features. See the WHATSNEW.txt file for all the details. --------------------------------------------------------------------- What Is 'twander'? ------------------ 'twander' is a macro-programmable Filesystem Browser that runs on both Unix-like systems as well as Win32 systems. It embraces the best ideas of both similar GUI-driven programs (Konqueror, Windows Explorer) as well as text-based interfaces (Midnight Commander, List, Sweep). Or, If You Prefer The "Elevator Pitch" -------------------------------------- 'twander' is: - A better file browser for Unix and Win32. (Tested on FreeBSD, Linux, Win32. Probably works on Mac OS/X, but not tested.) - A way to make browsing the same on all the OSs you use. - A macro-programmable tool that lets *you* define the features. - A GUI navigation front-end for your shell. - A way to "can" workflows for your technically-challenged colleagues. - A way to free yourself from the shackles of the mouse. - A way to significantly speed up your day-to-day workflow. - A Python/Tkinter application - about 5000 lines of code/comments - A RCT (Really Cool Tool) that will have you addicted in a day or two See the web page for more information, a screen shot, and the complete documentation. --------------------------------------------------------------------- Complete details of all fixes, changes, and new features can be found in the WHATSNEW.txt and documentation files included in the distribution. Users are strongly encouraged to join the twander-users mailing list as described in the documentation. A FreeBSD port has been submitted as well. From wildemar at freakmail.de Sat Jun 2 09:15:09 2007 From: wildemar at freakmail.de (Wildemar Wildenburger) Date: Sat, 02 Jun 2007 15:15:09 +0200 Subject: Observer-Pattern by (simple) decorator In-Reply-To: <1180781727.519949.172580@q75g2000hsh.googlegroups.com> References: <1180781727.519949.172580@q75g2000hsh.googlegroups.com> Message-ID: <46616D5D.1000604@freakmail.de> David Wahler wrote: > Is this desired behavior? > > >>>> a = SomeActor() >>>> b = SomeActor() >>>> a.meth.observers is b.meth.observers >>>> > True > No it's not, but I get >>> a = SomeActor() >>> b = SomeActor() >>> a.meth.observers is b.meth.observers False I don't see how your behaviour should come about ... a new observer-list is created for every decorated method, so there is no problem. Now I'm confused ?-| /W From james.harris.1 at googlemail.com Fri Jun 22 16:33:04 2007 From: james.harris.1 at googlemail.com (James Harris) Date: Fri, 22 Jun 2007 13:33:04 -0700 Subject: Portable general timestamp format, not 2038-limited Message-ID: <1182544384.709759.235300@o11g2000prd.googlegroups.com> I have a requirement to store timestamps in a database. Simple enough you might think but finding a suitably general format is not easy. The specifics are 1) subsecond resolution - milliseconds or, preferably, more detailed 2) not bounded by Unix timestamp 2038 limit 3) readable in Java 4) writable portably in Perl which seems to mean that 64-bit values are out 5) readable and writable in Python 6) storable in a free database - Postgresql/MySQL The formats provided by the two database systems are such as 8-byte or 12-byte values which, even if I could get Perl to work with I guess it would be messy. Keeping to 32-bit values should give me portability and be easy enough to work with without obscuring the program logic. Since 32 bits of microseconds is less than 50 days I have to store two 32-bit values. How to split them? The option I favour at the moment is to split days and parts of days like this: a) store, as a 32-bit number, days since a virtual year zero (there is no year zero in common era time ). This allows over five million years plus and minus. Still not completely general, I know. b) store parts of days as another 32-bit value. Its range would have to go to 86401 seconds - the number of seconds in a leap day. This means each 'tick' would be around 21 microseconds. For regularity I could make the ticks 25 microseconds so there would be 40,000 in a second and 3,456,000,000 in a day; and, finally, the counter could tick about 5 hours into the next day if not caught. Any thoughts on a better way to do this? (Please reply-all. Thanks). -- James From nikbaer at gmail.com Tue Jun 19 13:37:41 2007 From: nikbaer at gmail.com (nik) Date: Tue, 19 Jun 2007 17:37:41 -0000 Subject: serial readline thread IO Error (9, 'Bad file descriptor') Message-ID: <1182274661.534928.230420@i13g2000prf.googlegroups.com> Hi, How can I close a thread that is waiting on a file/port down gracefully, and not have an IO error pop up? I am having trouble closing a thread that is listening to the serial port. I have a thread that calls uses a pySerial serial port and calls readline() without a timeout, which is blocking. When I am shutting down the application I close the serial port, which causes the IO error: (9, 'Bad file descriptor'). It makes sense that we would get this error, because it is trying to read off of a closed 'file'. Is there a better way to close this thread and port down? Thanks, Nik From __peter__ at web.de Mon Jun 4 06:57:27 2007 From: __peter__ at web.de (Peter Otten) Date: Mon, 04 Jun 2007 12:57:27 +0200 Subject: subexpressions (OT: math) References: <4662675b$1_5@news.bluewin.ch> <1180890214.317409.85100@w5g2000hsg.googlegroups.com> <1180894045.538031.111610@g4g2000hsf.googlegroups.com> <1180895200.108582.313010@k79g2000hse.googlegroups.com> Message-ID: Wildemar Wildenburger wrote: > Peter Otten wrote: >> With y = x^2 = 1/3 pi^2 - 4(cos x - cos(2x)/2^2 + cos(3x)/3^2 - ...) >> >> area is dimensionless, too, I suppose. >> > > Ehr, ... maybe this is obvious, but I don't see it: Please explain the > second equality sign. I know not much more about Fourier series than that they do exist, so let me refer you to http://en.wikipedia.org/wiki/Fourier_series for a general explanation, and to http://www.exampleproblems.com/wiki/index.php/FS6 for the series given above. Peter From ed at leafe.com Fri Jun 8 07:25:19 2007 From: ed at leafe.com (Ed Leafe) Date: Fri, 8 Jun 2007 07:25:19 -0400 Subject: wxPython / Dabo demo shell ? In-Reply-To: <4646a$466901e6$83aef404$30670@news2.tudelft.nl> References: <4646a$466901e6$83aef404$30670@news2.tudelft.nl> Message-ID: On Jun 8, 2007, at 3:14 AM, stef wrote: > I was impressed by the demo shell of wxPython, > and a few days ago (finally getting Dabo to work), > I saw Dabo uses the same demo shell. > > Is there any more information available about this shell, > because it seems a very nice / good way to show > (many) demos, in an organized way to newbies. There isn't a common shell. I wrote DaboDemo from scratch, using the Dabo Class Designer visual tools; you can actually open up the demo in the Class Designer and edit the entire thing! I just thought that the wxPython demo was such a great way to explore wxPython and try out new things that I blatantly copied it. ;-) -- Ed Leafe -- http://leafe.com -- http://dabodev.com From bscrivener42 at gmail.com Wed Jun 20 17:35:21 2007 From: bscrivener42 at gmail.com (BartlebyScrivener) Date: Wed, 20 Jun 2007 21:35:21 -0000 Subject: The Modernization of Emacs In-Reply-To: <1182372821.298343.316860@g4g2000hsf.googlegroups.com> References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182370894.001918.36590@k79g2000hse.googlegroups.com> <1182372821.298343.316860@g4g2000hsf.googlegroups.com> Message-ID: <1182375321.067664.190780@o61g2000hsh.googlegroups.com> On Jun 20, 3:53 pm, Twisted wrote: > On Jun 20, 4:21 pm, BartlebyScrivener wrote: > > > On Jun 17, 10:13 am, Xah Lee wrote: > > > > [this post is a excerpt from > > > The Modernization of Emacs > > > ---------------------------------------- > > > SIMPLE CHANGES > > > At the command line, change "emacs" to "gvim" > > Out of the frying pan and into the fire... Nah. http://www.debian-administration.org/polls/89 From half.italian at gmail.com Thu Jun 7 06:50:34 2007 From: half.italian at gmail.com (half.italian at gmail.com) Date: Thu, 07 Jun 2007 10:50:34 -0000 Subject: get a list from a string In-Reply-To: References: Message-ID: <1181213434.814684.236770@q19g2000prn.googlegroups.com> On Jun 7, 3:34 am, simon kagwe wrote: > Hi, > > I have a string "distances = [[1,1,1,1],[2,2,2,2]]". I want to create a > variable called distances whose value is the list [[1,1,1,1],[2,2,2,2]]. How can > I go about that? I know I can use setattr, but how do I create the list from the > string? > > Regards, > Simon exec("distances = [[1,1,1,1],[2,2,2,2]]") ~Sean From andre.roberge at gmail.com Thu Jun 21 06:49:51 2007 From: andre.roberge at gmail.com (=?iso-8859-1?B?QW5kcuk=?=) Date: Thu, 21 Jun 2007 10:49:51 -0000 Subject: Python live environment on web-site? In-Reply-To: <1182405635.091199.180950@i13g2000prf.googlegroups.com> References: <46794396.442103@news.netcologne.de> <1182405635.091199.180950@i13g2000prf.googlegroups.com> Message-ID: <1182422991.388251.249110@o61g2000hsh.googlegroups.com> On Jun 21, 3:00 am, "tleeuwenb... at gmail.com" wrote: > On Jun 21, 1:18 am, Thomas.Len... at netcologne.de (Thomas Lenarz) wrote: > > > > > Hi all, > > > I was wondering if there was a python-live-environment available on a > > public web-site similar to the ruby-live-tutorial on > > >http://tryruby.hobix.com/ > > > I would prefer something which allows to paste small scripts into a > > text-field, to run them on the server, and to be able to read the > > produced output of the script. > > > I searched using google but didn't come across such a site. However, I > > imagine there must be at least one.... > > > Thanks for any hint, > > > Thomas > > Crunchy. Unfortunately, as far as I know, Crunchy is not (yet) hosted on any publicly accessible server. Here are two "try Python" sites: http://www.datamech.com/devan/trypython/trypython.py http://www.mired.org/home/mwm/try_python/ If you want to know more about Crunchy, the latest version is located at code.google.com/p/crunchy Andr? From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Tue Jun 19 17:06:47 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Tue, 19 Jun 2007 23:06:47 +0200 Subject: Python IDE References: <1182249585.535675.143460@m36g2000hse.googlegroups.com> <1182259143.375798.283620@k79g2000hse.googlegroups.com> <5dq3n9F359hp0U1@mid.individual.net> Message-ID: <5dqur8F35956oU2@mid.individual.net> William Allison wrote: > Not a tutorial, but I found this little snippet: > > http://www.ibiblio.org/obp/pyBiblio/tips/elkner/vim4python.php > > I thought the last line was especially neat. Nice. Thanks to you two, I'm going to try that out. Regards, Bj?rn -- BOFH excuse #414: tachyon emissions overloading the system From ppaterson at gmail.com Wed Jun 6 14:58:41 2007 From: ppaterson at gmail.com (Paul Paterson) Date: Wed, 06 Jun 2007 11:58:41 -0700 Subject: SOLVED: Can os.remove followed by os.path.isfile disagree? In-Reply-To: <1181151151_16897@sp12lax.superfeed.net> References: <1181140547.279974.83550@q66g2000hsg.googlegroups.com> <1181151151_16897@sp12lax.superfeed.net> Message-ID: <1181156321.175499.281200@o11g2000prd.googlegroups.com> On Jun 6, 12:30 pm, "Roger Upole" wrote: > ppater... at gmail.com wrote: > > Can os.path.isfile(x) ever return True after os.remove(x) has > > successfully completed? (Windows 2003, Python 2.3) > > Yes. If another application has opened the file with FILE_SHARE_DELETE, > os.remove succeeds but the file doesn't actually disappear until the last open > handle to it is closed. > Roger, Thanks - you've hit the nail on the head. This is the final piece of the puzzle and I've now been able to reproduce the problem! The cause is ... - a TSVCache.exe (Tortoise SVN) process is scanning the file with FILE_SHARE_DELETE access at the moment that the os.remove occurs - this causes os.remove to return but the file is still there while the scan completes - next, os.path.isfile returns True and the app raises an exception - a short while later the scan is complete and Windows deletes the file Thanks to everyone who responded - I didn't expect to be able to get to the bottom of this so quickly! Thanks, Paul From simonkagwe at yahoo.com Thu Jun 7 06:34:24 2007 From: simonkagwe at yahoo.com (simon kagwe) Date: Thu, 7 Jun 2007 10:34:24 +0000 (UTC) Subject: get a list from a string Message-ID: Hi, I have a string "distances = [[1,1,1,1],[2,2,2,2]]". I want to create a variable called distances whose value is the list [[1,1,1,1],[2,2,2,2]]. How can I go about that? I know I can use setattr, but how do I create the list from the string? Regards, Simon From bj_666 at gmx.net Tue Jun 12 06:31:00 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Tue, 12 Jun 2007 12:31:00 +0200 Subject: A gotcha: Python pain point? References: <1181604836.292323.154510@z28g2000prd.googlegroups.com> Message-ID: In , Terry Reedy wrote: > | Should I import this to see how > | many principles this behavior violates? > > ??? > > If you meant 'report' (on SF), please do not. I think he meant ``import this`` at the Python interpreter. Ciao, Marc 'BlackJack' Rintsch From bruno.42.desthuilliers at wtf.websiteburo.oops.com Thu Jun 28 11:42:30 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Thu, 28 Jun 2007 17:42:30 +0200 Subject: listing the type of an object In-Reply-To: References: <71af3$4682d18c$d443bb3a$9028@news.speedlinq.nl> <46836088$0$29024$426a74cc@news.free.fr> Message-ID: <4683d6d1$0$8993$426a74cc@news.free.fr> Neil Cerutti a ?crit : > On 2007-06-28, Bruno Desthuilliers wrote: >> Stef Mientki a ?crit : >>> How can I list a type of an object instance ? >>> >>> I tried: >>> >>> class tLED (tDevice): >> >> Do yourself (and the world) a favour and give up hungarian notation... >> This should be: >> >> class Led(Device): >> #... > > Using a naming convention for class objects, e.g., camel-case, is > a practice very similar to hungarian notation. And it's not even totally consistant since builtin types are usually lowercase. But it's still the convention. > I would've said something like: start learning the Python > community's naming conventions, and use those instead of > inventing your own. The TMyType convention comes from Delphi. So let's make this: """ start learning the Python community's naming conventions, and use those instead of the ones of your usual language """ !-) From bj_666 at gmx.net Tue Jun 12 06:24:40 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Tue, 12 Jun 2007 12:24:40 +0200 Subject: Accessing attributes? References: Message-ID: In , Jeff Rollin wrote: > (Initializing Calamity Jane) > Traceback (most recent call last): > ? File "/home/jef/bin/objvar.py", line 49, in > ? ? Person.how_many() > AttributeError: class Person has no attribute 'how_many' > > Where am I going wrong? Looking at the indention of the code I would say you just have an `__init__()` and all other ``def``\s are local functions to that method. Ciao, Marc 'BlackJack' Rintsch From basti.wiesner at gmx.net Sat Jun 30 13:14:59 2007 From: basti.wiesner at gmx.net (Sebastian Wiesner) Date: Sat, 30 Jun 2007 19:14:59 +0200 Subject: Building a Python app with Mozilla In-Reply-To: <5emhodF380g5gU2@mid.uni-berlin.de> References: <5emhodF380g5gU2@mid.uni-berlin.de> Message-ID: <200706301915.04133.basti.wiesner@gmx.net> [ "Diez B. Roggisch" ] > > I'd like to build a Python GUI app. Neither Tkinter nor Wxpython nor > > PyQT are actually what I want (because the lack of GUI builders and > > they don't really look good on Windows and Linux). > > The latter statement is bogus. Qt is THE native look on KDE. GTK for > Gnome. So how is it not "looking good on linux"? I guess, "not looking good on linux" refers to Tkinter, which is in fact really ugly on linux systems. > And as it has been said in this thread already, Qt has an excellent free > GUI-builder. So have Gtk and WxWidgets. -- Freedom is always the freedom of dissenters. (Rosa Luxemburg) -------------- 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 11 20:55:35 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 11 Jun 2007 21:55:35 -0300 Subject: Python for embedded systems with memory constraints References: <1181430148.793716.110350@q69g2000hsb.googlegroups.com> Message-ID: En Mon, 11 Jun 2007 15:59:19 -0300, vishnu escribi?: > So now I only see the solution to clear my memory pool and restart Python > without restarting the system (i.e. no power cycle to hardware). I tried > to > do this when my memory pool is 60% used in these steps: > 1) Py_Finalize( ) > 2) Reset my Memory pool (i.e. free list links) > 3) Then Restart Python by calling Py_Initialize(). > > But this resulted in Python crash during Py_Initialize(), where I found > that the static variables within embedded Python source code are still > holding some of the references to my memory pool. So now my question is > how > do I restart Python (i.e. reinitialize Python) without restarting whole > system. Is there a way to reset/re-initilaize those static variables such > that it will be possible to re-Initialize Python. Ouch... I think this should not happen, but anyway I don't know if this was a design principle. One should inspect all Python code to locate all static variable references... Maybe you could instrument your allocator to see which references are still held? C extensions may be problematic too - there is no way to "uninitialize" them, and nothing forbids an extension to hold a reference to any object. -- Gabriel Genellina From steve at REMOVE.THIS.cybersource.com.au Sun Jun 10 23:22:28 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Mon, 11 Jun 2007 13:22:28 +1000 Subject: Python's "only one way to do it" philosophy isn't good? References: <1181368143.874341.273140@r19g2000prf.googlegroups.com> Message-ID: On Mon, 11 Jun 2007 01:28:09 +0100, Alexander Schmolck wrote: > Steven D'Aprano writes: > >> On Sat, 09 Jun 2007 22:42:17 +0100, Alexander Schmolck wrote: >> >>>> As for why tail calls are not optimized out, it was decided that being able >>>> to have the stack traces (with variable information, etc.) was more useful >>>> than offering tail call optimization >>> >>> I don't buy this. >> >> Do you mean you don't believe the decision was made, or you don't agree >> with the decision? > > Neither. I don't believe the rationale stated in this thread to be the true > reason. Don't keep us in suspense. What do you believe is the true reason? >> Are you volunteering? If you are, I'm sure your suggestion will be welcomed >> gratefully. > > I rather doubt it. Guido has stated quite clearly that his not > interested in incorporating this feature. He's not the only one who gets to make these decisions. But even if he uses his veto to prevent tail-recursion optimization from being put into the main branch, there are other options. >>>> (do what I say). >>> >>> Where did you say run out of memory and fail? More importantly how do >>> you say "don't run out of memory and fail"? >> >> If we can live with a certain amount of "arbitrary failures" in simple >> arithmetic, > > I prefer not too, and thus when possible avoid to use languages where > ``a + b`` is liable to fail arbitrarily (such as C, where the behavior > will often be undefined). That's not the sort of arbitrary failure I was discussing, but for that matter Python is one of those languages. Perhaps Python is not the language for you? Correct me if I'm wrong, but surely it is C++ that can have arbitrary behaviour for "a + b", not C? >> then the world won't end if tail recursion isn't optimized away by the >> compiler. > > I'd personally much rather have arithmetic working properly. > Unfortunately this is not an option at the moment, although quite a few > smart people are working on it and although it is an immensely costly > problem. > >> You can always hand-optimize it yourself. > > Not tail calls, in general, no. Sorry, how does that work? You're suggesting that there is an algorithm which the compiler could follow to optimize away tail-recursion, but human beings can't follow the same algorithm? Now I'm confused. -- Steven. From basilisk96 at gmail.com Fri Jun 8 19:33:13 2007 From: basilisk96 at gmail.com (Basilisk96) Date: Fri, 08 Jun 2007 23:33:13 -0000 Subject: interating over single element array In-Reply-To: References: <4Beai.13210$5j1.6184@newssvr21.news.prodigy.net> Message-ID: <1181345593.788652.275380@h2g2000hsg.googlegroups.com> On Jun 8, 11:54 am, "T. Crane" wrote: > >> any suggestions are appreciated, > > > Yes, don't try iterating over objects that are not iterable. ;-) > > Ah, yes... I hadn't thought of that :) > > thanks, > trevis > > > > > What you *can* do is iterating over lists, tuples or other iterables with > > just one element in them. Try ``a = [1]``. > > > Ciao, > > Marc 'BlackJack' Rintsch You can also do this (if tuples are okay in your case): a = 1, The comma turns 'a' into a tuple (1,) which is both iterable and has a length of 1. I have run into this issue before with a function that took a list of filenames (strings), and needed to iterate over the list to operate on the input files. For the case when the input would be a single file, I needed to turn the input string into an iterable such that the 'for' loop would not iterate on the filename characters (a rather undesirable gotcha, you understand :-) ). So I solved my problem like this: def loadfiles(filelist): if not isinstance(filelist, list): filelist = filelist, for filename in filelist: f = open(filename,'r') #do interesting stuff with file, etc... ..and it's been working very well. Cheers, -Basilisk96 From sjmachin at lexicon.net Sun Jun 17 05:25:15 2007 From: sjmachin at lexicon.net (John Machin) Date: Sun, 17 Jun 2007 02:25:15 -0700 Subject: Goto In-Reply-To: References: <1181762459.749538.151730@z28g2000prd.googlegroups.com> Message-ID: <1182072315.357124.13560@q19g2000prn.googlegroups.com> On Jun 14, 4:32 pm, "Hendrik van Rooyen" wrote: [snip] > > Anything more fancy is "Verboten" - except, that, if you ask nicely, > John Machin might explain his comefrom construct. > > And maybe I will understand it this time around... Hendrik, if you google for 'comefrom' in this newsgroup, you will get several threads. However if you google for 'Machin comefrom' the only hit is the above posting. You must be confusing me with somebody else. Cheers, John From josiah.carlson at sbcglobal.net Fri Jun 15 17:52:06 2007 From: josiah.carlson at sbcglobal.net (Josiah Carlson) Date: Fri, 15 Jun 2007 21:52:06 GMT Subject: Priority Queue with Mutable Elements In-Reply-To: <1181939158.688317.207790@o61g2000hsh.googlegroups.com> References: <1181939158.688317.207790@o61g2000hsh.googlegroups.com> Message-ID: Chris Lasher wrote: > I am working with large graphs (~150,000 to 500,000 nodes) which I > need decompose node-by-node, in order of a node's value. A node's > value is determined by the sum of its edge weights. When a node is > removed from the graph, its neighbors' values must be updated to take > into account the removed edges. > > I was told to look for a priority queue in Python. I had a look at the > heapq module. It looks like it supports ordering on insertion, but I'm > unsure how to update the queue once a node's value changes. > Additionally, I need the queue to be sorted on a particular attribute > of the node objects, and don't see a way to do that other than > override the __cmp__ method. Should I just use a list and use .sort() > or sorted()? That seems like it could be horribly inefficient. > > I found Andrew Snare's PQueue extension module [1] , which supports > updating values in the priority queue by reassignment. It appeared to > be broken in Python2.5 [2] but I found the offending line (a call to > PyMem_DEL) and changed it (to PyObject_FREE) and it appears to be > working fine. I would prefer to limit external depedencies for my > modules, however. See this implementation of a "pair heap": http://mail.python.org/pipermail/python-dev/2006-November/069845.html ...which offers the ability to update the 'priority' of an entry in the heap. It requires that the 'value' in (priority, value) pairs be unique (to the heap) and hashable. - Josiah From mcPas.De.Spam at mclaveauPas.De.Spam.com Tue Jun 5 18:06:36 2007 From: mcPas.De.Spam at mclaveauPas.De.Spam.com (Michel Claveau) Date: Wed, 06 Jun 2007 00:06:36 +0200 Subject: which "GUI module" you suggest me to use? References: Message-ID: Hi! Only under Win: PLUIE (http://ponx.org/ponx/guie) This GUI is natively HTML. -- @-salutations Michel Claveau From tjreedy at udel.edu Sat Jun 2 01:03:17 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 2 Jun 2007 01:03:17 -0400 Subject: subexpressions References: <1180756858_54747@sp12lax.superfeed.net> Message-ID: "Cousin Stanley" wrote in message news:1180756858_54747 at sp12lax.superfeed.net... | | > .... | > After years of discussion, Guido has decided | > to leave lambda alone for 3.0. | > | > It will not be neither expanded, nor removed, nor renamed. | | But it still will be as ugh, ugh, ugh-lee | as a mule walking backwards ..... ;-) Then pretend it was eliminated, as Guido once thought to do, and do not use it. And look away when others do ;-) tjr From walterbyrd at iname.com Sat Jun 16 23:10:32 2007 From: walterbyrd at iname.com (walterbyrd) Date: Sat, 16 Jun 2007 20:10:32 -0700 Subject: Newbie question: how to get started? In-Reply-To: <2007061622483250073-user@superhoostcom> References: <2007061622483250073-user@superhoostcom> Message-ID: <1182049832.287814.310110@a26g2000pre.googlegroups.com> On Jun 16, 8:48 pm, ed wrote: > Hi, > > I'm interested in starting to learn python. I'm looking for any > reccomendations or advice that I can use to get started. Looking > forward to any help you can give! > > Thanks! > > -e Here are two very well regarded online books - both free: http://www.diveintopython.org/ http://www.ibiblio.org/obp/thinkCSpy/ From cgwalters at gmail.com Sun Jun 3 17:32:54 2007 From: cgwalters at gmail.com (cgwalters at gmail.com) Date: Sun, 03 Jun 2007 21:32:54 -0000 Subject: another thread on Python threading Message-ID: <1180906374.041535.296410@k79g2000hse.googlegroups.com> Hi, I've recently been working on an application[1] which does quite a bit of searching through large data structures and string matching, and I was thinking that it would help to put some of this CPU-intensive work in another thread, but of course this won't work because of Python's GIL. There's a lot of past discussion on this, and I want to bring it up again because with the work on Python 3000, I think it is worth trying to take a look at what can be done to address portions of the problem through language changes. Also, the recent hardware trend towards multicore processors is another reason I think it is worth taking a look at the problem again. = dynamic objects, locking and __slots__ = I remember reading (though I can't find it now) one person's attempt at true multithreaded programming involved adding a mutex to all object access. The obvious question though is - why don't other true multithreaded languages like Java need to lock an object when making changes? The answer is that they don't support adding random attributes to objects; in other words, they default to the equivalent of __slots__. == Why hasn't __slots__ been successful? == I very rarely see Python code use __slots__. I think there are several reasons for this. The first is that a lot of programs don't need to optimize on this level. The second is that it's annoying to use, because it means you have to type your member variables *another* time (in addition to __init__ for example), which feels very un- Pythonic. == Defining object attributes == In my Python code, one restriction I try to follow is to set all the attributes I use for an object in __init__. You could do this as class member variables, but often I want to set them in __init__ anyways from constructor arguments, so "defining" them in __init__ means I only type them once, not twice. One random idea is to for Python 3000, make the equivalent of __slots__ the default, *but* instead gather the set of attributes from all member variables set in __init__. For example, if I write: class Foo(object): def __init__(self, bar=None): self.__baz = 20 if bar: self.__bar = bar else: self.__bar = time.time() f = Foo() f.otherattr = 40 # this would be an error! Can't add random attributes not defined in __init__ I would argue that the current Python default of supporting adding random attributes is almost never what you really want. If you *do* want to set random attributes, you almost certainly want to be using a dictionary or a subclass of one, not an object. What's nice about the current Python is that you don't need to redundantly type things, and we should preserve that while still allowing more efficient implementation strategies. = Limited threading = Now, I realize there are a ton of other things the GIL protects other than object dictionaries; with true threading you would have to touch the importer, the garbage collector, verify all the C extension modules, etc. Obviously non-trivial. What if as an initial push towards real threading, Python had support for "restricted threads". Essentially, restricted threads would be limited to a subset of the standard library that had been verified for thread safety, would not be able to import new modules, etc. Something like this: def datasearcher(list, queue): for item in list: if item.startswith('foo'): queue.put(item) queue.done() vals = ['foo', 'bar'] queue = queue.Queue() threading.start_restricted_thread(datasearcher, vals, queue) def print_item(item): print item queue.set_callback(print_item) Making up some API above I know, but the point here is "datasearcher" could pretty easily run in a true thread and touch very little of the interpreter; only support for atomic reference counting and a concurrent garbage collector would be needed. Thoughts? [1] http://submind.verbum.org/hotwire/wiki From S.Mientki-nospam at mailbox.kun.nl Tue Jun 19 15:16:44 2007 From: S.Mientki-nospam at mailbox.kun.nl (Stef Mientki) Date: Tue, 19 Jun 2007 21:16:44 +0200 Subject: caseless dictionary howto ? Message-ID: <4dc64$46782a84$d443bb3a$4629@news.speedlinq.nl> hello, I need to search a piece of text and make all words that are equal (except their case) also equal in their case, based on the first occurrence. So I'm using a dictionary to store names and attributes of objects. As as I need to search on the caseless name (so I've choosen lowercase), My dictionairy looks like this: self.procs [ "serial_hw_read" ] = ( "Serial_HW_Read", "F", "++", T) Is this really a good solution, or are there better ways ? thanks, Stef Mientki From orsenthil at gmail.com Wed Jun 20 22:51:21 2007 From: orsenthil at gmail.com (Phoe6) Date: Thu, 21 Jun 2007 02:51:21 -0000 Subject: Reading multiline values using ConfigParser In-Reply-To: References: <1182358231.269388.250510@m36g2000hse.googlegroups.com> Message-ID: <1182394281.778904.315430@z28g2000prd.googlegroups.com> On Jun 20, 10:35 pm, "John Krukoff" wrote: > > Is there anyway, I can include multi-line value in the configfile? I > > Following the link to RFC 822 (http://www.faqs.org/rfcs/rfc822.html) > indicates that you can spread values out over multiple lines as long as > there is a space or tab character imeediately after the CRLF. Thanks for the response. It did work! >>> config = ConfigParser() >>> config.read("Testcases.txt") ['Testcases.txt'] >>> output = config.get("Information", "Testcases") >>> print output tct123 tct124 tct125 >>> output '\ntct123\ntct124\ntct125' >>> However, as I am going to provide Testcases.txt to be "user editable", I cannot assume or "ask users" to provide value testcases surronded by spaces. I got to figure out a workaround here. Thanks, Senthil From unews at onlinehome.de Sat Jun 16 05:06:05 2007 From: unews at onlinehome.de (Uwe Grauer) Date: Sat, 16 Jun 2007 11:06:05 +0200 Subject: Looking for a wxPython GUI builder In-Reply-To: <1181964947.369982.320630@c77g2000hse.googlegroups.com> References: <1181964947.369982.320630@c77g2000hse.googlegroups.com> Message-ID: Jens Thiede wrote: > On Jun 16, 3:18 am, Dick Moores wrote: >> How about SPE? >> >> Any others? >> >> And which ones do people >> actually use? Commercial or Freeware. >> >> Thanks, >> >> Dick Moores > > There's Boa Constructor... (http://boa-constructor.sourceforge.net/ > Screenshots). I haven't actually used it though. > You should also take a look at Dabo: http://www.dabodev.com It has a fairly nonrestrictive license. From gagsl-py2 at yahoo.com.ar Wed Jun 13 21:29:55 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 13 Jun 2007 22:29:55 -0300 Subject: Method much slower than function? References: <1181781612.939800.238890@q19g2000prn.googlegroups.com> Message-ID: En Wed, 13 Jun 2007 21:40:12 -0300, escribi?: > Hi all, > > I am running Python 2.5 on Feisty Ubuntu. I came across some code that > is substantially slower when in a method than in a function. > > ################# START SOURCE ############# > # The function > > def readgenome(filehandle): > s = '' > for line in filehandle.xreadlines(): > if '>' in line: > continue > s += line.strip() > return s > > # The method in a class > class bar: > def readgenome(self, filehandle): > self.s = '' > for line in filehandle.xreadlines(): > if '>' in line: > continue > self.s += line.strip() > In the function above, s is a local variable, and accessing local variables is very efficient (using an array of local variables, the compiler assigns statically an index for each one). Using self.s, on the other hand, requires a name lookup for each access. The most obvious change would be to use a local variable s, and assign self.s = s only at the end. This should make both methods almost identical in performance. In addition, += is rather inefficient for strings; the usual idiom is using ''.join(items) And since you have Python 2.5, you can use the file as its own iterator; combining all this: return ''.join(line.strip() for line in filehandle if '>' not in line) -- Gabriel Genellina From horpner at yahoo.com Wed Jun 13 14:51:27 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Wed, 13 Jun 2007 18:51:27 GMT Subject: Python's "only one way to do it" philosophy isn't good? References: <1181368143.874341.273140@r19g2000prf.googlegroups.com> <7xy7irxjom.fsf@ruckus.brouhaha.com> <466f0c2c$0$4157$ba624c82@nntp02.dk.telia.net> <46702229$0$4158$ba624c82@nntp02.dk.telia.net> Message-ID: On 2007-06-13, Neil Cerutti wrote: > On 2007-06-13, Anders J. Munch <2007 at jmunch.dk> wrote: >> General tail-call optimisation is of course completely >> out-of-bounds for Python, because it ruins tracebacks. Unlike >> tail recursion, which could use recursion counters. > > Is it really ruined? To use a similar example: I found some interesting notes by Alex Martelli pertaining to tail-call optimisation, and my assumption that tail-call optimization is easier to implement than tail-recursive optimization may have been naive. ;) http://groups.google.com/group/comp.lang.python/msg/1a7cccc103c1bd70?hl=en& Moreover, there are (or were) technical reasons that you can't do tail-call optimization in Python, which can't even recognize tail-calls at compile time. According to Tim Peters: http://groups.google.com/group/comp.lang.python/msg/ea1de1e35aefb828?hl=en& -- Neil Cerutti From dak at gnu.org Mon Jun 25 19:14:10 2007 From: dak at gnu.org (David Kastrup) Date: Tue, 26 Jun 2007 01:14:10 +0200 Subject: The Modernization of Emacs: terminology buffer and keybinding References: <87tzt3ihev.fsf@kobe.laptop> <1182370216.961241.6960@n60g2000hse.googlegroups.com> <85zm2ufjpb.fsf@lola.goethe.zz> <1182372592.803332.288260@u2g2000hsc.googlegroups.com> <1182373919.262388.100740@c77g2000hse.googlegroups.com> <85r6o6fhkb.fsf@lola.goethe.zz> <1182375045.626510.188170@m36g2000hse.googlegroups.com> <85myyufgwj.fsf@lola.goethe.zz> <1182375528.985142.293900@q69g2000hsb.googlegroups.com> <1182545268.055596.228700@i38g2000prf.googlegroups.com> <1182547318.325617.16370@o11g2000prd.googlegroups.com> <1182657564.912472.55570@g4g2000hsf.googlegroups.com> <1182713541.449966.195970@o61g2000hsh.googlegroups.com> <1182808864.211161.155920@u2g2000hsc.googlegroups.com> Message-ID: <853b0f8w59.fsf@lola.goethe.zz> Twisted writes: > 2. Regarding these graphical derivatives (apparently plural) of > emacs, Emacs is a graphical derivative of Emacs? What nonsense. The canonical Emacs as distributed and copyrighted by the FSF is a GUI application on a large number of platforms. > has nobody considered that this means that Xah had already won > before he'd even fired his shot? :P It just means that you have no clue what Xah has been talking about. Xah was concerned about keybindings and terminology. Never mind that there are menus (with keyboard shortcuts displayed automatically), toolbars, scrollbars, multiple frames, font support, mouse support and so forth and so on. Xah knows this since he actually _uses_ Emacs. > Someone obviously felt the need for a more usable emacs and > delivered one. In that case it's a fait accompli. Criticisms leveled > at original-emacs shouldn't bother users of the graphical versions > regardless. The graphical versions _are_ original Emacs. > The one complaint might be that both of us had out of date > information and were fighting a war our side had already won years > ago. :) You just have no clue what Xah has been talking about. > Unless of course these are all klunky bolted-on GUIs of the sort all > too common when porting unix software to Windows or the Mac or for > use under X, which don't work quite right or are clearly poorly > integrated with the application's internals...about which I > currently have no information. You have had no information about _anything_ right from the start. > And no, I'm not about to spend hours downloading half a gig of > bloated who-knows-what just to find out, tyvm. :) You could start with the current NEWS file at which describes everything which is new in Emacs 22.1 (and will give quite a few ideas about what has already been there in earlier versions). Of course, you'll whine together some excuse why you can't be bothered getting some information about Emacs, never mind that you post several dozens of embarrassing tirades that are completely based on nonsense of your own imagination. -- David Kastrup, Kriemhildstr. 15, 44793 Bochum From lance at augustmail.com Tue Jun 12 18:09:19 2007 From: lance at augustmail.com (Lance Hoffmeyer) Date: Tue, 12 Jun 2007 22:09:19 GMT Subject: excel column autofit Message-ID: Hey all, Wondering why the syntax won't autofit Column A? I am not getting any errors. Also, is there a way of reducing the number of syntax lines? Basically, I am wondering if there is an easier way to copy and paste? Thanks in Advance. Lance # ADD ROW LABELS sh = wb.Worksheets ("Total") sh.Select() sh.Range(sh.Cells(2,1), sh.Cells(20,1)).Select() sh.Range(sh.Cells(2,1), sh.Cells(20,1)).Copy() sh = wb.Worksheets ("Current Total") sh.Select() sh.Range(sh.Cells(2,1),sh.Cells(20,1)).Select() sh.Paste() sh.Columns("A:A").EntireColumn.AutoFit From email at christoph-haas.de Tue Jun 5 15:24:31 2007 From: email at christoph-haas.de (Christoph Haas) Date: Tue, 5 Jun 2007 21:24:31 +0200 Subject: web development without using frameworks In-Reply-To: <20d6f8950706051201mba83194hcbc4d17cd2439cd@mail.gmail.com> References: <20d6f8950706051201mba83194hcbc4d17cd2439cd@mail.gmail.com> Message-ID: <20070605192431.GB3525@workaround.org> On Tue, Jun 05, 2007 at 03:01:01PM -0400, Chris Stewart wrote: > I'm interested in learning web based python without the use of fancy frameworks > that are out there. I'm having a hard time coming up with resources and > examples for this. Does anyone have anything that could be helpful? I'd say the only decent ways are either using a full-featured framework (I favor Pylons) or write plain CGIs. Even for the later a look into http://wiki.python.org/moin/WebFrameworks might be useful (I wouldn't say that "web.py" is really a framework - and it's listed there). Or you write plain-old CGIs with Python's "cgi" module. I have also started like that but currently only use frameworks because the "cgi" module is pretty limited (compared to what Perl offers) and for serious applications not really the way to go. My 2? Christoph From thorsten at thorstenkampe.de Wed Jun 20 11:43:42 2007 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: 20 Jun 2007 15:43:42 GMT Subject: How to hide a program? References: <1182347596.414718.117190@w5g2000hsg.googlegroups.com> <1182352921.305431.72290@k79g2000hse.googlegroups.com> Message-ID: * jvdb (Wed, 20 Jun 2007 08:22:01 -0700) > The thing is, i don't want to see anything of my program, just the > launched program. > I already have the program working. But when i create an executable of > it with py2exe and start it, i don't want to see that it is running, > perhaps just in the systemtray. That is my problem. http://www.ntwind.com/software/utilities/hstart.html From sjmachin at lexicon.net Wed Jun 13 07:58:50 2007 From: sjmachin at lexicon.net (John Machin) Date: Wed, 13 Jun 2007 21:58:50 +1000 Subject: ANN: xlrd 0.6.1 final is now available Message-ID: <466FDBFA.5010001@lexicon.net> The final release of version 0.6.1 of xlrd is now available from http://www.lexicon.net/sjmachin/xlrd.htm and from the Cheeseshop (http://cheeseshop.python.org/pypi/xlrd). What is xlrd? It's a small (download approx 0.1 Mb) pure-Python library for extracting information from Microsoft Excel (tm) files, anywhere Python 2.1 or later will run -- no need for Excel itself, nor COM, nor even Windows. Further info: follow the links on the home page. This major release incorporates the functionality of 0.6.0 which was not released independently for various reasons including the need to push ahead with the 0.6.1 functionality. New in 0.6.0: facility to access named cell ranges and named constants (Excel UI: Insert/Name/Define). New in 0.6.1: extracts formatting information for cells (font, "number format", background, border, alignment and protection) and rows/ columns (height/width etc). To save memory and time for those who don't need it, this information is extracted only if formatting_info=1 is supplied to the open_workbook() function. The cell records BLANK and MULBLANKS which contain no data, only formatting information, will continue to be ignored in the default (no formatting info) case. There have been several changes made to handle anomalous files (written by 3rd party software) which Excel will open without complaint, but failed with xlrd, usually because an assertion fails or xlrd deliberately raises an exception. Refer to HISTORY.html for details. These have been changed to accept the anomaly either silently or with a NOTE message or a WARNING message, as appropriate. Many thanks are due to Simplistix Ltd (http://www.simplistix.co.uk) for funding the new functionality in 0.6.1. Since 0.6.1a4 was released in February, only one bug-fix and some tidying up have been done -- see HISTORY.html for details. Feedback: general discussion on the python-excel newsgroup (sign up at http://groups.google.com/group/python-excel?lnk=li&hl=en) or e-mail to sjmachin at lexicon dot net, preferably with [xlrd] as part of the message subject. Cheers, John From mark.martinez2 at gmail.com Tue Jun 19 20:33:44 2007 From: mark.martinez2 at gmail.com (mark.martinez2 at gmail.com) Date: Wed, 20 Jun 2007 00:33:44 -0000 Subject: Transfer file name input from one .py to another Message-ID: <1182299624.594164.145430@n2g2000hse.googlegroups.com> How do I transfer the file name which is input in one .py (an MDI parent frame in wxPython) to another .py (an MDI child frame)? The parent gets the file name from the user via a file select dialog, but the child frame is the one that needs to know what file it is working with. Thanks From python at jayloden.com Sun Jun 17 21:57:25 2007 From: python at jayloden.com (Jay Loden) Date: Sun, 17 Jun 2007 21:57:25 -0400 Subject: WebThumb In-Reply-To: <87bqfezfgu.fsf@pobox.com> References: <1181901372.058925.322830@w5g2000hsg.googlegroups.com> <87bqfezfgu.fsf@pobox.com> Message-ID: <4675E685.7060609@jayloden.com> John J. Lee wrote: > Johny writes: > >> How can I get a website thumbnail? >> I would like to allow visitors to add their URLs to our pages with >> the thumbnail of their website. >> Can anyone suggest a solution for web thumbnails? >> Thanks >> L. > Don't know if this really helps any but it does sort of reaffirm what John Lee said already: http://www.zubrag.com/articles/create-website-snapshot-thumbnail.php Seems like this is one are that could really use a nice open source library of some kind :-) -Jay From steve at REMOVE.THIS.cybersource.com.au Sun Jun 10 07:37:23 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sun, 10 Jun 2007 21:37:23 +1000 Subject: matching objects by a tuple field criterion References: <1181473124.790391.293120@r19g2000prf.googlegroups.com> Message-ID: On Sun, 10 Jun 2007 03:58:44 -0700, bullockbefriending bard wrote: > i have a large collection of python objects, each of which contains an > integer 6-tuple as part of its data payload. what i need to be able to > do is select only those objects which meet a simple tuple element > wildcard matching criterion. e.g. given the following python objects: > > object A includes tuple (1,2,3,4,5,6) > object B includes tuple (1,4,4,4,11,1) > object C includes tuple (1,3,9,1,1,1) > > all tuples are unique. for what it's worth, the values in each field > are independent of the other fields and range from 1 to 14. although > 'large', my collection is sparse cf. the 14^6 possible tuples. > > i want to search on *one only* tuple field/value. if my search > criterion is (*,*,*,4,*,*), then i want to find object A and object B. > if (1,*,*,*,*,*), i want to find objects A, B, and C, etc. i will only > ever specify an integer match for one tuple field. > > i can think of some naive approaches, but is there an elegant way to > do this? Instead of passing a wild-card tuple like (*,*,*,4,*,*) simply pass the integer you want to match and the position you want to match it in. As a generator: def matcher(list_of_objects, what, where): for obj in list_of_objects: if obj.data[where] == what: yield obj As a generator expression: (obj for obj in list_of_objects if obj.data[what] == where) -- Steven. From J.Fine at open.ac.uk Wed Jun 20 09:27:54 2007 From: J.Fine at open.ac.uk (Jonathan Fine) Date: Wed, 20 Jun 2007 14:27:54 +0100 Subject: Packing a simple dictionary into a string - extending struct? References: Message-ID: "Sridhar Ratna" wrote in message > What about JSON? You can serialize your dictionary, for example, in > JSON format and then unserialize it in any language that has a JSON > parser (unless it is Javascript). Thank you for this suggestion. The growing adoption of JSON in Ajax programming is a strong argument for my using it in my application, although I think I'd prefer something a little more binary. So it looks like I'll be using JSON. Thanks. Jonathan From keramida at ceid.upatras.gr Fri Jun 22 11:25:57 2007 From: keramida at ceid.upatras.gr (Giorgos Keramidas) Date: Fri, 22 Jun 2007 18:25:57 +0300 Subject: The Modernization of Emacs: terminology buffer and keybinding References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182272495.990807.99110@a26g2000pre.googlegroups.com> <87tzt3ihev.fsf@kobe.laptop> <1182370216.961241.6960@n60g2000hse.googlegroups.com> Message-ID: <87tzt01056.fsf@kobe.laptop> On 21 Jun 2007 16:52:17 +0200, Bjorn Borud wrote: > on my tombstone will say > "here lies the last Emacs user on earth. M-x rip". Hahaha! Very good one :-) From doug at alum.mit.edu Tue Jun 26 01:12:41 2007 From: doug at alum.mit.edu (Douglas Alan) Date: Tue, 26 Jun 2007 01:12:41 -0400 Subject: Python's "only one way to do it" philosophy isn't good? References: <7x3b0nmkk6.fsf@ruckus.brouhaha.com> <1182750077.570603.160240@q69g2000hsb.googlegroups.com> <7xir9cbm0g.fsf@ruckus.brouhaha.com> <7xejjzmk7u.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin writes: > Douglas Alan writes: >> I will certainly admit that Lisp programmers at the time were (and >> likely still are) much more enamored of mapping functions than of >> iterators. Mapping functions certainly get the job done as elegantly >> as iterators most of the time, although I would agree that they are >> not quite so general. > In the Maclisp era functions like mapcar worked on lists, and > generated equally long lists in memory. I'm aware, but there were various different mapping functions. "map", as opposed to "mapcar" didn't return any values at all, and so you had to rely on side effects with it. > It was sort of before my time but I have the impression that Maclisp > was completely dynamically scoped and as such, Yes, that's right. > it couldn't cleanly make anything like generators (since it had no > way to make lexical closures). That's right, generators would have been quite difficult to do in MacLisp. But a Lisp Machine (with stack groups) could have done them, and did, with or without closures. >> Scheme, on, the other hand, at least by idiom, has computation >> "streams", and streams are equivalent to iterators. > No not really, they (in SICP) are at best more like class instances > with a method that mutates some state. There's nothing like a yield > statement in the idiom. Right -- I wrote "iterators", not "generators". > You could do it with call/cc but SICP just uses ordinary closures to > implement streams. Yes, that's right. >> The canonical way to do this in Lisp would be something like: >> (mapcar (lambda (x) (blah x)) xs) > At least you could spare our eyesight by writing that as > (mapcar #'blah xs) ;-). Good point! But I just love lambda -- even when I'm just using it as a NOP.... (Also I couldn't remember the syntax for accessing the function property of a symbol in MacLisp.) > The point is that mapcar (as the name implies) advances down a list > using cdr, i.e. it only operates on lists, not general iterators or > streams or whatever. Right, but each sequence type had it's own corresponding mapping fuctions. >> > x = xs[key] >> I'm not sure what you are asserting? That Common Lisp doesn't have >> hash tables? That's certainly not the case. Or that it doesn't >> provide standard generic functions for accessing them > The latter. Of course there are getf/setf, but those are necessarily > macros. Right. OO on primitive data types is kind of hard in a non OO language. So, when writing an application in MacLisp, or Lisp Machine lisp, I might have had to spend a bit of time writing an application framework that provided the OO features I needed. This was not particularly hard to do in Lisp, but surely not nearly as nice as if they had standardized such things. This would not be particularly difficult to do, other than the getting everyone to agree on just what the interfaces should be. But Lisp programmers, are of course, just as recalcitrant as Python programmers. >> A language like Python, which is defined by its implementation, >> rather than by a standard, can move much more quickly. This debate >> though is really one more of what is the best model for language >> definition, rather than one on what the ideal language is like. > Python is not Perl and it has in principle always been defined by its > reference manual, And in Python's case, the reference manual is just an incomplete description of the features offered by the implementation, and people revel in features that are not yet in the reference manual. > though until fairly recently it's fostered a style of relying on > various ugly CPython artifacts like the reference counting GC. That's not ugly. The fact that CPython has a reference-counting GC makes the lifetime of object predictable, which means that like in C++, and unlike in Java, you can use destructors to good effect. This is one of the huge boons of C++. The predictability of lifespan makes the language more expressive and powerful. The move to deprecate relying on this feature in Python is a bad thing, if you ask me, and removes one of the advantages that Python had over Lisp. > Lisp accumulated a lot of cruft over the decades and it kept some > baggage that it really could have done without. Indeed -- true of most languages. Of course, there have been quite a few Lisp dialects that have been cleaned up in quite a few ways (e.g., Dylan), but they, of course, have a hard time achieving any significant traction. > I don't think Python's designers learned nearly as much from Lisp as > they could have, and Python has suffered because of it. Amen. > Lisp still has an awesome beauty in both the CL and Scheme > incarnations. Indeed. > But it's like listening to Elvis music--even if it can still get you > dancing, at the end of the day it's still a reflection of a bygone > culture. Lisp is more like The Beatles. And it's not bygone -- it's just nichified. Lisp is forever -- you'll see. |>oug From cam.ac.uk at mh391.invalid Sun Jun 3 20:32:37 2007 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Mon, 04 Jun 2007 01:32:37 +0100 Subject: *Naming Conventions* In-Reply-To: References: Message-ID: Michael Hoffman wrote: > Thorsten Kampe wrote: > >> for validanswer in validanswers: >> if myAnswers.myanswer in myAnswers.validAnswers[validanswer]: >> MyOptions['style'] = validanswer > > I usually try to avoid using "my" because I find it obscures a better > understanding of what is really going ...on. Whoops, sorry about missing the last word of that message. -- Michael Hoffman From timr at probo.com Sun Jun 3 00:43:18 2007 From: timr at probo.com (Tim Roberts) Date: Sun, 03 Jun 2007 04:43:18 GMT Subject: Need help! win32 com_error 'Exception occurred' References: Message-ID: "Richard Gordon" wrote: > >I've got a fatal bug using Parente's pyTTS with Python 2.3 on Windoze 32 >using MS SAPI 5.1 and Hammond's win32 module. The test program is > import pyTTS > tts = pyTTS.Create() > tts.Speak('Hello world.') >... > com_error: (-2147352567, 'Exception occurred.', (0, None, None, None, >0, -2147201015), None) > >>> > >The system does not have a sound card --- could that be an issue? Of course. -2147201015 is 0x80045009, which is SPERR_NO_DRIVER. Seriously, what on earth did you expect this to do? Its whole purpose is send sounds to the sound driver. If there is no sound driver, what was it supposed to do with the audio data? -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From sjmachin at lexicon.net Fri Jun 8 17:53:37 2007 From: sjmachin at lexicon.net (John Machin) Date: Fri, 08 Jun 2007 14:53:37 -0700 Subject: converting an int to a string In-Reply-To: References: Message-ID: <1181339617.166104.259300@i38g2000prf.googlegroups.com> On Jun 9, 1:40 am, Sean Farrow wrote: > Hi: > I have the folling code: > def parseTime(self, time): > minutes =int(float(time)/60) > seconds =int(float(time)-minutes*60) > minutes =str(minutes) > seconds =str(minutes) seconds = str(minutes) ??? Is that the actual code that you executed? What does "don't seem to be working" mean? The seconds output is always the same as the minutes output? Try again, with seconds = str(seconds) followed by print "debugging", repr(time), repr(minutes), repr(seconds) If it still seems not to be working, come back with a copy/paste of the actual code that you executed, plus a copy/paste of the output > the statements that convert the minutes and seconds variables > str(minutes) and str(seconds) don't seem to be working. > Any idea why? > is there any other way of doing this and perhaps using the $d > interpolation operator? What is the $d interpolation operator? Do you mean the %d string formatting operator? If so, the answer depends on what you want to do with the output ... e.g. "%d:%02d" % (int_minutes, int_seconds) might be what you want. From cam.ac.uk at mh391.invalid Fri Jun 22 10:31:57 2007 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Fri, 22 Jun 2007 15:31:57 +0100 Subject: What was that web interaction library called again? In-Reply-To: <1182521949.813529.75140@w5g2000hsg.googlegroups.com> References: <1182521949.813529.75140@w5g2000hsg.googlegroups.com> Message-ID: Harald Korneliussen wrote: > Hi, > > I remember I came across a python library that made it radically > simple to interact with web sites, connecting to gmail and logging in > with four or five lines, for example. I thought, "that's interesting, > I must look into it sometime". Now there's this child I know who asked > me about programming, especially programs that could do things like > this, how difficult it was, and so on. I mentioned how I though Python > was a good intro to programming, and there was a library which was > perfect for what he wanted. > > Only now I've forgotten the name of the library! And try as I might, I > can't find it with google. I know there are modules for it in the > standard libraries, but this thing was brilliantly simple in > comparison. It might have been some sort of research project, I can't > remember... but perhaps someone here can remind me what it was? If so, > there may be yet another young python programmer in training :-) BeautifulSoup? -- Michael Hoffman From martin at see.sig.for.address Sat Jun 23 10:36:31 2007 From: martin at see.sig.for.address (Martin Gregorie) Date: Sat, 23 Jun 2007 15:36:31 +0100 Subject: The Modernization of Emacs: terminology buffer and keybinding In-Reply-To: <1182547318.325617.16370@o11g2000prd.googlegroups.com> References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182272495.990807.99110@a26g2000pre.googlegroups.com> <87tzt3ihev.fsf@kobe.laptop> <1182370216.961241.6960@n60g2000hse.googlegroups.com> <85zm2ufjpb.fsf@lola.goethe.zz> <1182372592.803332.288260@u2g2000hsc.googlegroups.com> <1182373919.262388.100740@c77g2000hse.googlegroups.com> <85r6o6fhkb.fsf@lola.goethe.zz> <1182375045.626510.188170@m36g2000hse.googlegroups.com> <85myyufgwj.fsf@lola.goethe.zz> <1182375528.985142.293900@q69g2000hsb.googlegroups.com> <1182545268.055596.228700@i38g2000prf.googlegroups.com> <1182547318.325617.16370@o11g2000prd.googlegroups.com> Message-ID: BartlebyScrivener wrote: > On Jun 22, 3:47 pm, Twisted wrote: > >> If it requires years of mastery, it is clunky > > Well, now you keep harping on this, but it's just not true. > > I use vim myself, but for purposes of this argument it doesn't matter. > If you take the Vim tutorial and use the help (which appears in a > split window anytime you want it), you can use Vim like any other text > editor within a day or so, especially if you use Cream, which is set > up to hold your Windows hands and act like any other Windows text > editor on the surface. But if you use Vim for YEARS you get better and > faster and more efficient precisely BECAUSE of its arcane > capabilities. If you are going to keep your hands on the keyboard > where they belong, if you REALLY want to go fast, then there's no > alternative to having complex key commands, which become second nature > over time, and take the place of repetitive, totally inefficient > mousing around. > > You might enjoy this. Especially the link to an old essay called > "Interface Zen" > > http://tinyurl.com/2da3om > A good reference. Thanks. I like Interface Zen - much sense there. However, there's a case he missed, probably through never using a CAD system. All the good ones can be driven either by mouse, or by non-chorded key sequences or any combo the user likes. The essence of CAD is very accurate pointing but all too many mice move slightly when clicked. Fortunately a decent CAD system offers the possibility of purely pointing with the mouse and doing everything else with the other hand on the keyboard. The result is both fast and extremely accurate. An interface design point that nobody has yet mentioned here is that there are four different types of user that map onto a grid: casual dedicated untrained 1 2 expert 3 4 I first ran across grid this in "Design of Man-Computer Dialogs" by James Martin and its been very useful in systems interface design. The problem with almost all current GUIs is that they are aimed at types 1 and 3 users - this certainly applies to Windows, OS X and Gnome desktops with the emphasis on type 1. vi and microEmacs, OTOH, are aimed at type 3 and 4 users. Where does emacs fit on this grid? My guess would be 3 and 4. Its very difficult indeed to design an interface that suits both untrained and expert users. About the closest I've seen have been keyboard driven menu structures which have been designed so the user can build their own "command sequences" that traverse menu levels without showing the menus, as long as items are selected correctly from each level. Many CAD systems approximate to this but I've yet to see a graphical desktop, IDE, or editor menu structure that came close. -- martin@ | Martin Gregorie gregorie. | Essex, UK org | From anton.vredegoor at gmail.com Wed Jun 20 18:49:40 2007 From: anton.vredegoor at gmail.com (Anton Vredegoor) Date: Thu, 21 Jun 2007 00:49:40 +0200 Subject: Permutation over a list with selected elements In-Reply-To: <1182238025.739189.208970@a26g2000pre.googlegroups.com> References: <1182238025.739189.208970@a26g2000pre.googlegroups.com> Message-ID: weidongtom at gmail.com wrote: > Given a list of elements that are either a character or a character > follows by a number, e.g. > > ['a', 'b', 'c1', 'd', 'e1', 'f', 'c2', 'x', 'e2'] > > find all the permutations that are given by switching the positions of > the elements that: > (1) begins with the same letter, and > (2) follows by a number. > > With the above list, some possible permutations are: > > ['a', 'b', 'c2', 'd', 'e1', 'f', 'c1', 'x', 'e2'] > ['a', 'b', 'c1', 'd', 'e2', 'f', 'c2', 'x', 'e1'] > ['a', 'b', 'c2', 'd', 'e2', 'f', 'c1', 'x', 'e1'] Another idea, untested. Also I am not sure whether sequences types are supposed to be returning functions ... A. from operator import mul from collections import defaultdict class Swapper: """ Given a set of indices this class returns functions which will swap elements in a list *in place*. Each function corresponds to a permutation of the set of indices. """ def __init__(self,L): self.L = L self.n = reduce(mul,range(2,len(L)+1),1) #faculty def __getitem__(self,i): L = self.L if not -11: set_by_letter[elem[0]].append(i) return set_by_letter.values() def test(): L = ['a', 'b', 'c1', 'd', 'e1', 'f', 'c2', 'x', 'e2'] I = find_sets_of_indices_to_permute(L) #Alex Martelli's function M = map(Swapper,I) for F in cross(M): # conserve the original list because #the functions modify a list in place R = list(L) # apply each permutation function one by one, # each is acting on a different set of indices for fn in F: fn(R) print R if __name__=='__main__': test() From willmaier at ml1.net Wed Jun 27 13:07:55 2007 From: willmaier at ml1.net (Will Maier) Date: Wed, 27 Jun 2007 12:07:55 -0500 Subject: Reversing a string In-Reply-To: References: Message-ID: <20070627170755.GG30401@lass.lfod.us> On Wed, Jun 27, 2007 at 12:53:36PM -0400, Scott wrote: > So how on earth would be the best way to: Write a function that > takes a string as an argument and outputs the letters backward, > one per line. >>> def rev(forward): ... backward = list(forward) ... backward.reverse() ... return ''.join(backward) >>> rev("spam") 'maps' list.reverse() changes the list in-place. Instead of iterating over the items in the string sequence, you can just convert the input string outright. -- [Will Maier]-----------------[willmaier at ml1.net|http://www.lfod.us/] From john106henry at hotmail.com Fri Jun 22 15:15:59 2007 From: john106henry at hotmail.com (John Henry) Date: Fri, 22 Jun 2007 12:15:59 -0700 Subject: Adding method to a class on the fly In-Reply-To: <1182538969.522044.209560@q19g2000prn.googlegroups.com> References: <1182538969.522044.209560@q19g2000prn.googlegroups.com> Message-ID: <1182539759.302793.48230@j4g2000prf.googlegroups.com> Found a message on the web that says I need to use setattr to add the method to the class at run time. But how do I do that? Regards, On Jun 22, 12:02 pm, John Henry wrote: > Hi list, > > I have a need to create class methods on the fly. For example, if I > do: > > class Dummy: > def __init__(self): > exec '''def method_dynamic(self):\n\treturn > self.method_static("it's me")''' > return > > def method_static(self, text): > print text > return > > I like that to be the same as: > > class Dummy: > def __init__(self): > return > > def method_dynamic(self): > return self.method_static("it's me") > > def method_static(self, text): > print text > return > > so that I can do: > > dum=Dummy.method_dynamic() > > and see "it's me" printed. > > Can that be done? > > Thanks, From gagsl-py2 at yahoo.com.ar Wed Jun 13 13:41:25 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 13 Jun 2007 14:41:25 -0300 Subject: Focus to be removed References: <1181729598.372063.321500@i13g2000prf.googlegroups.com> Message-ID: En Wed, 13 Jun 2007 07:13:18 -0300, escribi?: > I'm very pleased to have your help about to solve a technical issue > related to HTML Editlet Editor. In this I' m facing the problem that You should ask the author - I don't think this product has anything to do with Python. -- Gabriel Genellina From rw at smsnet.pl Wed Jun 20 03:07:39 2007 From: rw at smsnet.pl (Rob Wolfe) Date: Wed, 20 Jun 2007 00:07:39 -0700 Subject: HTMLParser.HTMLParseError: EOF in middle of construct In-Reply-To: <46787e4d$0$28429$a729d347@news.telepac.pt> References: <1182195498.16548.5.camel@localhost.localdomain> <4677e790$0$2840$a729d347@news.telepac.pt> <46783ab1$0$1266$a729d347@news.telepac.pt> <46784A62.1000303@web.de> <46787e4d$0$28429$a729d347@news.telepac.pt> Message-ID: <1182323259.005478.251120@w5g2000hsg.googlegroups.com> S?rgio Monteiro Basto wrote: > Stefan Behnel wrote: > > > S?rgio Monteiro Basto wrote: > >> but is one single error that blocks this. > >> Finally I found it , it is : > >> >> if I put : > >> >> > >> p = re.compile('"align') > >> content = p.sub('" align', content) > >> > >> I can parse the html > >> I don't know if it a bug of HTMLParser > > > > Sure, and next time your key doesn't open your neighbours house, please > > report to the building company to have them fix the door. > > > > The question, here, is if > is valid HTML or not ? > I think is valid , if so it's a bug on HTMLParser According to the HTML 4.01 specification this is *not valid* HTML. """ Elements may have associated properties, called attributes, which may have values (by default, or set by authors or scripts). Attribute/value pairs appear before the final ">" of an element's start tag. Any number of (legal) attribute value pairs, separated by spaces, may appear in an element's start tag. """ > if not, we still have a very bad message error (EOF in middle of > construct !?) HTMLParser can deal with some errors e.g. lack of ending tags, but it can't handle many other problems. > I have to use HTMLParser because I want use only python 2.4 standard , I > have to install the scripts in many machines. > And I have to parse many different sites, I just want extract the links, so > with a clean up before parse solve very quickly my problem. In Python 2.4 you have to use some third party module. There is no other option for _invalid_ HTML. IMHO BeautifulSoup is the best among them. -- HTH, Rob From tjreedy at udel.edu Mon Jun 4 23:51:17 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 4 Jun 2007 23:51:17 -0400 Subject: Python 2.5.1 broken os.stat module References: <466140A6.1090100@v.loewis.de><-aOdnbFdroD_gP_bnZ2dnUVZ_uKknZ2d@comcast.com><4662750b$0$29898$9b622d9e@news.freenet.de><4662F98C.8070709@v.loewis.de><466472C8.9020003@v.loewis.de> Message-ID: "Joe Salmeri" wrote in message news:D_WdnYzFdue9O_nbnZ2dnUVZ_uKknZ2d at comcast.com... |I have tried (unsuccessfully) to get you to view things from the end user | perspective. But that perspective is not directly relevant to *your* topic line. When you make a claim that os.stat is 'broken' and bugged, you are making a claim about the *programmer* experience -- in particular, experiencing a discrepancy between performance and reasonable expectation based on the manuals. Martin and I are both concerned about that particular claim (which now appears to be resolved in the negative). >From the developer point of view, you, the programmer, are the user. What you present to your users (who may or may not be the 'end' users) is your responsibility. | However, there is a problem. Windows does *not* display the date like that. Python developers cannot fix that. Besides which, Python is a cross-platform language, originally developed on *nix. | The user is left scratching their head. | | I prefer not to leave my end users in that situation. Then do not. I am sure Martin also agrees. But if you want to discuss writing applications for end users, perhaps you should start a new thread with a different subject line. It would attract different respondents. Terry Jan Reedy From steve at holdenweb.com Fri Jun 1 07:09:05 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 01 Jun 2007 07:09:05 -0400 Subject: subexpressions In-Reply-To: References: Message-ID: Sergey Dorofeev wrote: > "Peter Otten" <__peter__ at web.de> wrote in message > news:f3ok60$vp7$03$1 at news.t-online.com... >> Sergey Dorofeev wrote: >> >>> Please help, is there way to use sub-expressions in lambda? >>> For example, if I want to calculate sin(x^2)+cos(x^2) I must code: >>> lambda x: sin(x*x)+cos(x*x) >>> How to make x*x to be evaluated once? >>>>> (lambda x: [sin(x2) + cos(x2) for x2 in [x*x]][0])(.5) == sin(.5*.5) + >> cos(.5*.5) >> True >> >> The real answer is of course: Use a function. > > But what about something like > > lambda x: sin(y)+cos(y) where y=x*x > > ? > May be this could be a PEP? If there is no straight way to do this. > > Or maybe it could be made a part of some other language. When straightforward mechanisms (in rhis case, function definitins) exist to avoid repeated computations it's very unlikely that such mangled constructions will be made a part of Python. If it *were* considered, you should at least change the "where" to "for", and extend it to unpacking assignment to allow lambda x, y: (sin(xx+yy) + cos(xx+yy) for xx, yy = x*x, y*y regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden ------------------ Asciimercial --------------------- Get on the web: Blog, lens and tag your way to fame!! holdenweb.blogspot.com squidoo.com/pythonology tagged items: del.icio.us/steve.holden/python All these services currently offer free registration! -------------- Thank You for Reading ---------------- From exarkun at divmod.com Thu Jun 21 10:24:56 2007 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Thu, 21 Jun 2007 10:24:56 -0400 Subject: Conceptualizing Threading In-Reply-To: <1182433877.742774.321760@p77g2000hsh.googlegroups.com> Message-ID: <20070621142456.4947.1344609457.divmod.quotient.3242@ohm> On Thu, 21 Jun 2007 06:51:17 -0700, JonathanB wrote: >I have a multi-access problem that I'm pretty sure needs to be solved >with threading, but I'm not sure how to do it. This will be my first >foray into threading, so I'm a little confused by all of the new >landscape. So, I'm going to lay out the problem I'm facing and if >someone could point me towards a good example of what I need to do, >that would be great. I read THE tutorial, and while it made since to >me in an esoteric sense, I'm not sure how to implement it. You described how threads introduce a problem in your program -- that of generating a sequence of sequential identifiers -- but you didn't describe the problem that threads are solving in your program. Maybe you don't need them at all? What led you to threading in the first place? Jean-Paul From Leo.Kislov at gmail.com Wed Jun 27 06:10:00 2007 From: Leo.Kislov at gmail.com (Leo Kislov) Date: Wed, 27 Jun 2007 03:10:00 -0700 Subject: String formatting for complex writing systems In-Reply-To: <1182928852.730131.323210@a26g2000pre.googlegroups.com> References: <1182928852.730131.323210@a26g2000pre.googlegroups.com> Message-ID: <1182939000.080429.136180@x35g2000prf.googlegroups.com> On Jun 27, 12:20?am, Andy wrote: > Hi guys, > > I'm writing a piece of software for some Thai friend. ?At the end it > is supposed to print on paper some report with tables of text and > numbers. ?When I test it in English, the columns are aligned nicely, > but when he tests it with Thai data, the columns are all crooked. > > The problem here is that in the Thai writing system some times two or > more characters together might take one single space, for example ?? > (u"\u0E07\u0E34"). ?This is why when I use something like u"%10s" > % ..., it just doesn't work as expected. > > Is anybody aware of an alternative string format function that can > deal with this kind of writing properly? In general case it's impossible to write such a function for many unicode characters without feedback from rendering library. Assuming you use *fixed* font for English and Thai the following function will return how many columns your text will use: from unicodedata import category def columns(self, s): return sum(1 for c in s if category(c) != 'Mn') -- Leo From gerrit.holl at gmail.com Tue Jun 19 17:18:51 2007 From: gerrit.holl at gmail.com (gerrit.holl at gmail.com) Date: Tue, 19 Jun 2007 21:18:51 -0000 Subject: How can I know the name of "caller" In-Reply-To: References: <1182285024.048003.310120@n2g2000hse.googlegroups.com> Message-ID: <1182287931.673370.245250@n15g2000prd.googlegroups.com> On Jun 19, 10:50 pm, Stefan Sonnenberg-Carstens wrote: > billiejoex schrieb: > > ...(if it is possible) how can I get, from method "called", the name > > of function/method that called it (in this case "caller")? > inspect.stack is your friend ;-) If you start doing such things on a regular basis, it will sooner or later become your enemy. Gerrit. From tjreedy at udel.edu Thu Jun 7 14:02:38 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 7 Jun 2007 14:02:38 -0400 Subject: lists - append - unique and sorted References: <1181143597.563633.241640@o5g2000hsb.googlegroups.com> <1181181710.879767.234090@m36g2000hse.googlegroups.com> Message-ID: "Dan Bishop" wrote in message news:1181181710.879767.234090 at m36g2000hse.googlegroups.com... | If you don't need the list to be sorted until you're done building it, | you can just use: | | lst = sorted(set(lst)) ?? looks same as lst.sort() From bj_666 at gmx.net Wed Jun 20 08:06:26 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Wed, 20 Jun 2007 14:06:26 +0200 Subject: Packing a simple dictionary into a string - extending struct? References: Message-ID: In , Jonathan Fine wrote: > I want to serialise a dictionary, whose keys and values are ordinary strings > (i.e. a sequence of bytes). Maybe you can use ConfigObj_ or JSON_ to store that data. Another format mentioned in the binary XML article you've linked in your post is `ASN.1`_. And there's a secure alternative to `pickle` called cerealizer_. .. _`ASN.1`: http://pyasn1.sourceforge.net/ .. _cerealizer: http://home.gna.org/oomadness/en/cerealizer/ .. _ConfigObj: http://www.voidspace.org.uk/python/configobj.html .. _JSON: http://www.json.org/ Ciao, Marc 'BlackJack' Rintsch From samuraiblog at gmail.com Fri Jun 15 11:09:00 2007 From: samuraiblog at gmail.com (samuraisam) Date: Fri, 15 Jun 2007 15:09:00 -0000 Subject: FTP Date Format Function In-Reply-To: <1181886827.068089.274960@q69g2000hsb.googlegroups.com> References: <1181841917.650027.307670@d30g2000prg.googlegroups.com> <1181886827.068089.274960@q69g2000hsb.googlegroups.com> Message-ID: <1181920140.623666.52890@i38g2000prf.googlegroups.com> On Jun 14, 10:53 pm, billiejoex wrote: > On 14 Giu, 19:25, samuraisam wrote: > > > > > FTP LST/LIST/NLST date field formatting function for all those seekers > > out there... > > > import time > > import datetime > > > def ftpdateformat(value): > > """Formats dates from most FTP servers""" > > if ":" in value: # within 6 months > > return datetime.datetime( > > *time.strptime( # have to guess this calculation > > "%s %s" % (value, datetime.datetime.now().year), > > "%b %d %H:%M %Y" > > )[0:5] > > ).strftime("%B %d, %Y %H:%M") > > else: # before six months > > return datetime.datetime( > > *time.strptime(value, "%b %d %Y")[0:5] > > ).strftime("%B %d, %Y") > > > I'm not sure if there is a proper algorithm for deciding on a proper > > year within the last 6 months as it isn't given by most FTP servers. > > I'd love to amend the function with the correct solution. :) > > I didn't well understand your question, anyway... > > - FTP got no LST command. What's that? > - NLST should return filenames only: returned output doesn't contain > file sizes, last modification time values or whatever. > - RFC959 gives no specifications about *how* LIST command output > should be formatted. Depending on the type of server you're talking to > you could find unix/"ls -l"-like format outputs, DOS-like ones or > something completely different and your code does not cover all of > them. Take a look at:http://effbot.org/downloads/#ftpparse Ah, well if there isn't LST and if NLST doesn't return dates that's OK, I wasn't sure at the time I authored the post. :) From harald.luessen at gmx.de Tue Jun 26 13:35:41 2007 From: harald.luessen at gmx.de (Harald Luessen) Date: Tue, 26 Jun 2007 19:35:41 +0200 Subject: Internals and complexity of types, containers and algorithms References: Message-ID: <8ti28393r7131javs36v2v5dn9ipr2j03u@4ax.com> On Mon, 25 Jun 2007 James Stroud wrote: >Harald Luessen wrote: >> Hi, I am new to python and I miss some understanding of the internals >> of some types and containers. With my C/C++ background I hope to get >> some hints to chose the best data structure for my programs. Here are >> some questions: > >This depends on how you define "best". If you want speed and >optimization, you can use the numpy package built with ATLAS tuned for a >specific machine. Are there arrays in numpy that can efficiently be used for other things than matrix arithmetic? Are they faster than lists but still easy to use? no_piece = 0 wpawn = 1 ... board[square] = no_piece board[square+8] = pawn ... could be a typical pawn move. >Beyond speed, "best" in the python community usually means "most suited" >from an idiomatic perspective and from the perspective of structure that >lends itself to long term maintainability because [C]python data >structures seem to undergo optimizations in their implementation at each >revision. I like the python way of "best" code. But in this particular question the emphasis was on performance and speed. >Your best bet is probably to forget about implementation and write code >that makes sense. For example, some have suggested a tuple-keyed >dictionary to represent a chess board: > >board = ((c,r) for r in xrange(1, 9) for c in 'abcdefgh') >starting = 'RNBQKBNR' + 'P' * 8 + ' ' * 32 + 'p' * 8 + 'rnbqkbnr' >position = dict(zip(board, starting)) I am not new to board game programming and I am used to an array approach or even bitboards. Therefore the dictionary looks a little bit strange to me. Harald From exarkun at divmod.com Sat Jun 23 21:28:06 2007 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Sat, 23 Jun 2007 21:28:06 -0400 Subject: Do eval() and exec not accept a function definition? (like 'def foo: pass) ? In-Reply-To: Message-ID: <20070624012806.4947.1193349050.divmod.quotient.3812@ohm> On Sun, 24 Jun 2007 11:17:40 +1000, Steven D'Aprano wrote: >On Sat, 23 Jun 2007 19:58:32 +0000, vasudevram wrote: > >> >> Hi group, >> >> Question: Do eval() and exec not accept a function definition? (like >> 'def foo: pass) ? > >eval() is a function, and it only evaluates EXPRESSIONS, not code blocks. Actually, that's not exactly true: >>> x = compile('def foo():\n\tprint "hi"\n', '', 'exec') >>> l = {} >>> eval(x, l) >>> l['foo']() hi >>> Jean-Paul From xavier_berard at hotmail.com Fri Jun 8 10:06:27 2007 From: xavier_berard at hotmail.com (=?iso-8859-1?q?Xavier_B=E9rard?=) Date: Fri, 08 Jun 2007 07:06:27 -0700 Subject: Tkinter custom drawing In-Reply-To: <18ffa$4668282d$4275d90a$7087@FUSE.NET> References: <1181224696.484887.29980@q66g2000hsg.googlegroups.com> <18ffa$4668282d$4275d90a$7087@FUSE.NET> Message-ID: <1181311587.317955.28650@q69g2000hsb.googlegroups.com> > > > Now, the problem, is that I have already plenty of widgets on my > > screen. I just want to draw over them, which is a bit difficult in my > > comprehension of things. > > What are you trying to achieve by "drawing over" widgets? Want I want to do is a sort of GUI builder for Tkinter. I already finished a rough version, but for now I'm making a lighter version of this project. So, my intent, is to create a widget under the widget. While dragging the mouse, I want to see this rectangle that defines the boundaries of the new widget I'm creating. Sorry for being unclear. From vinay_sajip at yahoo.co.uk Fri Jun 1 09:46:51 2007 From: vinay_sajip at yahoo.co.uk (Vinay Sajip) Date: Fri, 01 Jun 2007 06:46:51 -0700 Subject: logging module: log file with datetime In-Reply-To: <1180699233.916275.279330@u30g2000hsc.googlegroups.com> References: <1180699233.916275.279330@u30g2000hsc.googlegroups.com> Message-ID: <1180705611.348062.99440@o5g2000hsb.googlegroups.com> On 1 Jun, 13:00, ?lvaro Nieto wrote: > How could I define a log file with datetime in his name?. Now the > name > for log file is './Logs/cdmto.log' and I'd like it would be './ > Logs/cdmto_20070601.log', > for example. > You can't do this just in the configuration - TimedRotatingFileHandler automatically works out the filename in a predetermined manner when doing rollover (dependent on whether it's doing rollovers daily, hourly or whatever period). If you need more specific handling, you'll need to write a subclass of TimedRotatingFileHandler which does what you need. Regards, Vinay Sajip From newsgroups at debain.org Wed Jun 6 10:56:56 2007 From: newsgroups at debain.org (Samuel) Date: Wed, 6 Jun 2007 14:56:56 +0000 (UTC) Subject: which "GUI module" you suggest me to use? References: <136bvigp2ps99bc@corp.supernews.com> <136di0nsamvcgd0@corp.supernews.com> Message-ID: On Wed, 06 Jun 2007 14:43:35 +0000, Grant Edwards wrote: > On 2007-06-06, Samuel wrote: >> On Wed, 06 Jun 2007 00:22:40 +0000, Grant Edwards wrote: >>> wxPython works fine under Windows, Linux and OSX. >> >> wxPython emulates Gtk > > What? On some platforms (Linux), wxPython _uses_ Gtk. I don't see how > you could say it emulates it. That may be true in some cases, but in fact, most widgets show some sort of difference. Take for example the HPaned - it looks totally different (the slider is a lot slimmer, plus moving it makes a line appear. The behavior is different as well). Even simple widgets show differences. Try triple-clicking into entry boxes, it's different from Gtk. >> (though using some native widgets, it also uses some of its own) and in >> many cases it looks non-native compared to Gtk. > > How can that be the case when wxPython is using Gtk? Obviously, it does *not* always use Gtk. >> If your target platform includes Unix systems, you'll have to decide >> whether inconsistencies with the look and feel of the desktop are an >> issue for you. > > wxPython looks completely native on Unix, because it's using a native > widget set (Gtk). Same as above. -Samuel From tjreedy at udel.edu Fri Jun 29 15:34:54 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 29 Jun 2007 15:34:54 -0400 Subject: Rappresenting infinite References: <1182940919.351011.267020@n2g2000hse.googlegroups.com> <1182945569.081290.40870@c77g2000hse.googlegroups.com> <20070628234618.2907b52d@localhost> <20070629004542.31bbc7ac@localhost> Message-ID: "John Nagle" wrote in message news:iFchi.490$eY.360 at newssvr13.news.prodigy.net... | If Python numerics don't define | +INF, -INF, and NaN, along with the tests for them, that's a | flaw in the language. Are you volunteering to fix the 'flaw'? CPython floating point numerics are currently defined to be C doubles and whatever else the particular compiler/hardware provides. But Tim Peters said at least 5 years ago that a volunteer could try to improve portability. Various people have since talked about doing something. | We can assume IEEE floating point at this | late date; it's been standard for twenty years and Java assumes it. Not all processors running Python even have floats ;-) In any case, the IEEE standard did not seem to define a standard C binding. Neither did the C89 committee. So gcc and msc differ on how to spell such things. Not everyone is satisfied with the Java solution. From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Tue Jun 19 17:05:15 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Tue, 19 Jun 2007 23:05:15 +0200 Subject: static python classes ? References: <1182254405.901790.189190@p77g2000hsh.googlegroups.com> <5dq518F35ubh4U1@mid.uni-berlin.de> Message-ID: <5dquobF35956oU1@mid.individual.net> Diez B. Roggisch wrote: > With other OOP languages you mean Java. Which does have static > methods because they lack the notion of a function by its own, so > the shoehorned them into their "everything is inside a > class"-paradigm. ACK, but doesn't C++ have static methods too? Regards, Bj?rn -- BOFH excuse #236: Fanout dropping voltage too much, try cutting some of those little traces From arkanes at gmail.com Thu Jun 14 12:54:16 2007 From: arkanes at gmail.com (Chris Mellon) Date: Thu, 14 Jun 2007 11:54:16 -0500 Subject: Method much slower than function? In-Reply-To: References: <1181781612.939800.238890@q19g2000prn.googlegroups.com> <1181799961.148499.32210@o11g2000prd.googlegroups.com> Message-ID: <4866bea60706140954u6d339f1as2bbeeaf0efd27de9@mail.gmail.com> On 6/14/07, Peter Otten <__peter__ at web.de> wrote: > Peter Otten wrote: > > > Leo Kislov wrote: > > > >> On Jun 13, 5:40 pm, ido... at gmail.com wrote: > >>> Hi all, > >>> > >>> I am running Python 2.5 on Feisty Ubuntu. I came across some code that > >>> is substantially slower when in a method than in a function. > >>> > >>> >>> cProfile.run("bar.readgenome(open('cb_foo'))") > >>> > >>> 20004 function calls in 10.214 CPU seconds > >> > >>> >>> cProfile.run("z=r.readgenome(open('cb_foo'))") > >>> > >>> 20004 function calls in 0.041 CPU seconds > >>> > >> > >> I suspect open files are cached so the second reader > >> picks up where the first one left: at the of the file. > >> The second call doesn't do any text processing at all. > >> > >> -- Leo > > > > Indeed, the effect of attribute access is much smaller than what the OP is > > seeing: > > I have to take that back > Your tests (which I have snipped) show attribute access being about 3x slower than local access, which is consistent with my own tests. The OP is seeing a speed difference of 2 orders of magnitude. That's far outside the range that attribute access should account for. From george.sakkis at gmail.com Sun Jun 17 21:59:17 2007 From: george.sakkis at gmail.com (George Sakkis) Date: Mon, 18 Jun 2007 01:59:17 -0000 Subject: The Modernization of Emacs In-Reply-To: <1182120369.111379.87740@o61g2000hsh.googlegroups.com> References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182120369.111379.87740@o61g2000hsh.googlegroups.com> Message-ID: <1182131957.212093.24290@w5g2000hsg.googlegroups.com> On Jun 17, 6:46 pm, Philipp Leitner wrote: > Ever came to your mind that there are people (programmers and others) > who will not use emacs for their day-to-day work simply because they > have tools that suit them better for the work they have to do (Eclipse > for me, as an example)? > > Except from that: I personally don't feel that your rantings are > interesting enough to qualify for a 4 groups X-post ... this sort of > article goes well into a blog, but not so much on programmers > newsgroups (which are used for Q&A imho). You must be new here. Xah is a well-known self-important troll, crossposting his mostly off-topic and/or controversial ramblings and showing off his ignorance in a provocative condescending manner. Don't waste resources by replying, he rarely follows up anyway. From twisted0n3 at gmail.com Fri Jun 22 17:51:34 2007 From: twisted0n3 at gmail.com (Twisted) Date: Fri, 22 Jun 2007 21:51:34 -0000 Subject: The Modernization of Emacs: terminology buffer and keybinding In-Reply-To: References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182272495.990807.99110@a26g2000pre.googlegroups.com> <87tzt3ihev.fsf@kobe.laptop> <1182370216.961241.6960@n60g2000hse.googlegroups.com> <85zm2ufjpb.fsf@lola.goethe.zz> <1182372592.803332.288260@u2g2000hsc.googlegroups.com> Message-ID: <1182549094.366282.286740@m37g2000prh.googlegroups.com> On Jun 21, 12:03 pm, Robert Uhl wrote: > Twisted writes: > > >> Emacs is amazingly beginner-friendly for the power and flexibility it > >> provides. [snip] > > > That's a joke, right? I tried it a time or two. Every time it was > > rapidly apparent that doing anything non-trivial would require > > consulting a cheat sheet. The printed-out kind, since navigating to > > the help and back without already having the help displayed and open > > to the command reference was also non-trivial. > > C-h i, C-x b RET is non-trivial?!? Let's change that so that you see it the way most human beings see it: > > navigating to > > the help and back without already having the help displayed and open > > to the command reference was also non-trivial. > Erh h, dhsd f hHE is non-trivial? I'm sorry. I don't speak Chinese. I trust I've made my point. Not only does it insist you learn a whole other language (though I'm guessing it's not actually Chinese -- Greek, maybe), even when you know that's a bunch of keystrokes and even what they are... HOW IN THE BLOODY HELL IS IT SUPPOSED TO OCCUR TO SOMEONE TO ENTER THEM, GIVEN THAT THEY HAVE TO DO SO TO REACH THE HELP THAT WOULD TELL THEM THOSE ARE THE KEYS TO REACH THE HELP?! I suppose it just pops in there by divine inspiration? Or it's supposed to be self-evident to anyone who has TRUE wisdom? Or maybe it's just expected that you be mentored by an expert, who would know that arcane incantation and could pass it on to a new student. Well I've got news for you buddy -- there's no such thing as divine inspiration, it's not self-evident, and most people can't afford (if they could find) a tutor just to learn how to use A TEXT EDITOR. Of course, Notepad is so easy to use it doesn't even need help, despite which it's readily available. In case you forgot the bog- standard (and therefore it IS self-evident) "F1" there's even a "Help" menu in plain view as soon as you open a Notepad. This is the lowly Notepad, which I'll freely admit is the rusty bicycle of text editors, and it's much easier to use (including the help) than the supposed Mercedes-Benz of editors. [remainder snipped, apparently describing some piece of software that presents you automatically with an emacs tutorial if you start emacs while it's running. I've seen emacs a few times in my day but never whatever unnamed piece of software is being referred to here...but it does occur to me that a context-sensitive auto-popup cheat sheet tool would be useful on the typical unix system!] From S.Mientki-nospam at mailbox.kun.nl Tue Jun 5 15:55:11 2007 From: S.Mientki-nospam at mailbox.kun.nl (Stef Mientki) Date: Tue, 05 Jun 2007 21:55:11 +0200 Subject: Who uses Python? In-Reply-To: <1181062218.780387.219200@n4g2000hsb.googlegroups.com> References: <1180985830.288414.208850@q69g2000hsb.googlegroups.com> <1181028719.829671.22230@a26g2000pre.googlegroups.com> <1181034089.239173.282900@g4g2000hsf.googlegroups.com> <1181062218.780387.219200@n4g2000hsb.googlegroups.com> Message-ID: walterbyrd wrote: > On Jun 5, 3:01 am, Maria R wrote: >> I tend to agree with some earlier poster that if you use Python you >> are, in a sense, a programmer :o) >> > > Yes, in a sense. But, in another sense, that is sort of like saying > that people who post on message boards are "writers." > > I should have been more clear, when I posted "programmers" I meant > "professional programmers" i.e. people who develop software > applications for a living. I've heard that 80% of what google is doing, is done in Python ;-) I use Python as a replacement for MatLab, and intend to use it as replacement for Delphi, AutoIt, PHP, VB. And I'ld love to use it as a replacement for micro controller programming. The hardest to replace language is Delphi. And all the work I perform with these languages is paid ;-) The compagnies that only uses Python is growing. cheers, Stef From basilisk96 at gmail.com Tue Jun 5 23:15:28 2007 From: basilisk96 at gmail.com (Basilisk96) Date: Wed, 06 Jun 2007 03:15:28 -0000 Subject: Which class's comparison function is called? In-Reply-To: References: Message-ID: <1181099728.605706.279090@g4g2000hsf.googlegroups.com> Try adding the following diagnostic messages to your __eq__ class definitions, and see if it will dispel the confusion for the four equality tests you have tried: class A: def __init__(self,a): self.a = a def __eq__(self, other): print "(A) self:%r, other:%r" %(self.__class__, other.__class__) return self.a == other.a class B: def __init__(self,b): self.b = b def __eq__(self, other): print "(B) self:%r, other:%r" %(self.__class__, other.__class__) return self.b == other.b You are correct, Python evaluates the expressions from left to right. > A(1) == B(1) > ---> AttributeError: B instance has no attribute a The left instance's __eq__ method is invoked, which says, "is the value of self.a equal to the value of other.a ?"; and the answer is, "other has no attribute a to compare with self.a!" so you get an exception. > B(1) == A(1) > ---> AttributeError: A instance has no attribute b Same case as the first, but the instances have switched places... > A(1) == 3 > ---> AttributeError: 'int' object has no attribute a Same case as the first, but 'other' is now an object of type 'int', which inherently has no attribute 'a'. A similar effect will manifest when you will try to do: B(1) == 3 ---> AttributeError: 'int' object has no attribute 'b' > 3 == A(1) > ---> AttributeError: 'int' object has no attribute a > > Can someone explain this? I expected 3 == A(1) to use the __eq__ > function defined for 'int' objects. This last one is interesting. The '__eq__' method is not defined for 'int' objects. The '==' operator tests for value equivalence. As before, the left side is evaluated first, and evaluates to a simple integer value. No special methods are called. Now, the right side's value is evaluated. Since equality is being tested, the right side's __eq__ method is called, with the (self, other) arguments being (, 3) respectively. Since 'int' is the 'other' argument in this case, it again results in the exception "no attribute 'a' ". The last of the four tests that you have mentioned is giving you the trouble, right? Perhaps the solution is to add type-checking to the __eq__ method? (untested) def __eq__(self, other): if isinstance(other, int): tmp = other else: tmp = other.a # (other.b in class B definition) return self.a == tmp # (self.b in class B definition) Cheers, -Basilisk96 From xah at xahlee.org Tue Jun 19 13:04:38 2007 From: xah at xahlee.org (Xah Lee) Date: Tue, 19 Jun 2007 10:04:38 -0700 Subject: The Modernization of Emacs: exists already In-Reply-To: <1182093200.598418.218620@e9g2000prf.googlegroups.com> References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> Message-ID: <1182272678.877166.209640@j4g2000prf.googlegroups.com> Here are some Frequently Asked Questions about The Modernization of Emacs. They are slightly lengthy, so i've separated each item per post. The whole article can be found at http://xahlee.org/emacs/modernization.html ------------ Q: Aquamacs already does what you want. A: Aquamacs is a emacs variant based on emacs, for Apple's Macintosh computers, created in about 2004 by David Reitter. Aquamacs modifies emacs so that its user interface follows modern (Mac OS X) conventions. For example, copy, paste, undo shortcuts are cmd-c, cmd- v, cmd-z. Open file is cmd-o, saving is cmd-s. Close window is cmd-w. There is a redo command by default, with shortcut cmd-shift-z. By following a modern user interface, almost all points mentioned in this article are fixed in Aquamacs. For more info, see: Wikipedia Aquamacs? and Aquamac's home page at: Aquamacs.org ? As a emacs variant, it does help in spreading the idea that emacs user interface should be modernized. However, a third-party variant software is irrelevant to the modernization issue. For example, suppose Microsoft Word remained with its DOS era command line interface, for example, file is opened with [Esc] (to open the menus), [T] (for Transfer), [L] (for Load). Suppose Microsoft hired a third party to release a variant called MS AquaWord. This would not help Microsoft Word the software itself, and is likely to complicate the issue around Microsoft Word. Xah xah at xahlee.org ? http://xahlee.org/ From nick at craig-wood.com Wed Jun 27 06:30:06 2007 From: nick at craig-wood.com (Nick Craig-Wood) Date: Wed, 27 Jun 2007 05:30:06 -0500 Subject: import data.py using massive amounts of memory Message-ID: I've been dumping a database in a python code format (for use with Python on S60 mobile phone actually) and I've noticed that it uses absolutely tons of memory as compared to how much the data structure actually needs once it is loaded in memory. The programs below create a file (z.py) with a data structure in which looks like this -- z.py ---------------------------------------------------- z = { 0 : (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19), 1 : (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20), 2 : (2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21), [snip] 998 : (998, 999, 1000, 1001, 1002, ..., 1012, 1013, 1014, 1015, 1016, 1017), 999 : (999, 1000, 1001, 1002, 1003, ..., 1013, 1014, 1015, 1016, 1017, 1018), } ------------------------------------------------------------ Under python2.2-python2.4 "import z" uses 8 MB, whereas loading a pickled dump of the file only takes 450kB. This has been improved in python2.5 so it only takes 2.2 MB. $ python2.5 memory_usage.py Memory used to import is 2284 kB Total size of repr(z) is 105215 Memory used to unpickle is 424 kB Total size of repr(z) is 105215 $ python2.4 memory_usage.py Memory used to import is 8360 kB Total size of repr(z) is 105215 Memory used to unpickle is 456 kB Total size of repr(z) is 105215 $ python2.3 memory_usage.py Memory used to import is 8436 kB Total size of repr(z) is 105215 Memory used to unpickle is 456 kB Total size of repr(z) is 105215 $ python2.2 memory_usage.py Memory used to import is 8568 kB Total size of repr(z) is 105215 Memory used to unpickle is 392 kB Total size of repr(z) is 105215 $ python2.1 memory_usage.py Memory used to import is 10756 kB Total size of repr(z) is 105215 Memory used to unpickle is 384 kB Total size of repr(z) is 105215 Why does it take so much memory? Is it some consequence of the way the datastructure is parsed? Note that once it has made the .pyc file the subsequent runs take even less memory than the cpickle import. S60 python is version 2.2.1. It doesn't have pickle unfortunately, but it does have marshal and the datastructures I need are marshal-able so that provides a good solution to my actual problem. Save the two programs below with the names given to demonstrate the problem. Note that these use some linux-isms to measure the memory used by the current process which will need to be adapted if you don't run it on linux! -- memory_usage.py ----------------------------------------- import os import sys import re from cPickle import dump def memory(): """Returns memory used (RSS) in kB""" status = open("/proc/self/status").read() match = re.search(r"(?m)^VmRSS:\s+(\d+)", status) memory = 0 if match: memory = int(match.group(1)) return memory def write_file(): """Write the file to be imported""" fd = open("z.py", "w") fd.write("z = {\n") for i in xrange(1000): fd.write(" %d : %r,\n" % (i, tuple(range(i,i+20)))) fd.write("}\n") fd.close() def main(): write_file() before = memory() from z import z after = memory() print "Memory used to import is %s kB" % (after-before) print "Total size of repr(z) is ",len(repr(z)) # Save a pickled copy for later dump(z, open("z.bin", "wb")) # Run the next part os.system("%s memory_usage1.py" % sys.executable) if __name__ == "__main__": main() -- memory_usage1.py ---------------------------------------- from memory_usage import memory from cPickle import load before = memory() z = load(open("z.bin", "rb")) after = memory() print "Memory used to unpickle is %s kB" % (after-before) print "Total size of repr(z) is ",len(repr(z)) ------------------------------------------------------------ -- Nick Craig-Wood -- http://www.craig-wood.com/nick From bernhard.voigt at gmail.com Thu Jun 28 11:33:30 2007 From: bernhard.voigt at gmail.com (bernhard.voigt at gmail.com) Date: Thu, 28 Jun 2007 15:33:30 -0000 Subject: Segfault due to threads created by external modules Message-ID: <1183044810.325423.278760@n2g2000hse.googlegroups.com> Dear list, I'm using two external modules (matplotlib and pyroot). Both are using different GUI threads (internally) Unfortunately, pretty soon after I've loaded both modules and made some function calls (without invoking GUI commands), python dies with a segfault. A libthread_db captures the stack trace. My python version is 2.5 and I'm on a Scientific Linux 5 system. *** Break *** segmentation violation Using host libthread_db library "/lib/libthread_db.so.1". Attaching to program: /proc/20957/exe, process 20957 [Thread debugging using libthread_db enabled] [New Thread -1208964416 (LWP 20957)] [New Thread 133323664 (LWP 20964)] [New Thread 48200592 (LWP 20958)] 0x009e2402 in __kernel_vsyscall () Thread 3 (Thread 48200592 (LWP 20958)): #0 0x009e2402 in __kernel_vsyscall () #1 0x4e94bf91 in ___newselect_nocancel () from /lib/libc.so.6 #2 0x0494fcac in Tcl_InitNotifier () from /usr/lib/libtcl8.4.so #3 0x4e9f92db in start_thread () from /lib/libpthread.so.0 #4 0x4e95312e in clone () from /lib/libc.so.6 Thread 2 (Thread 133323664 (LWP 20964)): #0 0x009e2402 in __kernel_vsyscall () #1 0x4e9ff14e in sem_wait at GLIBC_2.0 () from /lib/libpthread.so.0 #2 0x00f2166e in PyThread_acquire_lock (lock=0x89b1ea8, waitflag=1) at Python/thread_pthread.h:349 #3 0x00eeff27 in PyEval_RestoreThread (tstate=0xa255820) at Python/ ceval.c:312 #4 0x002bec23 in time_sleep (self=0x0, args=0x9afcfec) at /tmp/bvoigt/ Python-2.5.1/Modules/timemodule.c:921 #5 0x00ea900d in PyCFunction_Call (func=0xb7e544ac, arg=0x9afcfec, kw=0x0) at Objects/methodobject.c:108 #6 0x00ef65df in PyEval_EvalFrameEx (f=0xa30028c, throwflag=0) at Python/ceval.c:3564 #7 0x00ef7734 in PyEval_EvalCodeEx (co=0xb7cd7698, globals=0xb7cb813c, locals=0x0, args=0x9afcfd8, argcount=1, kws=0xa05cf40, kwcount=0, defs=0x0, defcount=0, closure=0x0) at Python/ceval.c:2831 #8 0x00e953c0 in function_call (func=0xb7cdad14, arg=0x9afcfcc, kw=0x9af99bc) at Objects/funcobject.c:517 #9 0x00e734f7 in PyObject_Call (func=0x0, arg=0x9afcfcc, kw=0x9af99bc) at Objects/abstract.c:1860 #10 0x00ef441b in PyEval_EvalFrameEx (f=0xa30012c, throwflag=0) at Python/ceval.c:3844 #11 0x00ef6260 in PyEval_EvalFrameEx (f=0xa2fff9c, throwflag=0) at Python/ceval.c:3650 #12 0x00ef7734 in PyEval_EvalCodeEx (co=0xb7d93a88, globals=0xb7d9024c, locals=0x0, args=0x9afcfb8, argcount=1, kws=0x0, kwcount=0, defs=0x0, defcount=0, closure=0x0) at Python/ceval.c:2831 #13 0x00e952ea in function_call (func=0xb7d9d09c, arg=0x9afcfac, kw=0x0) at Objects/funcobject.c:517 #14 0x00e734f7 in PyObject_Call (func=0x0, arg=0x9afcfac, kw=0x0) at Objects/abstract.c:1860 #15 0x00e7ad15 in instancemethod_call (func=0x9af6054, arg=0x9afcfac, kw=0x0) at Objects/classobject.c:2497 #16 0x00e734f7 in PyObject_Call (func=0x0, arg=0xb7eca02c, kw=0x0) at Objects/abstract.c:1860 #17 0x00eef43c in PyEval_CallObjectWithKeywords (func=0x9af6054, arg=0xb7eca02c, kw=0x0) at Python/ceval.c:3433 #18 0x00f25d14 in t_bootstrap (boot_raw=0xa24eec8) at ./Modules/ threadmodule.c:424 #19 0x4e9f92db in start_thread () from /lib/libpthread.so.0 #20 0x4e95312e in clone () from /lib/libc.so.6 Thread 1 (Thread -1208964416 (LWP 20957)): #0 0x009e2402 in __kernel_vsyscall () #1 0x4e9136ab in __waitpid_nocancel () from /lib/libc.so.6 #2 0x4e8bba0f in do_system () from /lib/libc.so.6 #3 0x4e8bbdc2 in system () from /lib/libc.so.6 #4 0x4ea010bd in system () from /lib/libpthread.so.0 I have no idea how to solve this. Somebody else has an idea? Thanks! Bernhard From vel.accel at gmail.com Wed Jun 20 22:20:57 2007 From: vel.accel at gmail.com (D.Hering) Date: Wed, 20 Jun 2007 19:20:57 -0700 Subject: Downloading from a clean url Message-ID: <1182392457.751054.173500@n60g2000hse.googlegroups.com> General: How do I download a page's data from a clean url. Specific: I'm using PyQt's QHttp and QUrl classes for requests and acquiring the response, but I can't figure out how to access a page's data without knowing the file of the url's path. For instance http://kde.org Thanks, -Dieter From nszabolcs at gmail.com Thu Jun 7 18:32:22 2007 From: nszabolcs at gmail.com (Szabolcs Nagy) Date: Thu, 07 Jun 2007 15:32:22 -0700 Subject: Bragging about Python In-Reply-To: References: <46681369$0$12126$3b214f66@tunews.univie.ac.at> Message-ID: <1181255542.549027.164730@p47g2000hsd.googlegroups.com> Cameron Laird wrote: > In article <46681369$0$12126$3b214f66 at tunews.univie.ac.at>, > Mathias Panzenboeck wrote: > def fib(): > generation, parent_rabbits, baby_rabbits = 1, 1, 1 > while True: > yield generation, baby_rabbits > generation += 1 > parent_rabbits, baby_rabbits = \ > baby_rabbits, parent_rabbits + baby_rabbits > > for pair in fib(): > if pair[0] > 100: > break > print "Generation %d has %d (baby) rabbits." % pair > > as more appealing to non-Pythoneers. I'm still suspicious about > how they're going to react to itertools.islice(). Now, though, > I've begun to question my own sense of style ... actually i don't like when a tutorial uses over complicated cute names if the context is obvious (fibonacci) then we don't need to add 'parent_rabbits' and such identifiers eg i find more readable and clear the following: def fib(): a, b = 0, 1 while True: yield a a, b = b, a + b for (n, fn) in enumerate(fib()): if n > 100: break print "F[%d] = %d" % (n, fn) ymmv From mail at timgolden.me.uk Wed Jun 6 10:53:56 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Wed, 06 Jun 2007 15:53:56 +0100 Subject: Can os.remove followed by os.path.isfile disagree? In-Reply-To: <1181140547.279974.83550@q66g2000hsg.googlegroups.com> References: <1181140547.279974.83550@q66g2000hsg.googlegroups.com> Message-ID: <4666CA84.9020907@timgolden.me.uk> ppaterson at gmail.com wrote: > Can os.path.isfile(x) ever return True after os.remove(x) has > successfully completed? (Windows 2003, Python 2.3) > > We had a couple of failures in a server application that we cannot yet > reproduce in a simple case. Analysis of the code suggests that the > only possible explanation is that the following occurs, > > os.remove(x) > .... stuff > if os.path.isfile(x): > raise "Ooops, how did we get here?" > file(x, "wb").write(content) > > We end up in the raise. By the time we get to look at the system the > file is actually gone, presumably because of the os.remove. > > The "stuff" is a handful of lines of code which don't take any > significant time to perform. There are no "try" blocks to mask a > failure in the os.remove call. > > > The application is multithreaded so it is possible that another thread > writes to the file between the "remove" and the "isfile", but at the > end of the failure the file is actually not on the filesystem and I > don't believe there is a way that the file could be removed again in > this scenario. The os.remove implementation (in posixmodule.c) uses the DeleteFileW/A API call (depending on Unicode or not): http://msdn2.microsoft.com/En-US/library/aa363915.aspx No suggestion there that it might return before completion, but I'd be surprised if it did. The most likely bet would seem to be a race condition as you suggest below. Doesn't have to be from a thread in your program, although I assume you know best about your own filesystem ;) Another possibility -- I suppose, though without any authority -- is that the .remove is silently swallowing an error (ie failing at OS level without telling Python so no exception is raised). Much more likely is that somewhere in that "...stuff" is something which inadvertently recreates the file. Don't suppose you've got some kind of flashy software running which intercepts OS file-manipulation calls for Virus or Archiving purposes? TJG From showell30 at yahoo.com Mon Jun 11 19:16:36 2007 From: showell30 at yahoo.com (Steve Howell) Date: Mon, 11 Jun 2007 16:16:36 -0700 (PDT) Subject: SimplePrograms challenge In-Reply-To: <1181602284.131343.145200@i38g2000prf.googlegroups.com> Message-ID: <835146.69596.qm@web33504.mail.mud.yahoo.com> --- infidel wrote: > # reading CSV files, tuple-unpacking > import csv > > #pacific.csv contains: > #1,CA,California > #2,AK,Alaska > #3,OR,Oregon > #4,WA,Washington > #5,HI,Hawaii > > reader = csv.reader(open('pacific.csv')) > for id, abbr, name in reader: > print '%s is abbreviated: "%s"' % (name, abbr) > Definitely on track. I like that it uses a batteries-included module, and this program definitely reminds me of the type of smallish, but very useful, programs that I write in Python frequently on the job. I would add one more criterion to my challenge, though. You should be able to run the program simply by copying/pasting the code into a file and running Python. So I would change your program (as currently presented) to write its own input file for demonstration purposes. One more suggestion--maybe it could exercise a little more of the CVS module, i.e. have something in the data that would trip up the ','.split() approach? ____________________________________________________________________________________ Need a vacation? Get great deals to amazing places on Yahoo! Travel. http://travel.yahoo.com/ From evan at yelp.com Tue Jun 26 13:12:22 2007 From: evan at yelp.com (Evan Klitzke) Date: Tue, 26 Jun 2007 10:12:22 -0700 Subject: Hi How to implement switch case statement. In-Reply-To: References: Message-ID: Read this thread, which was discussed on the list a few days ago: http://www.mail-archive.com/python-list at python.org/msg150704.html On 6/25/07, parasuram.nooranianand at wipro.com wrote: > > > Hi > > My requirement is to check a variable with a set of constant values and call a particular function depending on the value of the variable. A C-language implementation might look something like : > > switch (a) { > > case 1 : func1(); > case 2 : func2() ; > default : func3(); > } > > How to do it in Python ? > > Ofcourse an if-elif construct can also be used to do the job, which is indeed my last option. However i would like to know if a 'switch-case' option is available. > > I found some implementations involving dictionaries and lambdas but i don't know how suitable they might be for this kind of an implementation. > > Any suggestions and ideas welcome > > > > Thanks and regards > Parasuram N.A. > I know the answers to all the questions > But its just that i don't find some of them worth answering > > > > > > The information contained in this electronic message and any attachments to this message are intended for the exclusive use of the addressee(s) and may contain proprietary, confidential or privileged information. If you are not the intended recipient, you should not disseminate, distribute or copy this e-mail. Please notify the sender immediately and destroy all copies of this message and any attachments. > > WARNING: Computer viruses can be transmitted via email. The recipient should check this email and any attachments for the presence of viruses. The company accepts no liability for any damage caused by any virus transmitted by this email. > > www.wipro.com > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Evan Klitzke From dak at gnu.org Wed Jun 20 17:35:40 2007 From: dak at gnu.org (David Kastrup) Date: Wed, 20 Jun 2007 23:35:40 +0200 Subject: The Modernization of Emacs: terminology buffer and keybinding References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182272495.990807.99110@a26g2000pre.googlegroups.com> <87tzt3ihev.fsf@kobe.laptop> <1182370216.961241.6960@n60g2000hse.googlegroups.com> <85zm2ufjpb.fsf@lola.goethe.zz> <1182372592.803332.288260@u2g2000hsc.googlegroups.com> <1182373919.262388.100740@c77g2000hse.googlegroups.com> <85r6o6fhkb.fsf@lola.goethe.zz> <1182375045.626510.188170@m36g2000hse.googlegroups.com> Message-ID: <85myyufgwj.fsf@lola.goethe.zz> Twisted writes: > On Jun 20, 5:21 pm, David Kastrup wrote: >> Twisted writes: >> > On Jun 20, 4:49 pm, Twisted wrote: >> >> On Jun 20, 4:35 pm, David Kastrup wrote: >> >> > Twisted writes: >> >> > > I continue to suspect that there's an ulterior motive for making and >> >> > > keeping certain software actively beginner-hostile; a certain macho >> >> > > elitism also seen with light aircraft pilots and commented on at >> >> > >www.asktog.com(exactURLescapes me; sorry). >> >> >> > You are babbling. >> >> >> No, I am not. You, however, are being gratuitously insulting. >> >> > I have that exact URL now -- >> >http://www.asktog.com/columns/027InterfacesThatKill.html >> >> Utterly unrelated to Emacs. > > I think it is quite relevant. Clunky computer interfaces may not be > so dramatically dangerous, but they certainly can hamper > productivity. But Emacs does not have a "clunky" interface. > Between Windows bugs and gratuitous misfeatures (e.g. DRM) and Unix > clunkiness, billions of dollars of potential productivity is lost > worldwide every *month*. You are spewing again. -- David Kastrup, Kriemhildstr. 15, 44793 Bochum From bill_maxwell_notMyRealAddress at notreal.net Sat Jun 2 01:20:27 2007 From: bill_maxwell_notMyRealAddress at notreal.net (Bill Maxwell) Date: Sat, 02 Jun 2007 01:20:27 -0400 Subject: PythonCard or Dabo? References: <1174326003.145538.113010@y80g2000hsf.googlegroups.com> Message-ID: <2fv163d2lv8gd9g3qqfbh91a7hraqbbi7v@4ax.com> On 19 Mar 2007 10:40:03 -0700, kyosohma at gmail.com wrote: ... >You might want to submit this to the wxpython news-group. ... What is the name of this newsgroup? I can't seem to locate it on my news server. Thanks, Bill From cedb816 at yahoo.com Thu Jun 28 11:42:01 2007 From: cedb816 at yahoo.com (ce) Date: Thu, 28 Jun 2007 08:42:01 -0700 Subject: Face Recognition In-Reply-To: <5ec525F388c7bU1@mid.uni-berlin.de> References: <1182814191.138864.80450@w5g2000hsg.googlegroups.com> <5ec525F388c7bU1@mid.uni-berlin.de> Message-ID: <1183045321.531035.185540@i13g2000prf.googlegroups.com> On Jun 26, 5:37 pm, "Diez B. Roggisch" wrote: > Henrik Lied wrote: > > Hi there! > > > Has anyone made effort to try to create a python binding to a facial > >recognitionsoftware [1]? > > > For those of you with some experience - would this be very hard? > > OpenCV has a python-binding. And a ctypes-binding. > > Diez I would add that the OpenCV includes face recognition example. From acfer at hotmail.com Tue Jun 19 08:15:17 2007 From: acfer at hotmail.com (ferrad) Date: Tue, 19 Jun 2007 05:15:17 -0700 Subject: File processing - is Python suitable? Message-ID: <1182255317.327241.196330@n2g2000hse.googlegroups.com> I have not used Python before, but believe it may be what I need. I have large text files containing text, numbers, and junk. I want to delete large chunks process other bits, etc, much like I'd do in an editor, but want to do it automatically. I have a set of generic rules that my fingers follow to process these files, which all follow a similar template. Question: can I translate these types of rules into programmatical constructs that Python can use to process these files? Can Python do the trick? ferrad From weheh at verizon.net Sat Jun 2 14:55:36 2007 From: weheh at verizon.net (Richard Gordon) Date: Sat, 02 Jun 2007 18:55:36 GMT Subject: Need help! win32 com_error 'Exception occurred' Message-ID: I've got a fatal bug using Parente's pyTTS with Python 2.3 on Windoze 32 using MS SAPI 5.1 and Hammond's win32 module. The test program is import pyTTS tts = pyTTS.Create() tts.Speak('Hello world.') The resulting debug trace is: PythonWin 2.3.5 (#62, Feb 8 2005, 16:23:02) [MSC v.1200 32 bit (Intel)] on win32. Portions Copyright 1994-2006 Mark Hammond - see 'Help/About PythonWin' for further copyright information. Traceback (most recent call last): File "C:\PROGRA~1\Python23\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py", line 307, in RunScript debugger.run(codeObject, __main__.__dict__, start_stepping=0) File "C:\PROGRA~1\Python23\Lib\site-packages\pythonwin\pywin\debugger\__init__.py", line 60, in run _GetCurrentDebugger().run(cmd, globals,locals, start_stepping) File "C:\PROGRA~1\Python23\Lib\site-packages\pythonwin\pywin\debugger\debugger.py", line 631, in run exec cmd in globals, locals File "C:\yakitome\test\examples\ex1.py", line 4, in ? tts.Speak('Hello world.') File "C:\PROGRA~1\Python23\Lib\site-packages\pyTTS\sapi.py", line 213, in Speak self.speech.Speak(text, flagsum) File "C:\Program Files\Python23\lib\site-packages\win32com\gen_py\C866CA3A-32F7-11D2-9602-00C04F8EE628x0x5x0.py", line 2637, in Speak , Flags) com_error: (-2147352567, 'Exception occurred.', (0, None, None, None, 0, -2147201015), None) >>> The system does not have a sound card --- could that be an issue? My head is about to explode trying to solve this problem, so your help and suggestions will be much appreciated. From leonhard.vogt at gmx.ch Sun Jun 3 03:02:11 2007 From: leonhard.vogt at gmx.ch (Leonhard Vogt) Date: Sun, 03 Jun 2007 09:02:11 +0200 Subject: subexpressions (OT: math) In-Reply-To: References: Message-ID: <4662675b$1_5@news.bluewin.ch> >> Yes, I understand that, but what is the geometrical >> meaning of the square root of an arc length? > > That's a different question to your original question, which was asking > about the square root of an angle. > >> And what would the units be? > > Angles are a ratio of two lengths, and are therefore dimensionless units. > So the square root of an angle is just another angle, in the same units, > and it requires no special geometric interpretation: the square root of 25 > degrees (just an angle) is 5 degrees (just another angle). But sqrt(25?) = sqrt(25/180*pi) = 5*sqrt(180/pi) != 5? Leonhard From Thomas.Lenarz at netcologne.de Sat Jun 23 08:49:39 2007 From: Thomas.Lenarz at netcologne.de (Thomas Lenarz) Date: Sat, 23 Jun 2007 12:49:39 GMT Subject: Python live environment on web-site? References: <46794396.442103@news.netcologne.de> Message-ID: <467d1621.1266073@news.netcologne.de> On Wed, 20 Jun 2007 15:18:26 GMT, Thomas.Lenarz at netcologne.de (Thomas Lenarz) wrote: >Hi all, > >I was wondering if there was a python-live-environment available on a >public web-site similar to the ruby-live-tutorial on Thanks a lot for all your replies. I looked at the "TryPython-Sites" and will have a look at crunchy, although I in fact was looking for something already hosted somewhere and ready to use. Nonetheless, crunchy looks very interesting in general. Thanks again, Thomas From rzantow at gmail.com Thu Jun 14 06:46:55 2007 From: rzantow at gmail.com (rzed) Date: Thu, 14 Jun 2007 10:46:55 +0000 Subject: SimplePrograms challenge References: <466F27A3.8000106@gmail.com> Message-ID: Steven Bethard wrote in news:466F27A3.8000106 at gmail.com: > Steve Howell wrote: >> --- George Sakkis wrote: >>> from itertools import count, ifilter >>> def sieve(): >>> seq = count(2) >>> while True: >>> p = seq.next() >>> seq = ifilter(p.__rmod__, seq) >>> yield p > [snip] >> Is there a way to broaden the problem somehow, so that >> it can be a longer solution and further down on the >> page, and so that I can continue to enforce my >> somewhat arbitrary rule of ordering examples by how >> long they are? > > How about we just comment it better? > > import itertools > > def iter_primes(): > # an iterator of all numbers between 2 and +infinity > numbers = itertools.count(2) > > # generate primes forever > while True > > # generate the first number from the iterator, > # which should always be a prime > prime = numbers.next() > yield prime > > # lazily remove all numbers from the iterator that > # are divisible by prime we just selected > numbers = itertools.ifilter(prime.__rmod__, numbers) > > I think that's 17-ish, though you could shrink it down by > removing some of the spaces. > > STeVe How about including a driver? Generators are frustrating for newbies (including oldies new to generators) because they don't actually do anything unless you know how to use them. Given the above, what's a newbie going to try first? Something like: >>> iter_primes() Hmmm. Doesn't do anything. How about >>> for ix in range(10): ... print iter_primes() Not what you might expect. Later: >>> for ix in range(10): ... print iter_primes().next() Hmmmmm.... ... and so on. In much of Python's documentation, and in this case, an occasional working example of use would go FAR in aiding understanding of the underlying concept. -- rzed From cai.haibin at gmail.com Sun Jun 3 20:59:51 2007 From: cai.haibin at gmail.com (james_027) Date: Mon, 04 Jun 2007 00:59:51 -0000 Subject: excel library without COM Message-ID: <1180918791.467050.186520@r19g2000prf.googlegroups.com> Hi, is there any library to help me write excel files without using win com? because i'll be working on linux platform. At the same time I could want to perform some formatting, merging of cells. adding sheets and etc ... Thanks james From apatheticagnostic at gmail.com Wed Jun 6 19:50:39 2007 From: apatheticagnostic at gmail.com (kaens) Date: Wed, 6 Jun 2007 19:50:39 -0400 Subject: MySQL InterfaceError In-Reply-To: <008e01c7a7a5$ddaf8ae0$0f01a8c0@desktop9> References: <001e01c7a6f3$e687ed40$0f01a8c0@desktop9> <002901c7a6f4$f55e56a0$0f01a8c0@desktop9> <008e01c7a7a5$ddaf8ae0$0f01a8c0@desktop9> Message-ID: <163f0ce20706061650k5708926ck449c53bf0bb39a81@mail.gmail.com> On 6/5/07, Joe wrote: > > > > > >File "build/bdist.linux-i686/egg/MySQLdb/cursors.py", line > 147, in execute > > > charset = db.character_set_name() > > > > > >InterfaceError: (0, '') > > > > We got it working. It was caused by passing a database connection to a > module: > > > > import MySQLdb > > import module_name > > connection = MySQLdb.connect(host='localhost', user='user', > passwd='password', db='database') > > module = module_name.ClassName(connection) > > > > But, when the connection was made within the module itself, it would work > flawlessly every time. Can someone explain to me why this is? > > > > Jough > -- > http://mail.python.org/mailman/listinfo/python-list > Try passing the cursor and not the connection - import MySQLdb import module_name connection = MySQLdb.connect(host='localhost', user='user', passwd='password', db='database') cursor = connection.cursor() module = module_name.ClassName(cursor) You'll probably have to modify the module's code a bit as well, but it should work. From evan at yelp.com Wed Jun 13 04:11:01 2007 From: evan at yelp.com (Evan Klitzke) Date: Wed, 13 Jun 2007 01:11:01 -0700 Subject: a question about unicode in python In-Reply-To: <6faf39c90706130056n5c32cff3v534dceccd339b570@mail.gmail.com> References: <1181663182.251071.10540@i13g2000prf.googlegroups.com> <6faf39c90706130056n5c32cff3v534dceccd339b570@mail.gmail.com> Message-ID: On 6/13/07, Andre Engels wrote: > 2007/6/12, WolfgangZ : > > hzqij schrieb: > > > i have a python source code test.py > > > > > > # -*- coding: UTF-8 -*- > > > > > > # s is a unicode string, include chinese > > > s = u'??' > > > > > > then i run > > > > > > $ python test.py > > > UnicodeDecodeError: 'utf8' codec can't decode bytes in position 0-1: > > > invalid data > > > > > > by in python interactive, it is right > > > > > >>>> s = u'??' > > > > > > why? > > > > > > > > > > just an idea: is your text editor really supporting utf-8? In the mail > > it is only displayed as '??' which looks for me as the mail editor did > > not send the mail as utf. Try to attach a correct text file. > > That must be your mail client, not his text editor or mail client. I > do see two Chinese characters in the message. Nonetheless, the email is not UTF-8 encoded (it's encoded in gb2312, which is much more commonly used in China than UTF-8). It's likely that the source code file is encoded using GB characters as well. -- Evan Klitzke From robert.kern at gmail.com Tue Jun 12 21:30:35 2007 From: robert.kern at gmail.com (Robert Kern) Date: Tue, 12 Jun 2007 20:30:35 -0500 Subject: questions about solving equations in scipy In-Reply-To: <466ED410.2010507@gmail.com> References: <466ED410.2010507@gmail.com> Message-ID: fdu.xiaojf at gmail.com wrote: > Hi all, > > I have two questions about scipy. You're likely to get a better response from the scipy mailing list. Here, you'll primarily get me, and I have to rush out right now. http://www.scipy.org/Mailing_Lists > 1) When I was trying to solve a single variable equations using scipy, I > found two methods: scipy.optimize.fsolve, which is designated to find the > roots of a polynomial, No, it finds the roots of a non-linear system of N functions in N variables. The documentation makes no mention of polynomials. > and scipy.optimize.newton, which is used for Scalar > function root finding according to the help(). There's also brentq, brenth, ridder, and bisect for this problem. > I have tried both, and it seemed that both worked well, and fsolve ran > faster. > > My questions is, which is the right choose ? Whichever one works faster and more robustly for your problem. fsolve is implemented in FORTRAN, which sometimes helps. I do recommend looking at the brentq and brenth if you can provide bounds rather than just an initial guess. > 2) I have to solve a linear equation, with the constraint that all > variables should be positive. Currently I can solve this problem by > manually adjusting the solution in each iteration after get the solution > bu using scipy.linalg.solve(). > > Is there a smart way ? I don't think that's a well-defined problem. Either the (unique) solution is within the constraint or it's not. Are you sure you don't want to find the minimum-error solution that obeys the constrain, instead? -- 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 showell30 at yahoo.com Mon Jun 11 17:56:05 2007 From: showell30 at yahoo.com (Steve Howell) Date: Mon, 11 Jun 2007 14:56:05 -0700 (PDT) Subject: SimplePrograms challenge Message-ID: <427935.29664.qm@web33501.mail.mud.yahoo.com> Hi, I'm offering a challenge to extend the following page by one good example: http://wiki.python.org/moin/SimplePrograms Right now the page starts off with 15 examples that cover lots of ground in Python, but they're still scratching the surface. (There are also two Eight Queens implementations, but I'm looking to fill the gap in lines-of-code, and they're a little long now.) I'm looking for a good 16-line code example with the following qualities: 1) It introduces some important Python concept that the first 15 programs don't cover. 2) It's not too esoteric. Python newbies are the audience (but you can assume they're not new to programming in general). 3) It runs on Python 2.4. 4) It doesn't just demonstrate a concept; it solves a problem at face value. (It can solve a whimsical problem, like counting rabbits, but the program itself should be "complete" and "suitably simple" for the problem at hand.) 5) You're willing to have your code reviewed by the masses. 6) No major departures from PEP 8. Any takers? -- Steve ____________________________________________________________________________________ Looking for a deal? Find great prices on flights and hotels with Yahoo! FareChase. http://farechase.yahoo.com/ From fred at adventistcare.org Thu Jun 28 13:01:07 2007 From: fred at adventistcare.org (Sells, Fred) Date: Thu, 28 Jun 2007 13:01:07 -0400 Subject: Evolution of a pythonistas! Message-ID: > > Wow Fred! You're awesome! How did you get 20 years in of Python when > it was created in 1991? You're right, programming skills exceed basic math. I think I started around 1990 with version 0.92 beta. From doug at alum.mit.edu Fri Jun 15 15:05:24 2007 From: doug at alum.mit.edu (Douglas Alan) Date: Fri, 15 Jun 2007 15:05:24 -0400 Subject: Python's "only one way to do it" philosophy isn't good? References: <1181368143.874341.273140@r19g2000prf.googlegroups.com> Message-ID: "Terry Reedy" writes: > Try suggesting on a Lisp or Scheme group that having only one type > of syntax (prefix expressions) lacks something and that they should > add variety in the form of statement syntax ;-) Hint: some Lispers > have bragged here about the simplicity of 'one way to do it' and put > Python down for its mixed syntax. (Of course, this does not mean > that some dialects have not sneaked in lists of statements thru a > back door ;-). Almost all Lisp dialects have an extremely powerful macro mechanism that lets users and communities extend the syntax of the language in very general ways. Consequently, dialects such a Scheme try to keep the core language as simple as possible. Additional ways of doing things can be loaded in as a library module. So, a language such as Scheme may have no *obvious* way of something, and yet may provide excellent means to extend the language so that many obvious ways might be provided. |>oug From doug at alum.mit.edu Fri Jun 29 12:03:03 2007 From: doug at alum.mit.edu (Douglas Alan) Date: Fri, 29 Jun 2007 12:03:03 -0400 Subject: Python's "only one way to do it" philosophy isn't good? References: <7xy7i7xjl5.fsf@ruckus.brouhaha.com> Message-ID: "Chris Mellon" writes: >> On the other hand, in Python, you can be 100% sure that your files >> will be closed in a timely manner without explicitly closing them, as >> long as you are safe in making certain assumptions about how your code >> will be used. Such assumptions are called "preconditions", which are >> an understood notion in software engineering and by me when I write >> software. > Next time theres one of those "software development isn't really > engineering" debates going on I'm sure that we'll be able to settle > the argument by pointing out that relying on *explicitly* unreliable > implementation details is defined as "engineering" by some people. The proof of the pudding is in it's eating. I've worked on very large programs that exhibited very few bugs, and ran flawlessly for many years. One managed the memory remotely of a space telescope, and the code was pretty tricky. I was sure when writing the code that there would be a number of obscure bugs that I would end up having to pull my hair out debugging, but it's been running flawlessly for more than a decade now, without require nearly any debugging at all. Engineering to a large degree is knowing where to dedicate your efforts. If you dedicate them to where they are not needed, then you have less time to dedicate them to where they truly are. |>oug From showell30 at yahoo.com Sat Jun 2 11:31:15 2007 From: showell30 at yahoo.com (Steve Howell) Date: Sat, 2 Jun 2007 08:31:15 -0700 (PDT) Subject: subexpressions In-Reply-To: <45023$46618025$d443bb3a$19391@news.speedlinq.nl> Message-ID: <408034.91081.qm@web33506.mail.mud.yahoo.com> --- Stef Mientki wrote: > Maybe he meant > sin(x)^2 + cos(x)^2 > which is well known demodulation technique if you > create two signals 90 degrees out of phase. > There's a shorter way to phrase that expression, of course. :) 1 ____________________________________________________________________________________ Moody friends. Drama queens. Your life? Nope! - their life, your story. Play Sims Stories at Yahoo! Games. http://sims.yahoo.com/ From rridge at caffeine.csclub.uwaterloo.ca Mon Jun 4 13:12:07 2007 From: rridge at caffeine.csclub.uwaterloo.ca (Ross Ridge) Date: Mon, 04 Jun 2007 13:12:07 -0400 Subject: Python, Dutch, English, Chinese, Japanese, etc. References: Message-ID: Ross Ridge wrote: > Translating keywords and standard identifiers into Chinese could make > learning Python even more difficult. It would probably make things > easier for new programmers, but I don't know if serious programmers would > actually prefer programming using Chinese keywords. It would make their > Python implementations incompatible with the standard implementation, they > wouldn't be able to use third-party modules and their own code wouldn't > be portable. If novice Chinese programmers would have to unlearn much > of they've learned in order to become serious Python programmers are > you really doing them a favour by teaching them Chinese Python? > > It would really only work if Chinese Python became it own successful > dialect of Python, independent of the standard Python implementation. > Chinese Python programmers would be isolated from other Python > programmers, each with their own set of third-party modules and little > code sharing between the two groups. I don't think this would be good > for Python as whole. Wildemar Wildenburger wrote: >I don't see the problem here. The bytecode wouldn't change (right?). Python code generally isn't shared as bytecode and it's not just keywords we're talking about here, all standard Python identifiers (eg. "os" and "sys") would be translated too. >So what? One would have to make sure that the interprter understands both >(or to generalize: all) language versions of python and wham! That might work, you'd need both the standard and Chinese versions the Python standard libraries. I doubt anyone outside of China would want a distribution that included both, so there would still be barriers to code sharing between the two communities. Interestingly, someone has already created a Chinese version of Python much like Steve Howell suggested: http://www.chinesepython.org/cgi_bin/cgb.cgi/home.html http://www.chinesepython.org/cgi_bin/cgb.cgi/english/english.html Apparently it hasn't been updated in almost four years, so I don't know much use it gets. Ross Ridge -- l/ // Ross Ridge -- The Great HTMU [oo][oo] rridge at csclub.uwaterloo.ca -()-/()/ http://www.csclub.uwaterloo.ca/~rridge/ db // From michele.simionato at gmail.com Sat Jun 30 02:14:51 2007 From: michele.simionato at gmail.com (Michele Simionato) Date: Sat, 30 Jun 2007 06:14:51 -0000 Subject: Python's "only one way to do it" philosophy isn't good? In-Reply-To: References: <7xejjzmk7u.fsf@ruckus.brouhaha.com> <7xy7i7xjl5.fsf@ruckus.brouhaha.com> <1183098228.517915.12140@q75g2000hsh.googlegroups.com> Message-ID: <1183184091.240942.29060@w5g2000hsg.googlegroups.com> On Jun 29, 3:42 pm, Douglas Alan wrote: > Michele Simionato writes: > >> I've written plenty of Python code that relied on destructors to > >> deallocate resources, and the code always worked. > > You have been lucky: > > No I haven't been lucky -- I just know what I'm doing. > > > > > $ cat deallocating.py > > import logging > > > class C(object): > > def __init__(self): > > logging.warn('Allocating resource ...') > > > def __del__(self): > > logging.warn('De-allocating resource ...') > > print 'THIS IS NEVER REACHED!' > > > if __name__ == '__main__': > > c = C() > > > $ python deallocating.py > > WARNING:root:Allocating resource ... > > Exception exceptions.AttributeError: "'NoneType' object has no > > attribute 'warn'" in > 0xb7b9436c>> ignored > > Right. So? I understand this issue completely and I code > accordingly. What does it mean you 'code accordingly'? IMO the only clean way out of this issue is to NOT rely on the garbage collector and to manage resource deallocation explicitely, not implicitely. Actually I wrote a recipe to help with this a couple of months ago and this discussion prompted me to publish it: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/523007 But how would you solve the issue using destructors only? I am just curious, I would be happy if there was a simple and *reliable* solution, but I sort of doubt it. Hoping to be proven wrong, Michele Simionato From laurent.pointal at limsi.fr Thu Jun 14 08:45:19 2007 From: laurent.pointal at limsi.fr (Laurent Pointal) Date: Thu, 14 Jun 2007 14:45:19 +0200 Subject: Cretins. In-Reply-To: <1181787316_1279@sp12lax.superfeed.net> References: <1181753716_51257@sp12lax.superfeed.net> <873b0vv3b9.fsf@benfinney.id.au> <1181787316_1279@sp12lax.superfeed.net> Message-ID: Cousin Stanley a ?crit : >> On Thu, 14 Jun 2007 09:32:10 +1000, Ben Finney wrote: >> >>> "Dr. Pastor" writes: >>> >>>> Please do not do business with those cretins >>>> who without authorization attaching [spam footers] >>> Indeed. The cost of Usenet access should not be translated >>> to spam on messages. >> Out of curiosity, who are these cretins ? > > NewsFeeds.Com .... > > I don't do business with them either .... > > But my ISP does, apparently farming out > their news service .... > > I complained about the addition of spammed footers > by NewsFeeds.Com to my ISP several years back > but it didn't help at all .... > > My news client is configured to use my ISP's news server > but it gets spun off to NewsFeeds.Com .... > > Anything below Phoenix, Arizona in my signature > was not added by me but by NewsFeeds.Com .... As they wrote: Unlimited-Unrestricted-Secure => spammer's paradise. From aleax at mac.com Sun Jun 3 11:56:09 2007 From: aleax at mac.com (Alex Martelli) Date: Sun, 3 Jun 2007 08:56:09 -0700 Subject: Python rocks References: <4661700a$0$19261$da0feed9@news.zen.co.uk> <1hz3dq5.1ujabwt1n1e6mfN%aleax@mac.com> <46627efa$0$19248$da0feed9@news.zen.co.uk> Message-ID: <1hz4iv6.1ixzkn1oqeaatN%aleax@mac.com> Mark Carter wrote: > Alex Martelli wrote: > > Mark Carter wrote: > > > Yes, GMP is a pain to compile (especially on Mac OS X), but I believe > > > Just mentioning this in case you want to give Scheme another chance > > Thanks. I'll take a look at it. You're welcome. > I think I've decided to finish off my little in project in Python first, > though. I'd like to actually get it done (!). I may well decide to > reimplement bits in either Scheme, or I might try my hand at Forth. My > app will be small enough to permit re-writes. Excellent situation to play around with many languages, then. If your app can run on dotNET or Mono, you might also want to try Boo, a language somewhat inspired by Python but with a different approach to typing (based on type-inferencing, with an explicit 'duck' type for those rare cases in which you really _want_ a single variable to take on values of heterogeneous types during execution). > I had actually done a small 3-month Java project professionally about 7 > years ago. Can't say I was too impressed. IMO, it was too verbose, I'm > not an OO fanatic, and some immutable strings turned out to be not quite > as immutable as I expected. Nolo contendere on the verbosity and the need to stuff _every_thing into a class, but the non-immutable-strings looks like a serious bug in whatever JVM you were using at the time. Anyway, what's impressive with Java today is not the language (maybe a bit better than it was 7 years ago but still substantially Java:-), it's the array of excellent tools, libraries and frameworks grown around it; Java's standard library has arguably surpassed Python's, and third-party offerings for Java are really great. > I had a brief toy around with Java using Xcode very recently, and I was Not the best IDE for Java, btw -- Apple doesn't seem to like Java all that much any more, and it looks to me like it's backpedaling on Java's integration in MacOSX (in favor of Python, Ruby, etc). BTW, ObjectiveC is another language worth trying (though its non-Apple implementations lag far, far behind, alas). Eclipse is probably "the" Java IDE nowadays (and it's free, cross-platform, and all). > able to figure out how to download webpages easy enough (I do this to > scrape stock quotes). I felt fairly confident that I could achieve what > I wanted in Java, even though I'm fairly raw with it. I started from a > default project using Xcode, and it seemed to generate a lot of base > code. I quickly abandoned the Java idea, as I'm not gunning to be a Java > developer, and Python seems to do what I want without fuss. > > I think that's the key to Python. You can do what you want without fuss, > and it's copiously documented. Yes, excellent points. Although I have a long-time fascination with many programming languages, Python does still stand out from the crowd in enabling me to get any given app done "without fuss"!-) Alex From steve at REMOVE.THIS.cybersource.com.au Tue Jun 19 10:23:23 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Wed, 20 Jun 2007 00:23:23 +1000 Subject: Does altering a private member decouple the property's value? References: <87r6o8z5m6.fsf@benfinney.id.au> Message-ID: On Tue, 19 Jun 2007 18:54:41 +1000, Ben Finney wrote: > "Ethan Kennerly" writes: > >> I really like properties for readonly attributes, > > Python doesn't have "readonly attributes", and to attempt to use > properties for that purpose will only lead to confusion. class Parrot(object): def _plumage(self): return "Beautiful red plumage" plumage = property(_plumage) >>> parrot = Parrot() >>> parrot.plumage 'Beautiful red plumage' >>> parrot.plumage = "Ragged grey feathers" Traceback (most recent call last): File "", line 1, in AttributeError: can't set attribute It walks like a read-only attribute, it squawks like a read-only attribute, but since Python doesn't have read-only attributes, Ben must be right: using properties to implement read-only attributes will only lead to confusion. *wink* -- Steven. From josiah.carlson at sbcglobal.net Mon Jun 11 02:52:36 2007 From: josiah.carlson at sbcglobal.net (Josiah Carlson) Date: Mon, 11 Jun 2007 06:52:36 GMT Subject: memory efficient set/dictionary In-Reply-To: References: <1181485676.481109.234980@c77g2000hse.googlegroups.com> <1181492122.508277.209500@n4g2000hsb.googlegroups.com> Message-ID: Rafael Darder Calvo wrote: >> > > Please recommend a module that allows persistent set/dict storage + >> > > fast query that best fits my problem, >> > >> > What is the problem you are trying to solve? How many keys do you have? >> >> Corpus processing. There are in the order of billions to tens of >> billions keys (64bit integers). >> > I would recommend you to use a database since it meets your > requirements (off-memory, fast, persistent). The bsdddb module > (berkeley db) even gives you a dictionary like interface. > http://www.python.org/doc/lib/module-bsddb.html Standard SQL databases can work for this, but generally your recommendation of using bsddb works very well for int -> int mappings. In particular, I would suggest using a btree, if only because I have had troubles in the past with colliding keys in the bsddb.hash (and recno is just a flat file, and will attempt to create a file i*(record size) to write to record number i . As an alternative, there are many search-engine known methods for mapping int -> [int, int, ...], which can be implemented as int -> int, where the second int is a pointer to an address on disk. Looking into a few of the open source search implementations may be worthwhile. - Josiah From mcPas.De.Spam at mclaveauPas.De.Spam.com Fri Jun 1 00:46:35 2007 From: mcPas.De.Spam at mclaveauPas.De.Spam.com (Michel Claveau) Date: Fri, 01 Jun 2007 06:46:35 +0200 Subject: Embed text document in excel application using python References: <1180671570.317687.206360@j4g2000prf.googlegroups.com> Message-ID: Hi! > to embed object in excel An example come with PyWin32. This example create a toolbar inside Excel. This toolbar is write with Python. -- @-salutations Michel Claveau From mistabean at gmail.com Mon Jun 4 10:58:38 2007 From: mistabean at gmail.com (mistabean at gmail.com) Date: Mon, 04 Jun 2007 07:58:38 -0700 Subject: Embedding Python in C Message-ID: <1180969118.795850.15160@w5g2000hsg.googlegroups.com> Hello, first of all, I am a programming newbie, especially in python... Onwards to the problem, I have been having difficulty embedding a python module into my C/C++ program. (just a test program before moving on into the real thing). I have been making test runs using the codes from http://docs.python.org/ext/pure-embedding.html as a basic, but modifiying it now as a function inside my C/C++ code. Problem started when I started passing an array as an argument. The module also need an array as an argument, but somehow I can't make them to go pass the "input-error checking" of the module. The code for argument building and calling are as follows: void CallSnake(char ModName[], char FuncName[], double result[]) { ... /*Some operations to import modname, and preping FuncName, all is ok*/ ... /*Processing the result array and calling the function, problem time*/ pArgs = PyTuple_New(MAX_ELEMENT); pArg = PyList_New(1); for (i = 0; i < MAX_ELEMENT; ++i) { pValue = Py_BuildValue("d", result[i]); PyTuple_SetItem(pArgs, i, pValue); if (!(*pArgs).ob_refcnt) { Py_DECREF(pArgs); Py_DECREF(pModule); fprintf(stderr, "Cannot convert argument\n"); return; } } PyList_SetItem(pArg, 0, pArgs); pValue = PyObject_CallFunctionObjArgs(pFunc,pArg,NULL); /*Some more checking and DECREFing occurs here*/ } Error I have been getting is: Traceback if x.ndim != 1; /*x is the input array, checking if it's a 1D*/ AttributeError: 'list' object has no attribute 'ndim' I have been trying many call variations, but alas, I think the problem lies in the list building process. I have no problems calling a non- arrayed (albeit,still single) argument. Thanks in advance... From zacherates at gmail.com Tue Jun 19 16:56:08 2007 From: zacherates at gmail.com (zacherates) Date: Tue, 19 Jun 2007 20:56:08 -0000 Subject: How can I know the name of "caller" In-Reply-To: <1182285024.048003.310120@n2g2000hse.googlegroups.com> References: <1182285024.048003.310120@n2g2000hse.googlegroups.com> Message-ID: <1182286568.226409.139890@o61g2000hsh.googlegroups.com> > ...(if it is possible) how can I get, from method "called", the name > of function/method that called it (in this case "caller")? The traceback module will give you access to the call stack. >>> import traceback >>> def foo(): ... return traceback.extract_stack() ... >>> def bar(): ... return foo() ... >>> foo() [('', 1, '', None), ('', 2, 'foo', None)] >>> bar() [('', 1, '', None), ('', 2, 'bar', None), ('', 2, 'foo', None)] However, this seems like one of those it-matters-where-you-call-it- from functions from days of yore. They're generally considered to be a bad idea and was one of the patterns that prompted a rather famous essay by Dijkstra. I'd recommend exploring other design alternatives and leave this monstrosity in peace. Cheers, Aaron From martin at v.loewis.de Fri Jun 22 02:01:17 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Fri, 22 Jun 2007 08:01:17 +0200 Subject: Error while installing Python2.5.1 In-Reply-To: <1182491487.062013.92940@x35g2000prf.googlegroups.com> References: <1182413023.924197.302390@o11g2000prd.googlegroups.com> <1182479927.467515.216720@g37g2000prf.googlegroups.com> <1182491487.062013.92940@x35g2000prf.googlegroups.com> Message-ID: <467B65AD.9070108@v.loewis.de> > So how do i overcome this problem?? How do i access my distribution > repositories(if any) or installation media? You need to move to your living room. In the closet on the right side, in the second drawer from the top, you are keeping the keeping the Redhat DVDs. Open the drawer, pick the DVD cover, open it, and remove the DVD. Push the "open" button on your DVD drive, put the DVD into the tray, and put the "open" button again. When done, ask for further instructions. Regards, Martin From timr at probo.com Fri Jun 15 00:27:31 2007 From: timr at probo.com (Tim Roberts) Date: Fri, 15 Jun 2007 04:27:31 GMT Subject: Where can I suggest an enchantment for Python Zip lib? References: <46684DB8.6080900@websafe.com> <1181287080.398800.194140@q75g2000hsh.googlegroups.com> <1181726855.129860.237130@i38g2000prf.googlegroups.com> Message-ID: <185473p1a192237qsg9lkastp7137mkdtt@4ax.com> durumdara wrote: > >The problem, that: > - I want to process 100-200 MB zip files. > - I want to abort in process > - I want to know the actual position > - I want to slow the operation sometimes! > >Why I want to slow? > >The big archiving is slow operation. When it is slow, I want to >working with other apps while it is processing. > >So I want to slow the zipping with time.sleep, then the background >thread is not use the full CPU... >I can work with other apps. Surely a more intelligent (and much easier) solution would be to reduce the priority of your archiving process. Your operating system is far better equipped to share the CPU than you are. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From jstroud at mbi.ucla.edu Mon Jun 11 18:08:23 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Mon, 11 Jun 2007 15:08:23 -0700 Subject: Properties for modules? In-Reply-To: References: Message-ID: James Stroud wrote: > # moduleFoo.py > > def get_setting(self, name): > return do_whatever(name) > > def set_setting(self, name, arg): > return do_whatever_else(name, arg) > > class Foo(object): > someSetting = property(set_setting, get_setting) > > foo = Foo() someSetting = property(set_setting, get_setting) should be someSetting = property(get_setting, set_setting) James From malaclypse2 at gmail.com Fri Jun 1 13:36:39 2007 From: malaclypse2 at gmail.com (Jerry Hill) Date: Fri, 1 Jun 2007 13:36:39 -0400 Subject: c[:]() In-Reply-To: <005f01c7a471$6f4b8b30$240110ac@Muse> References: <1180504190.055427.173610@h2g2000hsg.googlegroups.com> <135tv1bjqgbmsc9@corp.supernews.com> <9qudnbFRU9QHJsLbnZ2dnUVZ_rKvnZ2d@speakeasy.net> <005f01c7a471$6f4b8b30$240110ac@Muse> Message-ID: <16651e80706011036x37e6dbd8y69b6bfcf17eda971@mail.gmail.com> On 6/1/07, Warren Stringer wrote: > > And that your > > insisting on ``c[:]()`` instead of just ``c()`` seems to indicate you want > > a change that is quite surprising. It would mean that a slice of a list > > returns an other type with the __call__ method implemented. > > I am not insisting on anything. I use ``c[:]()`` as shorthand way of saying > "c() for c in d where d is a container" The problem people are having with that is that c[:]() *already* means something in python, and it doesn't mean "c() for c in d where d is a container". In today's python c[:]() means "return a slice of object c, then call that slice". Since most container objects don't have a __call__() method, it doesn't do what you want, but it is currently valid syntax. -- Jerry From user at superhoost.com Sat Jun 16 23:01:44 2007 From: user at superhoost.com (ed) Date: Sat, 16 Jun 2007 23:01:44 -0400 Subject: Newbie question: how to get started? References: <2007061622483250073-user@superhoostcom> Message-ID: <200706162301448930-user@superhoostcom> I should also mention that I know C/C++, Perl, Javascript, the basics of mySQL, and HTML/CSS. If anyone has tried to enter python from these angles, I'd be grateful to hear from you. On 2007-06-16 22:48:32 -0400, ed said: > Hi, > > I'm interested in starting to learn python. I'm looking for any > reccomendations or advice that I can use to get started. Looking > forward to any help you can give! > > Thanks! > > -e From rustompmody at gmail.com Thu Jun 28 12:57:46 2007 From: rustompmody at gmail.com (Rustom Mody) Date: Thu, 28 Jun 2007 22:27:46 +0530 Subject: The Modernization of Emacs: terminology buffer and keybinding In-Reply-To: <86zm2ka0q5.fsf@eder.homelinux.net> References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <85zm2ufjpb.fsf@lola.goethe.zz> <1182372592.803332.288260@u2g2000hsc.googlegroups.com> <1182549094.366282.286740@m37g2000prh.googlegroups.com> <87bqf7fwmg.fsf@telesippa.clsnet.nl> <1182553682.197778.138500@g37g2000prf.googlegroups.com> <87r6nzc9nu.fsf@mail.eng.it> <1182904631.083783.170640@o61g2000hsh.googlegroups.com> <86zm2ka0q5.fsf@eder.homelinux.net> Message-ID: On 6/28/07, Andreas Eder wrote: > Twisted> In the other corner, we have just about every Unix application ever > Twisted> developed. When a user needs help, they may do such things as manually > Twisted> explore the directories where the application was installed > Twisted> (equivalent to rooting around in C:\Program Files\Appname for .hlp > Twisted> files, because F1 didn't work and there was no "help" menu, if such a > Twisted> thing ever happened on Windoze). > > Ever heard of man pages? and info? Hi Andreas: Yeah thats the problem.... there's the 40 year old man and the 20 year old info and then yelp and random stuff in /usr/doc and of course then theres google and... and... So its not that theres too little info but too much and unnecessarily similar and inconsistent. Twisted may not know what he's talking about but Ive used Unix (xenix) starting 1986 and emacs from '93 so I can say that the state of linux is not all that great. Apart from the help-itis mentioned above there are: -- distro-itis -- its almost as difficult to move from debian/ubuntu to redhat I as moving to windows -- script-itis -- why must we have perl and python and ruby (and tcl and lua and...) -- emacs-itis -- Ive mostly only used gnu-emacs but at least once I had to use xemacs for running APL. Sorry... I dont want to start another flame-war but my main point is that we geeks think that the issues are technical when the real issues are unfruitful political divisions. Sure you can fire me for my views but before you do just reflect: How different were dos and unix 20 years back and today how different is a gnome-topped linux from a win-XP and then say whether ths issues are essentially technical or political. Hi Twisted: I could give real (not made up) horror stories of my use of windows as much as you give of your use of emacs/linux -- but I dont translate my ignorance into condemnation. Rustom From phus at live.com Mon Jun 11 13:47:27 2007 From: phus at live.com (jigloo) Date: Mon, 11 Jun 2007 10:47:27 -0700 Subject: Repository - file scanner In-Reply-To: <1181331239.609059.320740@g4g2000hsf.googlegroups.com> References: <1181331239.609059.320740@g4g2000hsf.googlegroups.com> Message-ID: <1181584047.632242.71690@g37g2000prf.googlegroups.com> On 6 9 , 3 33 , HMS Surprise wrote: > Greetings, > > Could someone point my muddled head at a/the python repository. I know > that one exists but cannot find it again. In particular I am looking > for a standalone search tool that given a path searches files for a > text string. > > Thanks, > > jvh grep maybe the best choice. if you want a pure python script here it is. #!/usr/bin/python # -*- coding: utf-8 -*- # # File: grep.py # Author: phus try: import psyco psyco.full() except ImportError: print 'no mod psyco' import os, re def grep_r(rx, path): root = path dirstack = [root] while len(dirstack) > 0: dir = dirstack.pop() try: dirs = os.listdir(dir) except: print "os.listdir('%s') error: %s" % (dir, os.error) continue for name in dirs: fullname = os.path.join(dir, name) if os.path.isdir(fullname): dirstack.append(fullname) else: grep(rx, fullname) def grep(rx, file): try: f = open(file, "r") for line in f: if rx.findall(line): print file, ":", line.strip() f.close() except: print "grep error in %s" % file if __name__ == "__main__": patern = "blah blah" rx = re.compile(patern, re.I) grep_r(rx, '.') From bjourne at gmail.com Wed Jun 20 07:48:46 2007 From: bjourne at gmail.com (=?ISO-8859-1?Q?BJ=F6rn_Lindqvist?=) Date: Wed, 20 Jun 2007 13:48:46 +0200 Subject: Q: listsort and dictsort - official equivalents? In-Reply-To: References: <1182302544.4202.40.camel@delta.sgr-a.net> <740c3aec0706191757i43204155o89f4b37ed0bc68eb@mail.gmail.com> Message-ID: <740c3aec0706200448k38d19272m2e3f457138ad41de@mail.gmail.com> On 6/20/07, Gabriel Genellina wrote: > > It's not true that the sort must complete (or that the whole file must > > be read for that matter), Python has cool generators which makes the > > above possible. > > That's not possible, the input must be read completely before sorted() can > output anything. Suppose the minimum element is at the end - until you > read it, you can't output the very first sorted element. Doh! Yes of course. I always thought that sorted() returned a generator. Since Python's sort is based on merge sort, using a generator approach it should at least be theoretically possible to begin emitting the items before the sort operation completes. -- mvh Bj?rn From carsten at uniqsys.com Tue Jun 26 06:35:18 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Tue, 26 Jun 2007 06:35:18 -0400 Subject: sqlite newbie questions In-Reply-To: <9g4gi.1014$tj6.207@newsread4.news.pas.earthlink.net> References: <1182453849.251898.127630@d30g2000prg.googlegroups.com> <9g4gi.1014$tj6.207@newsread4.news.pas.earthlink.net> Message-ID: <20070626103250.M20932@uniqsys.com> On Tue, 26 Jun 2007 08:38:29 GMT, Dennis Lee Bieber wrote: > In both cases, the whole idea behind letting the adapter do > parameter substitution is that the adapter will add the appropriate > delimiters (quote marks, for the most part) needed for the data type. That's only the case if the adapter is dumb enough to stuff the parameter into the query as a literal value. Most adapters aren't that dumb. -- Carsten Haese http://informixdb.sourceforge.net From robert.kern at gmail.com Wed Jun 27 00:48:38 2007 From: robert.kern at gmail.com (Robert Kern) Date: Tue, 26 Jun 2007 23:48:38 -0500 Subject: p & br using ElementTree? In-Reply-To: <4681e39a$1@griseus.its.uu.se> References: <4681e39a$1@griseus.its.uu.se> Message-ID: Jan Danielsson wrote: > Hello all, > > This is probably a mind numbingly brain dead question.. But how do I > generate the following: > >

        Current date:
        2000-01-01

        > > ..using ElementTree? The

        element kind of needs two text blocks, > as far as I can tell? Use the .tail attribute on the br element: In [1]: from xml.etree import ElementTree as ET In [4]: p = ET.Element('p') In [5]: p.text = 'Current date:' In [6]: br = ET.SubElement(p, 'br') In [7]: br.tail = '2000-01-01' In [8]: ET.dump(p)

        Current date:
        2000-01-01

        -- 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 showell30 at yahoo.com Sat Jun 2 11:47:45 2007 From: showell30 at yahoo.com (Steve Howell) Date: Sat, 2 Jun 2007 08:47:45 -0700 (PDT) Subject: subexpressions (fourier example) In-Reply-To: <408034.91081.qm@web33506.mail.mud.yahoo.com> Message-ID: <721966.15213.qm@web33508.mail.mud.yahoo.com> --- Steve Howell wrote: > > --- Stef Mientki > wrote: > > Maybe he meant > > sin(x)^2 + cos(x)^2 > > which is well known demodulation technique if you > > create two signals 90 degrees out of phase. > > > A more realistic subexpression where you might repeat yourself: lambda t: a[0]/2 + sum(a[n]*cos(n*f*t) + b[n]*sin(n*f*t) \ for n in range(1,101)) http://en.wikipedia.org/wiki/Fourier_series Granted it's not the best style to cram it in a lambda, but I think some folks might prefer the terseness. ___________________________________________________________________________________ You snooze, you lose. Get messages ASAP with AutoCheck in the all-new Yahoo! Mail Beta. http://advision.webevents.yahoo.com/mailbeta/newmail_html.html From twisted0n3 at gmail.com Mon Jun 11 22:52:05 2007 From: twisted0n3 at gmail.com (Twisted) Date: Tue, 12 Jun 2007 02:52:05 -0000 Subject: The Concepts and Confusions of Prefix, Infix, Postfix and Fully Functional Notations In-Reply-To: <1181597817.867161.10510@h2g2000hsg.googlegroups.com> References: <1179936917.652372.24780@q69g2000hsb.googlegroups.com> <1180508453.226022.44230@q19g2000prn.googlegroups.com> <1181335574.107472.229370@x35g2000prf.googlegroups.com> <1181358616.792797.97720@k79g2000hse.googlegroups.com> <1181414625.121073.203940@g4g2000hsf.googlegroups.com> <0uHai.176367$nh4.13819@newsfe20.lga> <1181448558.120521.63250@g4g2000hsf.googlegroups.com> <0G_ai.1970$xg4.809@trnddc08> <1181525392.369255.138460@h2g2000hsg.googlegroups.com> <1181545345.788665.191690@q66g2000hsg.googlegroups.com> <1181597817.867161.10510@h2g2000hsg.googlegroups.com> Message-ID: <1181616725.678833.104690@n15g2000prd.googlegroups.com> On Jun 11, 5:36 pm, Tim Bradshaw wrote: > I think it's just obvious that this is the case. What would *stop* > you writing maintainable Perl? For starters, the fact that there are about six zillion obscure operators represented by punctuation marks, instead of a dozen or so. More generally, the fact that it comes out looking like modem barf, and modem barf is unmaintainable. ;) From saint at spammer.impiccati.it Tue Jun 26 06:17:20 2007 From: saint at spammer.impiccati.it (Gian Uberto Lauri) Date: Tue, 26 Jun 2007 12:17:20 +0200 Subject: The Modernization of Emacs: terminology buffer and keybinding References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182272495.990807.99110@a26g2000pre.googlegroups.com> <87tzt3ihev.fsf@kobe.laptop> <1182370216.961241.6960@n60g2000hse.googlegroups.com> <85zm2ufjpb.fsf@lola.goethe.zz> <1182372592.803332.288260@u2g2000hsc.googlegroups.com> <1182549094.366282.286740@m37g2000prh.googlegroups.com> <877iprhos9.fsf@kobe.laptop> <1182843872.488493.153700@m36g2000hse.googlegroups.com> Message-ID: <87myync95b.fsf@mail.eng.it> >>>>> Long count = 12.19.14.7.15; tzolkin = 1 Men; haab = 3 Tzec. >>>>> I get words from the Allmighty Great Gnus that >>>>> "T" == Twisted writes: T> And the myth of the bicycle being easy to learn persists. Did you T> know that kids learn better than adults do? Why do kids pick up at T> least one language without any conscious effort, while adults T> trying to learn one more often struggle in night school? Mostly because they block themselves with strange fears and due bad teaching, the "fear" of a test, the lack of fun, the "constriction", all block adults learning new language. Pick an over 30, overloaded with (often) frustrating work, and give her an university level course in languages with grammars and/or alphabets completly different from those she uses (yesss, I am thinking of a woman, my wife...) like Arab (alphabet and some grammar) and Turkish (its grammar sound lispish to my ears), and she'll go ahead without "fatigue" and with flying colours. Children pick up other language without any conscious effort because either they learn it by using with parents, relatives and friends or they are involved in a game-like style of learning. Why else hacker prize fun this much ? :) :) T> I know people who find all kinds of vehicles easy to learn but T> never mastered a bicycle (despite trying). People, plural, as in T> more than one of them. Again, fear, or maybe, some malfunction in the balancing organs. But fear mainly. You do not see what keeps a bike upright and running, you have to trust that you can. You can walk on a 4 inch wide stripe on a floor without problems, but when it is a 4 inch wide bar some feet over the floor... -- /\ ___ /___/\_|_|\_|__|___Gian Uberto Lauri_____ //--\| | \| | Integralista GNUslamico \/ e coltivatore diretto di Software A Cesare avrei detto di scrivermi a fnvag at rat.vg From thomas at jollans.com Thu Jun 28 08:56:45 2007 From: thomas at jollans.com (Thomas Jollans) Date: Thu, 28 Jun 2007 14:56:45 +0200 Subject: problem with hack using multiple inheritance for plugins In-Reply-To: <1183033365.183481.143310@n60g2000hse.googlegroups.com> References: <1183026288.857294.91620@q69g2000hsb.googlegroups.com> <1183028051.940679.145680@q69g2000hsb.googlegroups.com> <46839f4c$0$22380$426a74cc@news.free.fr> <1183033365.183481.143310@n60g2000hse.googlegroups.com> Message-ID: massimo s. wrote: > On 28 Giu, 13:45, Bruno Desthuilliers 42.desthuilli... at wtf.websiteburo.oops.com> wrote: >> massimo s. a ?crit : >> >>>> At this point, it seems too much a deep object-oriented hell to be >>>> able to dig it myself. Would you help me getting some cue on the >>>> problem? >>> Update. Now I know that: >>> - every sane Python class should return after >>> type(self) >> Certainly not, unless you're using a pretty old Python version. >> 'instance' type means old-style classes - the legacy Python object >> model, replaced some years ago with a *much* better one ('new-style' >> classes). IIRC, this (now dying) legacy object model should disappear >> with Py3K. > > Oops. That's probably the problem. > > I always followed the class syntax found in Section 9 of the tutorial, > and Python code I've seen uses the same syntax. > > Where can I find the syntax of new-style classes? syntax is the same. A class is new-style if it inherits from at least one new-style class and zero or more old-style classes. If you're not really inheriting, inherit from object, which is a new-style class that does nothing. see http://wiki.python.org/moin/NewClassVsClassicClass Thomas -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 260 bytes Desc: OpenPGP digital signature URL: From ErendisAldarion at gmail.com Mon Jun 25 00:01:37 2007 From: ErendisAldarion at gmail.com (Aldarion) Date: Mon, 25 Jun 2007 04:01:37 -0000 Subject: how to sorted by summed itemgetter(x) In-Reply-To: <7xwsxs96gg.fsf@ruckus.brouhaha.com> References: <1182733105.118722.86390@e16g2000pri.googlegroups.com> <7xwsxs96gg.fsf@ruckus.brouhaha.com> Message-ID: <1182744097.603103.130230@d30g2000prg.googlegroups.com> Thanks for the reply,I got it. On 6 25 , 9 19 , Paul Rubin wrote: > Aldarion writes: > > how to sorted by summed itemgetter(1)? > > maybe sorted(items,key = lambda x:sum(x[1])) > > can't itemgetter be used here? > > You really want function composition, e.g. > > sorted(items, key=sum*itemgetter(1)) > > where * is a composition operator (doesn't exist in Python). > > You could write: > > def compose(f,g): > return lambda *a,**k: f(g(*a,**k)) > > and then use > > sorted(items, key=compose(sum,itemgetter(1))) > > or spell it out inline: > > sorted(items, key=lambda x: sum(itemgetter(1)(x))) > > I'd probably do something like: > > snd = itemgetter(1) # I use this all the time > sorted(items, key=lambda x: sum(snd(x))) From LJones at securetrading.com Tue Jun 5 05:38:38 2007 From: LJones at securetrading.com (Lee Jones) Date: Tue, 5 Jun 2007 10:38:38 +0100 Subject: url encode Message-ID: Hello, I am trying to urlencode a string. In python the only thing I can see is the urllib.urlencode(). But this takes a dictionary, and returns "key=value", which is not what I want. I only want to url-encode a string. Does any one know how to do this in python Thanks Lee Lee Jones, Software Developer SecureTrading Ltd European Operations Centre Parc Menai Bangor Gwynedd LL57 4BL T: 01248 672 028 F: 01248 672 099 www.securetrading.com -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: image001.gif Type: image/gif Size: 3164 bytes Desc: image001.gif URL: From robert.kern at gmail.com Mon Jun 25 21:00:08 2007 From: robert.kern at gmail.com (Robert Kern) Date: Mon, 25 Jun 2007 20:00:08 -0500 Subject: distutils/setuptools de-installation? In-Reply-To: <87y7i7zhdy.fsf@grogan.peloton> References: <87y7i7zhdy.fsf@grogan.peloton> Message-ID: David Abrahams wrote: > I've been googling myself silly trying to find an answer to this; my > system's package manager is broken until I can solve it. > > I installed some packages using > > python setup.py install > > and I need to remove them. For some packages, > > python setup.py develop --uninstall > > is good enough, because it cleans the package out of Python's egg > database (wherever that is), It's just your site-packages/easy-install.pth file. The idiomatic (but admittedly roundabout) way of doing this without having the source is to use easy_install --multi-version mypackage That accomplishes the same thing: to remove the egg from the list of active eggs in easy-install.pth but not removing the egg itself. > although it doesn't delete the eggs > themselves. > > For other packages, PyPgSQL among them, the above command isn't even > recognized. This _has_ to be a FAQ, doesn't it? Please help! distutils itself has no notion of uninstallation. You need to figure out what files the package installed and delete them yourself. -- 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 danb_83 at yahoo.com Fri Jun 8 00:08:06 2007 From: danb_83 at yahoo.com (Dan Bishop) Date: Thu, 07 Jun 2007 21:08:06 -0700 Subject: Integer division In-Reply-To: References: <1181207216.890336.99990@r19g2000prf.googlegroups.com> Message-ID: <1181275686.205607.53200@q69g2000hsb.googlegroups.com> On Jun 7, 8:30 pm, Some Other Guy wrote: > jm.sur... at no.spam.gmail.com wrote: > > Hello all, > > I have two integers and I want to divide one by another, and want to > > get an integer result which is the higher side whenever the result is > > a fraction. > > 3/2 => 1 # Usual behavior > > some_func(3, 2) => 2 # Wanted > > Are you trying to accomplish int((a/b) + 0.5), but cheaply? > > If so, consider that that is the same as (a/b) + (b/2b), > which is (2a/2b) + (b/2b), which is (2a+b)/2b. > > Since this just involves doubling you can avoid multiplying altogether > and just use this: > > def rounddiv(a,b): > return int((a+a+b)/(b+b)) > > That's 3 integer adds and 1 integer divide. The int() cast is just > there is case somebody passes in floats for a or b; if you know you're > only going to have integer arguments you don't need it. The // operator was added to the language for a reason. I'm surprised at how few Pythonistas are using it six years later. From bj_666 at gmx.net Sun Jun 10 01:57:13 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Sun, 10 Jun 2007 07:57:13 +0200 Subject: Third-party libs in version control References: <466b6f7f$0$70264$c89e4b0f@news.dwx.com> Message-ID: In <466b6f7f$0$70264$c89e4b0f at news.dwx.com>, Marcus wrote: > I'm new to developing large subversion-controlled projects. This one > will involve a few third-party libraries like wxWidgets, and perhaps > Twisted. Ordinarily you could just install these into your system and > they'll end up globally (in Python's Lib/site-packages directory). Is it > proper practice to instead install the libraries into a separate [vendor > branch] of the repository and reference that instead? > > I've read about vendor branches, and I'm under the impression that > you're supposed to do that /instead/ of installing the libraries > globally into Python's subdirectories... is that correct? I think that's not the "normal" way. Vendor branches are useful if you want *exactly* one version if a third party product. That might be important if their API is a rapidly moving target or newer versions changed much, or have critical bugs. Another use case is modifying the external sources. Then it's of course a good idea to put the vanilla sources under version control to be able to merge updates from the vendor into the modified branch. Do you ship all that third party stuff with your project? Last but not least I'm using subversion nearly exclusively for source code IOW not for compiled code. Checking in an installed wxWidgets or wxPython alongside some source code "feels" a little strange to me. Pure Python code might be okay but if there are external dependencies one can't checkout on another computer and expect everything to work there. Ciao, Marc 'BlackJack' Rintsch From fred at adventistcare.org Thu Jun 28 09:02:37 2007 From: fred at adventistcare.org (Sells, Fred) Date: Thu, 28 Jun 2007 09:02:37 -0400 Subject: Evolution of a pythonistas! Message-ID: concur 100%. You can breeze through the fist half of the online tutorial in a about 2 cups of coffee but you don't know what you don't know until you try to do something real. Even with 20 years of working with Python, I find goodies in the cookbook for each new project. Get a python aware editor. I use Eclipse+PyDev for big jobs, but still use Emacs with python-mode for quickies. Although I would never recommend Emacs to someone who does not already know how to use it. IDLE is ok, for beginning but I find it distracting. Eclipse can be intimidating at first, but if you go through the PyDev howto's, You'll learn all you need. Forget about typing stuff interactively, It is better to work in a file so you can see your work evolve. Finally, I have never had a project in the last 5 years that someone hasn't already done. Google is your friend. Many of the hits are misleading or too much code to fit what I need, but I often find a snippet that I can use. > -----Original Message----- > From: python-list-bounces+frsells=adventistcare.org at python.org > [mailto:python-list-bounces+frsells=adventistcare.org at python.org]On > Behalf Of BartlebyScrivener > Sent: Thursday, June 28, 2007 8:18 AM > To: python-list at python.org > Subject: Re: Evolution of a pythonistas! > > > On Jun 28, 6:46 am, swordofrue wrote: > > Hello everyone, > > > > How does a pythonistas evolve? > > > > Get the Python Cookbook 2d, pick a useful looking project, and adapt > it for your own needs. Learn by doing. Some people enjoy just doing > the tutorials with the interpreter open, testing code line by line. > That works, too. But often the most gratifying is to solve a problem, > or make a useful script that does something you need, which saves you > time--time you can invest in learning more Python. :) > > rd > > -- > http://mail.python.org/mailman/listinfo/python-list > From doug at alum.mit.edu Fri Jun 22 19:51:28 2007 From: doug at alum.mit.edu (Douglas Alan) Date: Fri, 22 Jun 2007 19:51:28 -0400 Subject: Python's "only one way to do it" philosophy isn't good? References: <1181368143.874341.273140@r19g2000prf.googlegroups.com> <7x3b0nmkk6.fsf@ruckus.brouhaha.com> Message-ID: "Terry Reedy" writes: > "Douglas Alan" wrote in message > | "Terry Reedy" writes: > | > I think this points to where Sussman went wrong in his footnote > | > and Alan in his defense thereof. Flexibility of function -- > | > being able to do many different things -- is quite different > | > from flexibility of syntax > | I think you are setting up a false dichotomy. > I think this denial of reality is your way of avoiding admitting, perhaps > to yourself, that your god Sussman made a mistake. Sussman isn't my god -- Kate Bush is. Just because I'm right and you're wrong, doesn't mean that I'm in denial. It is you who are in denial if you believe that syntax is unimportant, as long as one is provided the required functionality. In fact, that's stereotypical Computer Science denial. Computer Science academics will typically state as a truism that semantics are what is important and syntax is just a boring trifle in comparison. But time and time again, you'll see programming languages succeed or fail more on their syntax than on their semantics. And issues of syntax is often where you see the most inflamed debates. Just look at all the flames one used to hear about Python using whitespace significantly. Or all the flames that one will still hear about Lisp using a lot of parentheses. You seem oblivious to the fact that one of the huge benefits of Python is its elegant and readable syntax. The problem with not having a "flexible syntax", is that a programming language can't provide off-the-shelf an elegant syntax for all functionality that will ever be needed. Eventually programmers find themselves in need of new elegant functionality, but without a corresponding elegant syntax to go along with the new functionality, the result is code that does not look elegant and is therefore difficult to read and thus maintain. Consequently, "flexibility of function" is often moot without "flexibility of syntax". I don't know how I can make it any clearer than this. I'm sorry if you don't understand what I am saying, but just because you don't understand, or if you do, that you don't agree, doesn't mean that I don't have a reasoned and reasonable point of view. > | One that is related to the false unification that annoying people > | used to always make when they would perpetually argue that it > | wasn't important which programming language you programmed in, as > | they are all Turing equivalent anyway. Well, I sure as hell don't > | want to write all my programs for a Turning machine, and a Turing > | machine is certainly Turing equivalent! > Diversionary crap unrelated to the previous discussion. Take the issue up with Paul Graham. Since making a fortune developing software in Lisp (making heavy use of macros), he now has much more free time to write essays defending the truth than I do: http://www.paulgraham.com/avg.html |>oug From rahulnag22 at yahoo.com Fri Jun 8 12:48:34 2007 From: rahulnag22 at yahoo.com (rahulnag22 at yahoo.com) Date: Fri, 08 Jun 2007 09:48:34 -0700 Subject: Tkinter - Force toplevel window to stay on top of Tk() window Message-ID: <1181321314.023016.185650@i38g2000prf.googlegroups.com> Hi, I have a Tk() window "base_win = Tk()" with multiple frames on it having a combination of widgets. If I click on say a button widget which launches a new top level window "new_win = TopLevel()", I was looking for a way for this "new_win" to always stay on top of "base_win" till I close "new_win", as a result also not allowing any selections to be made in the "base_win" . Thanks Rahul From steve at REMOVE.THIS.cybersource.com.au Sat Jun 2 21:24:57 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sun, 03 Jun 2007 11:24:57 +1000 Subject: c[:]() References: <1180504190.055427.173610@h2g2000hsg.googlegroups.com> <135tv1bjqgbmsc9@corp.supernews.com> <9qudnbFRU9QHJsLbnZ2dnUVZ_rKvnZ2d@speakeasy.net> <005f01c7a471$6f4b8b30$240110ac@Muse> <6faf39c90706012146l551dfe60o6358f48dd5127505@mail.gmail.com> Message-ID: On Sat, 02 Jun 2007 11:25:04 -0700, Warren Stringer wrote: > Since `a()` translates to `a() for a in b` then the error would be the exact > same `TypeError: 'str' object is not callable` Not in any language called Python I know of. Supposedly 28 years programming experience, and you can't even see the _serious_ problems with "a()" --> "a() for a in b". Well, that explains a lot about the lousy state of so many programming projects. What's b? Given "a()", how does the compiler identify which b is the one to look at? How does the recursive reference to a() terminate? [snip] > For now, I am out of here! Please don't come back until you have a clue. -- Steven. From sergio at sergiomb.no-ip.org Tue Jun 26 16:26:06 2007 From: sergio at sergiomb.no-ip.org (sergio) Date: Tue, 26 Jun 2007 21:26:06 +0100 Subject: urllib interpretation of URL with ".." References: <467cc85f$0$3039$9b622d9e@news.freenet.de> Message-ID: <4681765c$0$424$a729d347@news.telepac.pt> John Nagle wrote: > In Python, of course, "urlparse.urlparse", which is > the main function used to disassemble a URL, has no idea whether it's > being used by a client or a server, so it, reasonably enough, takes option > 1. >>> import urlparse >>> base="http://somesite.com/level1/" >>> path="../page.html" >>> urlparse.urljoin(base,path) 'http://somesite.com/page.html' >>> base="http://somesite.com/" >>> urlparse.urljoin(base,path) 'http://somesite.com/../page.html' For me this is a bug and is very annoying because I can't simply trip ../ from path because base could have a level. -- Best regards, -- S?rgio M. B. From papalagi.pakeha at gmail.com Sat Jun 16 06:46:51 2007 From: papalagi.pakeha at gmail.com (Papalagi Pakeha) Date: Sat, 16 Jun 2007 22:46:51 +1200 Subject: Installing manpage in setup.py Message-ID: <343d1bca0706160346t6f04f401ia8bf83313121196d@mail.gmail.com> Hi all, how can I tell setup() in distutils' setup.py to install manual pages of my program? I.e. prgclient.1 to /.../man/man1 and prgdaemon.8 to /.../man/man8? The problem is that those /.../ directories may be different on every system, for instance /usr/share/man on OpenSUSE and /usr/man on Solaris. Is there a way to automatically put the manpages to their proper directories? Thanks PaPa From gagsl-py2 at yahoo.com.ar Mon Jun 11 05:12:51 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 11 Jun 2007 06:12:51 -0300 Subject: Regular Text References: <1181552035.275951.68010@g4g2000hsf.googlegroups.com> Message-ID: En Mon, 11 Jun 2007 05:53:55 -0300, escribi?: > Hallo, > I am new to python. > I wrote a program to retrieve the filepath. eg. C:\Programs\Python\ > and write it in a text file > It works fine until the path contains \t or \n. eg. C:\Programs\Python > \new\. > Because of the regular text format, I didn't get what I want in the > text file. > > I tried to change the separator from \ to / but python only gives C:/ > Programs/Python\new/. > > How should I do to make sure that the program writes the correct path > in the text file? In your code, you should use string literals like my_path = r"C:\Programs\Python\new" my_path = "C:\\Programs\\Python\\new" But you said "a program to retrieve the filepath" - and I understand that you dont have a string literal, and you compute it somehow. Escape characters should not be a problem then. Have you verified the contents of the text file? With notepad? -- Gabriel Genellina From steven.bethard at gmail.com Fri Jun 1 15:02:54 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Fri, 01 Jun 2007 13:02:54 -0600 Subject: subexpressions In-Reply-To: References: Message-ID: <1NOdnc2sK4_C8P3bnZ2dnUVZ_gidnZ2d@comcast.com> Sergey Dorofeev wrote: > Please help, is there way to use sub-expressions in lambda? > For example, if I want to calculate sin(x^2)+cos(x^2) I must code: > lambda x: sin(x*x)+cos(x*x) [and later] > This code is needed once in a map, Peter Otten wrote: > Perhaps you like [sin(y)+cos(y) for y in (x*x for x in items)] then. Just wanted to emphasize this suggestion so that it doesn't get lost in the flood of lambda recommendations. If your code really looks like:: map(lambda x: sin(x * x) + cos(x * x), items) you should be using a list comprehension instead. Using map() here is not only more obscure and more verbose, but slower than:: [sin(x * x) + cos(x * x) for x in items] From there, it's a simple nested generator comprehension to pull out the subexpression: [sin(y) + cos(y) for y in (x * x for x in items)] If you aren't yet familiar with list and generator comprehensions, you should take a few minutes to look at some of your uses of map() and filter and see if you can simplify them using comprehensions instead. STeVe From adam at lumanation.com Sat Jun 16 06:27:46 2007 From: adam at lumanation.com (Adam Teale) Date: Sat, 16 Jun 2007 03:27:46 -0700 Subject: retrieve / find out an image's dimensions Message-ID: <1181989666.584877.308920@i13g2000prf.googlegroups.com> hey guys Is there a builtin/standard install method in python for retrieving or finding out an image's dimensions? A quick google found me this: http://www.pythonware.com/library/pil/handbook/introduction.htm but it looks like it is something I will need to install - I'd like to be able to pass my script around to people without them needing any additional modules Any help would be fantastic! Cheers Adam python 2.3.5 osx 10.4.9 From steve at laniels.org Thu Jun 21 09:49:57 2007 From: steve at laniels.org (Stephen R Laniel) Date: Thu, 21 Jun 2007 09:49:57 -0400 Subject: strip() 2.4.4 In-Reply-To: <467A802B.8050702@gmail.com> References: <1182432181.050589.5800@n2g2000hse.googlegroups.com> <20070621133006.GQ6145@slaniel-laptop.itasoftware.com> <467A802B.8050702@gmail.com> Message-ID: <20070621134957.GX6145@slaniel-laptop.itasoftware.com> On Thu, Jun 21, 2007 at 01:42:03PM +0000, linuxprog wrote: > that should work for you ? I reproduced the original poster's problem by adding one extra space after the final "'" on each line. I'd vote that that's the problem. -- Stephen R. Laniel steve at laniels.org Cell: +(617) 308-5571 http://laniels.org/ PGP key: http://laniels.org/slaniel.key From vbr at email.cz Wed Jun 27 13:26:07 2007 From: vbr at email.cz (vbr at email.cz) Date: Wed, 27 Jun 2007 19:26:07 +0200 (CEST) Subject: =?us-ascii?Q?Re=3A=20Reversing=20a=20string?= In-Reply-To: <20070627170755.GG30401@lass.lfod.us> Message-ID: <11393.13168-31849-361047026-1182965167@email.cz> > ------------ P?vodn? zpr?va ------------ > Od: Will Maier > P?edm?t: Re: Reversing a string > Datum: 27.6.2007 19:08:40 > ---------------------------------------- > On Wed, Jun 27, 2007 at 12:53:36PM -0400, Scott wrote: > > So how on earth would be the best way to: Write a function that > > takes a string as an argument and outputs the letters backward, > > one per line. > > >>> def rev(forward): > ... backward = list(forward) > ... backward.reverse() > ... return ''.join(backward) > >>> rev("spam") > 'maps' > > list.reverse() changes the list in-place. Instead of iterating over > the items in the string sequence, you can just convert the input > string outright. > > -- > > [Will Maier]-----------------[willmaier at ml1.net|http://www.lfod.us/] > -- > http://mail.python.org/mailman/listinfo/python-list > > > Or using string slice with negative step? >>> "spam"[::-1] 'maps' or one letter per line: >>> print "\n".join("spam"[::-1]) m a p s Greetings, Vlastimil Brom From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Sun Jun 24 07:12:16 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Sun, 24 Jun 2007 13:12:16 +0200 Subject: Collections of non-arbitrary objects ? References: <1182449993.223262.229500@z28g2000prd.googlegroups.com> <87k5twx4hf.fsf@benfinney.id.au> <1182559502.069773.321620@i38g2000prf.googlegroups.com> <87wsxvrzsj.fsf@benfinney.id.au> <1182620734.940718.196520@e16g2000pri.googlegroups.com> <1182625562.657089.66150@p77g2000hsh.googlegroups.com> Message-ID: <5e71sgF36o7avU1@mid.individual.net> 7stud wrote: > On Jun 23, 11:45 am, walterbyrd wrote: >> Suppose you are sequentially processing a list with a routine >> that expects every item to be of a certain type. Something in the >> list that doesn't conform to the type could give you unexpected >> results, maybe crash your application. >> > > if hasattr(elmt, some_func): > elmt.some_func() Personally, I prefer try: elmt.some_func() except AttributeError: # do stuff Regards, Bj?rn -- BOFH excuse #130: new management From paddy3118 at googlemail.com Tue Jun 12 17:35:52 2007 From: paddy3118 at googlemail.com (Paddy) Date: Tue, 12 Jun 2007 21:35:52 -0000 Subject: for ... else ? In-Reply-To: References: <1181622331.955264.31610@i38g2000prf.googlegroups.com> <1181640889.439145.60020@g37g2000prf.googlegroups.com> <4866bea60706120641j2fa1fb09r89f937d75f5bd1b6@mail.gmail.com> Message-ID: <1181684152.300967.319390@i13g2000prf.googlegroups.com> On Jun 12, 7:55 pm, "Gabriel Genellina" wrote: > En Tue, 12 Jun 2007 10:41:28 -0300, Chris Mellon > escribi?: > > > > > On 6/12/07, Gabriel Genellina wrote: > >> for x in iterable: > >> do something with x > >> else: > >> do something when there are no more x > > >> You can think the above as: > > >> while there are still values in iterable: > >> do something with the next value > >> else: > >> do something when there are no more items > > > This is a good way of phrasing it and I hope I can remember it, > > because for..else always gives me trouble. To me, "else" indicates the > > negative condition and I intuitively associate it with executing the > > loop early, not normal exit. Personally, I think a different keyword > > (maybe "after"?) would have done a better job of clarifying this. > > Yes, maybe, but it's hard to find a keyword equally applicable to "for" > and "while" and creating two new keywords for essencially the same thing > would be too much... Anyway it's too late to be changed now. > > -- > Gabriel Genellina Hmmm, Would replacing the word 'else' with 'then' read better? The implied meaning is if the loop terminates normally *then* also do this block. - Paddy. From nick at craig-wood.com Sun Jun 3 15:30:05 2007 From: nick at craig-wood.com (Nick Craig-Wood) Date: Sun, 03 Jun 2007 14:30:05 -0500 Subject: Detecting an active exception References: Message-ID: NeBlackCat wrote: > I've now also looked at this from a traceback and stack frame walking > perspective as well and it seems impossible, ie. it see,s impossible to > create a function AmIHandlingAnException() which would behave as follows: > > try: > a=a+1 > except: > pass > > try: > AmIHandlingAnException() # returns FALSE > b = b + 1 > except: > AmIHandlingAnException() # returns TRUE > try: > AmIHandlingAnException() # returns TRUE > except: > pass > > AmIHandlingAnException() # returns FALSE > > The only way I can see to do it is to use something like the 'inspect' > module to walk up the stack and, for each frame, walk lines of code > backwards to determine whether or not you're in an except: block. Of > course that would be horribly inefficient. > > I'm rather stunned by this (this was the 'easy' bit that I left to > last!). Why don't you tell us what you are actually trying to achieve and we can see if we can come up with a more pythonic solution? The fact that you are running into limits of the language like this as a new python programmer probably means you aren't thinking in python yet. -- Nick Craig-Wood -- http://www.craig-wood.com/nick From sbellon at sbellon.de Fri Jun 29 17:05:55 2007 From: sbellon at sbellon.de (Stefan Bellon) Date: Fri, 29 Jun 2007 23:05:55 +0200 Subject: Hooking __import__ when embedding the interpreter In-Reply-To: <20070629115713.5d0d8dd8@cube.tz.axivion.com> References: <20070629115713.5d0d8dd8@cube.tz.axivion.com> Message-ID: <20070629230555.4c135b5f@cube.tz.axivion.com> I think I solved all my three questions for myself now ... On Fri, 29 Jun, Stefan Bellon wrote: > 1) The above code seems to work ok when using the "import" statement, > but it does not when using the dynamic __import__ function. If > using it that way, I get: > > >>> sys=__import__("sys") > Traceback (most recent call last): > File "", line 1, in ? > SystemError: new style getargs format but argument is not a tuple > > What am I missing in order to get the __import__ function covered > as well? static PyMethodDef import_hook[] = { {"__import__", __import__, METH_VARARGS, import_doc}, {NULL, NULL} }; Adding the METH_VARARGS solved this, now the __import__ function is intercepted as well. > 2) Another point is, that I need to check _from where_ the module is > imported. In fact, this is going to become part of the consistency > check condition. How can I find out from which module the import > was initiated? > > > 3) My final point is related to 2) ... if I get to the module object, > then how do I get at the source file name of that? I noticed that > when a .pyc is available, then this is preferred. I'd like to get > at the .py file itself. Is this available or do I just have to > strip off the trailing 'c' (or 'o'?) if present (seems hacky to > me). By not focusing on the module but using sys._getframe().f_code.co_filename I solved point 2 and 3 in one go. I'm still looking forward to comments regarding this issue. ;-) -- Stefan Bellon From bbxx789_05ss at yahoo.com Fri Jun 15 19:42:40 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: Fri, 15 Jun 2007 16:42:40 -0700 Subject: Want to learn Python In-Reply-To: References: <1181907696.878873.214760@i13g2000prf.googlegroups.com> Message-ID: <1181950960.793735.304570@c77g2000hse.googlegroups.com> On Jun 15, 11:59 am, "Evan Klitzke" wrote: > On 6/15/07, Amol wrote: > > > Hi, I want to learn Python in less than a month which resources should > > I use. I prefer to read books . Please give me a list of *recognized* > > resources. Thank You all > > The Apress "Beginning Python" book is the one that I recommend to > people who want to learn the language. I started off with the O'Reilly > book, and that book went too slow and didn't cover as many topic as > the Apress book. If you are an experienced programmer and use the > Apress book, you'll get a pretty good grasp of the language within a > week or so. > > -- > Evan Klitzke I am of the opposite opinion: I recommend that people get any book but "Beginning Python: Novice to Professional". In my opinion, that book is horribly written, the examples are terrible, some subjects are only covered in passing so the info is too parse to be of any use, and there are no problems at the end of the chapters to work on. I think a beginner might be fooled into thinking Beginning Python is a good book because they won't know how many holes their knowledge of python is riddled with, and since there are no problems to work on, they may not even realize how little they learned. I think an experienced programmer would spot all the blunders in the book straight away. As a result, I often use "Learning Python" as a reference to fill in all the missing material in Beginning Python, and I wish I had purchased it initially. It also has problems to work on at the end of each section. One problem with Learning Python is that it needs a new edition to catch up with the changes that have occurred in the language, but it still seems like a much, much better book than Beginning Python. The reference book "Python in a Nutshell" is excellent, however its index is so bad I hesitate to recommend it. A reference book should have a thorough index--you shouldn't have to hunt through the chapters trying to find the particular topic you are interested in. From bruno.42.desthuilliers at wtf.websiteburo.oops.com Fri Jun 8 03:59:56 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Fri, 08 Jun 2007 09:59:56 +0200 Subject: *Naming Conventions* In-Reply-To: References: <1180909218.939713.112010@q69g2000hsb.googlegroups.com> <1180990280.960271.235550@h2g2000hsg.googlegroups.com> <466699e9$0$2308$426a74cc@news.free.fr> Message-ID: <46690c7c$0$32006$426a34cc@news.free.fr> Neil Cerutti a ?crit : > On 2007-06-06, Bruno Desthuilliers > wrote: >> Neil Cerutti a ?crit : >>> On 2007-06-04, Michael Hoffman wrote: >>>> Wildemar Wildenburger wrote: >>>> I agree with Bruno that i and j should be used only for >>>> indices, but I'm usually less terse than that. >>> I find i and j preferable to overly generic terms like "item." >> Since 'i' and 'j' are canonically loop indices, I find it >> totally confusing to use them to name the iteration variable - >> which is not an index. >> >> At least, 'item' suggests that it's an object, and a part of >> the collection - not just an index you'll have to use to >> subscript the container. Also, and as far as I'm concerned, I >> certainly dont find 'i' and 'j' *less* generic than 'item' !-) > > Thanks, I didn't say clearly what I meant. > > Certainly i and j are just as generic, but they have the > advantage over 'item' of being more terse. I'm not sure this is really an "advantage" here. From deets at nospam.web.de Tue Jun 5 08:31:24 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 05 Jun 2007 14:31:24 +0200 Subject: *args and **kwargs References: <1181046478.824231.117300@q75g2000hsh.googlegroups.com> Message-ID: <5cl3csF2r2kvkU1@mid.uni-berlin.de> JonathanB wrote: > Ok, this is probably definitely a newbie question, but I have looked > all over the Python library reference material and tutorials which I > can find online and I cannot find a clear definition of what these are > and more importantly how to use them. From what I can tell from their > use in the examples I've seen, they are for passing a variable number > of arguments to a function (which I need to do in a program I am > working on). But how do you use them? Is there a fixed order in which > the arguments within *arg or **kwarg should be passed or will be > called within a function? I realize this probably involves a long- > winded answer to a very simple and common programming problem, so if > someone has a link to TFM, I'll gladly go RTFM. I just can't find it. That's because it's in the language reference, not in the library reference. http://docs.python.org/ref/calls.html Diez From montyphyton at gmail.com Mon Jun 4 08:06:04 2007 From: montyphyton at gmail.com (montyphyton at gmail.com) Date: Mon, 04 Jun 2007 05:06:04 -0700 Subject: Python, Dutch, English, Chinese, Japanese, etc. In-Reply-To: <4663fe2a$0$5068$ba4acef3@news.orange.fr> References: <4663fe2a$0$5068$ba4acef3@news.orange.fr> Message-ID: <1180958764.491893.130160@h2g2000hsg.googlegroups.com> M?ta-MCI je napisao/la: > Et le klingon ? > > Please, don't forget klingons > SVP, n'oubliez pas les klingons > > ;o) je pense que le klingon utilise les mems lettres comme l'anglais From showell30 at yahoo.com Thu Jun 14 06:14:53 2007 From: showell30 at yahoo.com (Steve Howell) Date: Thu, 14 Jun 2007 03:14:53 -0700 (PDT) Subject: SimplePrograms challenge In-Reply-To: Message-ID: <601771.65481.qm@web33506.mail.mud.yahoo.com> --- Steven Bethard wrote: unit.text) > > I posted a slight variant of this, trimmed down a > bit to 21 lines. > Thanks, I think this will be a very useful example. ____________________________________________________________________________________ Pinpoint customers who are looking for what you sell. http://searchmarketing.yahoo.com/ From Ognjen at mailshack.com Fri Jun 22 11:33:52 2007 From: Ognjen at mailshack.com (Ognjen Bezanov) Date: Fri, 22 Jun 2007 16:33:52 +0100 Subject: Changing the names of python keywords In-Reply-To: <1182519691.290422.134390@n60g2000hse.googlegroups.com> References: <1182519691.290422.134390@n60g2000hse.googlegroups.com> Message-ID: <467BEBE0.8060107@mailshack.com> vedrandekovic at v-programs.com escribi?: > Hello again, > > Thanks for everything previously, I was change the grammar and Lib/ > keyword.py, now > Python recognize "koristiti" as a keyword, but that is not enough: > > when I write in my python shell: > >>>> koristiti os # "koristiti" get keyword "color", but I get error: > > File "", line 1 > koristi os > ^ > SyntaxError: invalid syntax > > and now, when I write: > >>>> import os # "import" don't get keyword "color" but still working > > > > > Please help me, thanks!!!!!!!!!!!!!!!! > Sorry, but I am having some trouble understanding what exactly you are trying to do. Mozda bi bilo lakse da objasnis na neki drugi jezik, sta mislis o tome? Ogi. From warren at muse.com Fri Jun 1 13:22:29 2007 From: warren at muse.com (Warren Stringer) Date: Fri, 1 Jun 2007 10:22:29 -0700 Subject: c[:]() In-Reply-To: References: <1180504190.055427.173610@h2g2000hsg.googlegroups.com><1180554872.3356.30.camel@dot.uniqsys.com><465DF3DE.40404@cc.umanitoba.ca><1180566831.239580.199300@m36g2000hse.googlegroups.com><005401c7a31a$136f7fe0$240110ac@Muse><135tobve86qj808@corp.supernews.com><135tru124pie2b3@corp.supernews.com><135tv1bjqgbmsc9@corp.supernews.com> <135v9liaoqgcf83@corp.supernews.com> Message-ID: <005e01c7a471$6ec60780$240110ac@Muse> > > [Please quit saying "a container" if you mean lists and tuples. > > "A container" is way too general. There most probably _are_ > > containers for which c() does not fail.] > > One example of such a container is any folderish content in Zope: > subscripting gets you the contained pages, calling renders the default > view. Cool. Could you point me to some example code? From marcpp at gmail.com Wed Jun 13 16:33:54 2007 From: marcpp at gmail.com (Marcpp) Date: Wed, 13 Jun 2007 13:33:54 -0700 Subject: wx Listbox event Message-ID: <1181766834.764449.35930@o11g2000prd.googlegroups.com> Hi, I need to charge a list when starts the program. I've tried a few events like: self.llistatids = wx.ListBox(self, -1, choices=['a'], style=wx.LB_SINGLE|wx.LB_ALWAYS_SB) self.llistatids.SetBackgroundColour(wx.Colour(255, 255, 220)) self.llistatids.Bind(wx.EVT_LISTBOX, self.carrega_llistatids) But I cannot do it, any idea? From p at ulmcnett.com Wed Jun 13 16:35:19 2007 From: p at ulmcnett.com (Paul McNett) Date: Wed, 13 Jun 2007 13:35:19 -0700 Subject: Build EXE on Mac OsX 10.4 In-Reply-To: <1181762699.145088.159500@j4g2000prf.googlegroups.com> References: <1181762699.145088.159500@j4g2000prf.googlegroups.com> Message-ID: <46705507.4000201@ulmcnett.com> Tempo wrote: > Has anyone sucesfully built a *.exe file on a mac operating system > before from a *.py file? I have been trying to do this with > pyinstaller, but I keep getting errors and I don't know how to install > UPX properly. I tried putting the linux UPX folder in my python 2.4 > directory, but that didn't work. I am just generally confused right > now. Ha. If anybody can lend me some insight I would really appreciate > it. Thank you for taking the time to read this post. You need to build Mac Apps on Mac, Windows EXE's on Windows, and Linux ELF's on Linux. You can't build a windows.exe from Mac, just as you can't build a mac.app from Windows. -- pkm ~ http://paulmcnett.com From eadmund42 at NOSPAMgmail.com Fri Jun 22 13:28:34 2007 From: eadmund42 at NOSPAMgmail.com (Robert Uhl) Date: Fri, 22 Jun 2007 11:28:34 -0600 Subject: The Modernization of Emacs: terminology buffer and keybinding References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182272495.990807.99110@a26g2000pre.googlegroups.com> <87tzt3ihev.fsf@kobe.laptop> <1182370216.961241.6960@n60g2000hse.googlegroups.com> <85zm2ufjpb.fsf@lola.goethe.zz> <1182372592.803332.288260@u2g2000hsc.googlegroups.com> <1182373919.262388.100740@c77g2000hse.googlegroups.com> <85r6o6fhkb.fsf@lola.goethe.zz> <1182375045.626510.188170@m36g2000hse.googlegroups.com> <1182453375.531950.141460@m36g2000hse.googlegroups.com> Message-ID: Falcolas writes: > > Being a primarily windows user, I have to question your assertion that > using ctrl-f for find causes a "mental context switch". For me, in 90% > of the windows applications, finding something is as simple as ctrl-f, > the phrase, hit enter. Not terribly different from your set of > commands. The biggest difference is that if I need to use a Find > feature I might not often use, I have a visual interface to all the > related search functions. On the other hand, a terminal program would > necessitate a memory search at best, or a trip to the help pages at > worst. That's the advantage of a well-organised set of commands. If you want to use regexp search, you have to look at the dialogue box and click on a checkbox--which would be a context switch. That's even assuming that your editor _offers_ regexp search. If emacs didn't have it, I could add it, and it'd be just as much part of the editor as if it were included... > The best part of my windows knowledge is that it's transferable to > most (all?) of the applications I work with. Find is usually ctrl-f. > Undo is ctrl-z. Save is ctrl-s, yadda yadda. Such knowledge is rarely > transferable from terminal programs in my experience -- what may be > true for one program (emacs) is wildly different in another program > (vi), and useless in yet another (pico). Consistency is nice. That's be why the emacs are found throughout Unix. In fact, for a long time Netscape used emacs bindings on Macs and Windows. Among these bindings are C-a to go the beginning of a line, C-e to go to the end, C-k to kill from point to the end of the line, M-b and M-f to move forward and back by word and so forth. It's Mac OS and Windows which are inconsistent. Emacs has been around since they were mere glimmers in the eye of Jobs & Gates... -- Robert Uhl Just because I'm not doing anything, doesn't mean I have nothing to do! --Ellen Winnie From gagsl-py2 at yahoo.com.ar Mon Jun 11 17:10:03 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 11 Jun 2007 18:10:03 -0300 Subject: Accessing global namespace from module References: <1181577768.728377.262720@m36g2000hse.googlegroups.com> <1181583469.562064.29440@p77g2000hsh.googlegroups.com> <1181585938.144294.119790@w5g2000hsg.googlegroups.com> <1181593775.957808.136050@m36g2000hse.googlegroups.com> Message-ID: En Mon, 11 Jun 2007 17:29:35 -0300, reubendb escribi?: > On Jun 11, 3:30 pm, "Gabriel Genellina" > wrote: >> En Mon, 11 Jun 2007 15:18:58 -0300, reubendb >> escribi?: >> >> > The problem is I don't define the functions AddPlot() and DrawPlots(). >> > It's built into the python interpreter of the CLI version of the >> > program I mentioned, and they are defined on the main script. I load >> > the main script using something like "software -cli -s >> > mainscript.py". >> > In the mainscript.py I import myModule, but of course myModule does >> > not have access to the functions defined in the global namespace of >> > mainscript.py. >> >> Don't you have some import statements at the top of mainscript.py that >> are >> responsible for bringing AddPlot and DrawPlots into the current >> namespace? >> Import the same things in your second module. > > No, I *don't* have any import statement mainscript.py. When using this > software's CLI, AddPlot and DrawPlots are available to me > automagically from mainscript.py. Hence my question: How do I make > this available from other module. Is there any way at all ? Yes: create your own module on-the-fly, using the recipe posted earlier by John Krukoff. If there are many functions, try enumerating them all: import sys from types import ModuleType as module plotModule = module('plot') for key,value in globals().items(): if key[:2] != '__': setattr(plotModule, key, value) sys.modules['plot'] = plotModule -- Gabriel Genellina From gagsl-py2 at yahoo.com.ar Wed Jun 20 20:43:59 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 20 Jun 2007 21:43:59 -0300 Subject: need help with re module References: <46795CBA.9040807@gmail.com> Message-ID: En Wed, 20 Jun 2007 17:56:30 -0300, David Wahler escribi?: > On 6/20/07, Gabriel Genellina wrote: >> En Wed, 20 Jun 2007 13:58:34 -0300, linuxprog >> escribi?: >> >> > i have that string "helloworldok" and i want to >> > extract all the text , without html tags , the result should be some >> > thing like that : helloworldok >> >> You can't use a regular expression for this task (no matter how >> complicated you write it). > [snip] > > I agree that BeautifulSoup is probably the best tool for the job, but > this doesn't sound right to me. Since the OP doesn't care about tags > being properly nested, I don't see why a regex (albeit a tricky one) > wouldn't work. For example: > > regex = re.compile(r''' > <[^!] # beginning of normal tag > ([^'">]* # unquoted text... > |'[^']*' # or single-quoted text... > |"[^"]*")* # or double-quoted text > > # end of tag > | srvr =SocketServer.TCPServer(('',port_num), TCPHandlerClass) > > I'd like to be able to: srvr =SocketServer.TCPServer(('',port_num), > TCPHandlerClass, (arg1,arg2)) > > And have arg1, arg2 available via TCPHandlerClass.__init__ or some other > way. > I use the following method. Would also like to know if there's another way to do this. class SVNUpdateRequestHandler(SocketServer.BaseRequestHandler): def __init__(self, svn, wms, *args, **kwargs): self.svn = svn self.wms = wms # NEED to set additional attributes before parent init SocketServer.BaseRequestHandler.__init__(self, *args, **kwargs) def handle(self): pass def get_handler(svn, wms): class RequestHandler(SVNUpdateRequestHandler): def __init__(self, *args, **kwargs): SVNUpdateRequestHandler.__init__(self, svn, wms, *args, **kwargs) return RequestHandler def main(port, requesthandler): server = SVNUpdateServer(('', port), requesthandler) while 1: server.handle_request() if __name__ == '__main__': svn, wms = sys.argv[1:] requesthandler = get_handler(svn, wms) main(port, requesthandler) From exarkun at divmod.com Sat Jun 9 17:31:57 2007 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Sat, 9 Jun 2007 17:31:57 -0400 Subject: Hooking exceptions outside of call stack In-Reply-To: <002c01c7aad8$12963440$240110ac@Muse> Message-ID: <20070609213157.30678.763231875.divmod.quotient.13265@ohm> On Sat, 9 Jun 2007 13:52:19 -0700, Warren Stringer wrote: >Am still trying to hook a NameError exception and continue to run. After a >few more hours of searching the web and pouring over Martelli's book, the >closest I've come is: > >>>> import sys >>>> def new_exit(arg=0): >... print 'new_exit called' >... #old_exit(arg) >... >>>> def hook(type, value, tb): >... print 'hook called with', type >... return >... >>>> sys.excepthook = hook >>>> old_exit = sys.exit >>>> sys.exit = new_exit >>>> a[b]=1 # would like to get new_exit called >hook called with exceptions.NameError >>>> >>>> def test(): >... sys.exit() >... >>>> test() >new_exit called > >The interactive session is different from running in the IDE (am using >ActiveState's Visual Python) which exits just after the `a[b]=1` without >calling hook. > >Am I missing something? Perhaps this is the wrong approach? I want Python to >check a specific set of locals first, before checking globals. For instance: > Yes. Python doesn't have restartable exceptions. Perhaps you would like to take a look at CL or Smalltalk? Jean-Paul From fdu.xiaojf at gmail.com Wed Jun 13 03:45:08 2007 From: fdu.xiaojf at gmail.com (fdu.xiaojf at gmail.com) Date: Wed, 13 Jun 2007 15:45:08 +0800 Subject: How to create a tuple quickly with list comprehension? Message-ID: <466FA084.7050503@gmail.com> Hi all, I can use list comprehension to create list quickly. So I expected that I can created tuple quickly with the same syntax. But I found that the same syntax will get a generator, not a tuple. Here is my example: In [147]: a = (i for i in range(10)) In [148]: b = [i for i in range(10)] In [149]: type(a) Out[149]: In [150]: type(b) Out[150]: Is there a way to create a tuple like (1, 2, 3, 4, 5, 6, 7, 8, 9) quickly? I already I can use tuple() on a list which is created by list comprehension to get a desired tuple. Regards, Xiao Jianfeng From doug at alum.mit.edu Thu Jun 28 21:30:48 2007 From: doug at alum.mit.edu (Douglas Alan) Date: Thu, 28 Jun 2007 21:30:48 -0400 Subject: Python's "only one way to do it" philosophy isn't good? References: <1182750077.570603.160240@q69g2000hsb.googlegroups.com> <7xir9cbm0g.fsf@ruckus.brouhaha.com> <7xejjzmk7u.fsf@ruckus.brouhaha.com> <7xy7i7xjl5.fsf@ruckus.brouhaha.com> <5N0C7KBirhgGFwUp@woodrowhorsfall.plus.com> Message-ID: Steve Holden writes: > Douglas Woodrow wrote: >> On Wed, 27 Jun 2007 01:45:44, Douglas Alan wrote >>> A chaque son gout >> I apologise for this irrelevant interruption to the conversation, >> but this isn't the first time you've written that. The word >> "chaque" is not a pronoun. >> http://grammaire.reverso.net/index_alpha/Fiches/Fiche220.htm > Right, he probably means "Chaqu'un ? son gout" (roughly, each to his > own taste). Actually, it's "chacun". And the "?" may precede the "chacun". |>oug From weidongtom at gmail.com Tue Jun 19 03:27:05 2007 From: weidongtom at gmail.com (weidongtom at gmail.com) Date: Tue, 19 Jun 2007 07:27:05 -0000 Subject: Permutation over a list with selected elements Message-ID: <1182238025.739189.208970@a26g2000pre.googlegroups.com> Hi, I have been working at this problem, and I think I need a permutation algorithm that does the following: Given a list of elements that are either a character or a character follows by a number, e.g. ['a', 'b', 'c1', 'd', 'e1', 'f', 'c2', 'x', 'e2'] find all the permutations that are given by switching the positions of the elements that: (1) begins with the same letter, and (2) follows by a number. With the above list, some possible permutations are: ['a', 'b', 'c2', 'd', 'e1', 'f', 'c1', 'x', 'e2'] ['a', 'b', 'c1', 'd', 'e2', 'f', 'c2', 'x', 'e1'] ['a', 'b', 'c2', 'd', 'e2', 'f', 'c1', 'x', 'e1'] Can anyone help me out? Thanks in advance. From zaperaj at gmail.com Thu Jun 21 04:03:43 2007 From: zaperaj at gmail.com (zaperaj at gmail.com) Date: Thu, 21 Jun 2007 08:03:43 -0000 Subject: Error while installing Python2.5.1 Message-ID: <1182413023.924197.302390@o11g2000prd.googlegroups.com> I use red hat 9 which comes with python2.2 installed in it. Wanting to use the latest version, i downloaded python 2.5.1 from the official python website. After downloading, i performed the following steps, but there is some error during the configuration process and hence i'm not able to run the "make" command after this. Following is the sequence of events that happened in my terminal: [root at localhost root]# tar xfz Python-2.5.1.tgz [root at localhost root]# cd Python-2.5.1 [root at localhost Python-2.5.1]# ./configure checking MACHDEP... linux2 checking EXTRAPLATDIR... checking for --without-gcc... no checking for gcc... no checking for cc... no checking for cc... no checking for cl... no configure: error: no acceptable C compiler found in $PATH See `config.log' for more details. [root at localhost Python-2.5.1]# make make: *** No targets specified and no makefile found. Stop. If anybody can help... Thanx! From oscartheduck at gmail.com Fri Jun 22 17:23:11 2007 From: oscartheduck at gmail.com (oscartheduck) Date: Fri, 22 Jun 2007 21:23:11 -0000 Subject: regular expression concatenation with strings In-Reply-To: <1182546637.032673.106920@a26g2000pre.googlegroups.com> References: <1182543519.337279.25800@z28g2000prd.googlegroups.com> <1182546637.032673.106920@a26g2000pre.googlegroups.com> Message-ID: <1182547391.636712.131740@a26g2000pre.googlegroups.com> Shoot, I think I realised what I'm doing wrong. Let me write some code to address this, but I'm almost certain that the error is that I'm attempting to save an image with a regular expression, which is by nature fluid, tacked on to its ass after the .thumbnail. Which, now I look at your code, you address implicitly by suggesting that the extension be a different variable. Thanks! On Jun 22, 3:10 pm, oscartheduck wrote: > Hi, > > I noticed a small error in the code (you referenced extension, which > you had renamed to filenameRx), and when I corrected it I received the > original error again. What was it you were trying to do to solve the > problem, though? > > Thanks! > > On Jun 22, 2:41 pm, Jacek Trzmiel wrote: > > > Hi, > > > oscartheduck wrote: > > > I have a little script that sits in a directory of images and, when > > > ran, creates thumbnails of the images. It works fine if I call the > > > function inside the program with something like "thumbnailer("jpg), > > > but I want to use a regular expression instead of a plain string so > > > that I can match jpeg, jpg, JPEG etc. > > > Something like this will work: > > > #!/usr/bin/env python > > #from PIL import Image > > import glob, os, re > > > size = 128, 128 > > > def thumbnailer(dir, filenameRx): > > for picture in [ p for p in os.listdir(dir) if > > os.path.isfile(os.path.join(dir,p)) and filenameRx.match(p) ]: > > file, ext = os.path.splitext(picture) > > im = Image.open (picture) > > im.thumbnail(size, Image.ANTIALIAS) > > im.save(file + ".thumbnail." + extension) > > > jpg = re.compile(".*\.(jpg|jpeg)", re.IGNORECASE) > > thumbnailer(".", jpg) > > > Best regards, > > Jacek. From nick at craig-wood.com Fri Jun 8 12:30:04 2007 From: nick at craig-wood.com (Nick Craig-Wood) Date: Fri, 08 Jun 2007 11:30:04 -0500 Subject: Bug/Weak Implementation? popen* routines can't handle simultaneous read/write? References: <1181232071.928835.301710@w5g2000hsg.googlegroups.com> <1181264380.441881.38570@i13g2000prf.googlegroups.com> Message-ID: Noah wrote: > On Jun 7, 9:01 am, dmoore wrote: > > popen and friends will never do what you want it to do. Down that path > lies bitter disappointment. > You need pseduo-ttys and non-blocking IO. I don't know how to do this > on Windows, but I know it's possible. > Cygwin does it. > > > Anybody have any thoughts on this? Do I have my story straight? (the > > popen variants can't handle this case and there are no other > > alternatives in the standard python distro) Is there some place I can > > submit this as a feature request? (Python dev?) > > Try Pexpect http://pexpect.sourceforge.net/ > It's been around for a long time and is quite complete and stable. > > The catch is that it's UNIX-only. If you want to tease out the magic > code from wxProcess that > does non-blocking reads on win32 then I'd be happy to integrate that > into the current development branch > of Pexpect. Windows has a really strange idea of non-blocking IO - it uses something called overlapped io. You or in the FILE_FLAG_OVERLAPPED flag when you create the file/pipe. You then pass in overlap buffers for reading writing. I implemented this for serial ports in C a while ago. If you look at the code in pyserial (in serialwin32.py) you'll see a very similar implementation of non blocking IO. I assume that the same things will work for pipes, but I've only direct experience with serial ports! > I'm sure this is feasible without any C extensions -- it might require > some ctypes hacking. pyserial uses win32file and win32event > I know Windows has pretty decent async IO, but I don't know what they > have as an equivalent for a pty. > Maybe it isn't necessary. A pty is only necessary on UNIX because the > standard c library, stdio, behaves > differently when it's talking to a plain pipe versus a terminal -- it > switches buffering > between block and line oriented buffer. You don't want block buffering > on interactive applications. Pty's probably aren't needed on Windows. BTW I'd love to see pexpect working on windows and also in the standard library. It is the proper answer to controlling other interactive processes IMHO. -- Nick Craig-Wood -- http://www.craig-wood.com/nick From bbxx789_05ss at yahoo.com Sun Jun 3 02:17:33 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: Sat, 02 Jun 2007 23:17:33 -0700 Subject: How to control the creation of an instance? In-Reply-To: References: Message-ID: <1180851453.441872.107890@k79g2000hse.googlegroups.com> On Jun 2, 10:31 pm, lialie wrote: > Hi, > > suppose i have a free_object list[Sample1, Smaple2....]. when create a > new object sample(*args, **kwds), if free_object_list isn't empty, just > pop one from free_object_list instead of creating a new instance. > > any way to do this? > > I do some work as follows: > > class Sample(object): > used_object = [] > free_object = [] > > def __init__(self, *args, **kwds): > pass > > def __new__(self, *args, **kwds): > if Sample.free_object: > obj = Sample.free_object.pop(0) > else: > obj = object.__new__(Sample, *args, **kwds) > Sample.used_object.append(obj) > return obj > > ######## still get a new instance :( > > def Release(self): > Sample.used_object.remove(self) > Sample.free_object.append(self) > return True This seems to work for me: import collections class Sample(object): free_objects = collections.deque() used_objects = [] def __new__(cls, *args, **kwds): if not Sample.free_objects: temp = object.__new__(Sample, args, kwds) Sample.used_objects.append(temp) return temp else: return Sample.free_objects.popleft() def __init__(self, *args, **kwds): self.args = args self.kwds = kwds def release(self): Sample.used_objects.remove(self) Sample.free_objects.append(self) s1 = Sample(10, name="Bob") print s1 print s1.args print s1.kwds s2 = Sample("red", name="Bill") print s2 print s2.args print s2.kwds s1.release() s3 = Sample("blue", name="Tim") print s3 print s3.args print s3.kwds From nagle at animats.com Thu Jun 21 00:51:31 2007 From: nagle at animats.com (John Nagle) Date: Thu, 21 Jun 2007 04:51:31 GMT Subject: Python's "only one way to do it" philosophy isn't good? In-Reply-To: <7xabuv5doo.fsf@ruckus.brouhaha.com> References: <1181368143.874341.273140@r19g2000prf.googlegroups.com> <1182320758.022154.88360@o61g2000hsh.googlegroups.com> <7xabuv5doo.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > Michele Simionato writes: > >>I see Python or C as much better practical implementations >>of Sussman's quote about minimalism than real Scheme (for >>an example of real Scheme, I refer for instance to the PLT >>implementation). > > > Python and C as programming languages are like democracy as a system > of government--absolutely terrible, but everything else seems to be > even worse. > > The real answer (to programming languages, not governments) seems > tantalizingly close, but not here yet. Modula 3 was getting close, but it was being developed at DEC, which had no software business outside of selling for DEC systems. Then Compaq bought DEC and HP bought Compaq and all the research units disappeared. John Nagle From pjb at informatimago.com Fri Jun 22 15:19:30 2007 From: pjb at informatimago.com (Pascal Bourguignon) Date: Fri, 22 Jun 2007 21:19:30 +0200 Subject: I need some cleanings tips and advice. References: <1182528064.446459.49420@n2g2000hse.googlegroups.com> <467bf4c9@news.nucleus.com> Message-ID: <87fy4jkda5.fsf@thalassa.lan.informatimago.com> "Colin B." writes: > In comp.lang.perl.misc CleaningTips at gmail.com wrote: >> Me and my buddy made a website called www.stupidpinheads.com, its >> basically a free forum and free blog driven web site dedicated as a >> source people can goto to find out how to clean and remove stains from >> pretty much anything. Problem is, as of yet, you couldn't find out how >> to clean anything right now cause the site is new and no one has found >> it yet. > > Let's see if I get this right. > > You create a website for a subject that you know nothing about. Then you > try to solicit content in a bunch of programming language newsgroups. > > Wow, that's pretty pathetic, even for a google-groups poster! > > Begone with you. Pathetic, but it's a prooven way to become millionaire with the Internet. You can't blame him... http://www.milliondollarhomepage.com/ -- __Pascal Bourguignon__ http://www.informatimago.com/ NOTE: The most fundamental particles in this product are held together by a "gluing" force about which little is currently known and whose adhesive power can therefore not be permanently guaranteed. From bj_666 at gmx.net Wed Jun 13 06:37:02 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Wed, 13 Jun 2007 12:37:02 +0200 Subject: How to create a tuple quickly with list comprehension? References: <1181722446.984694.242700@q19g2000prn.googlegroups.com> <5d9ngkF32j8imU1@mid.uni-berlin.de> Message-ID: In <5d9ngkF32j8imU1 at mid.uni-berlin.de>, Diez B. Roggisch wrote: > No need to create the intermediate list, a generator expression works just > fine: > > a = tuple(i for i in range(10)) But `range()` creates the intermediate list anyway. ;-) a = tuple(xrange(10)) Ciao, Marc 'BlackJack' Rintsch From steve at holdenweb.com Sat Jun 2 14:06:53 2007 From: steve at holdenweb.com (Steve Holden) Date: Sat, 02 Jun 2007 14:06:53 -0400 Subject: Using PIL to find separator pages In-Reply-To: References: <4660406F.7070506@websafe.com> Message-ID: Larry Bates wrote: > Steve Holden wrote: >> Larry Bates wrote: >>> Steve Holden wrote: >>>> Larry Bates wrote: >>>>> I have a project that I wanted to solicit some advice >>>>> on from this group. I have millions of pages of scanned >>>>> documents with each page in and individual .JPG file. >>>>> When the documents were scanned the people that did >>>>> the scanning put a colored (hot pink) separator page >>>>> between the individual documents. I was wondering if >>>>> there was any way to utilize PIL to scan through the >>>>> individual files, look at some small section on the >>>>> page, and determine if it is a separator page by >>>>> somehow comparing the color to the separator page >>>>> color? I realize that this would be some sort of >>>>> percentage match where 100% would be a perfect match >>>>> and any number lower would indicate that it was less >>>>> likely that it was a coverpage. >>>>> >>>>> Thanks in advance for any thoughts or advice. >>>>> >>>> I suspect the easiest way would be to select a few small patches of each >>>> image and average the color values of the pixels, then normalize to hue >>>> rather than RGB. >>>> >>>> Close enough to the hue you want (and you could include saturation and >>>> intensity too, if you felt like it) across several areas of the page >>>> would be a hit for a separator. >>>> >>>> regards >>>> Steve >>> Steve, >>> >>> I'm completely lost on how to proceed. I don't know how to average color >>> values, normalize to hue... Any guidance you could give would be greatly >>> appreciated. >>> >>> Thanks in advance, >>> Larry >> I'd like to help but I don't have any sample code to hand. Maybe someone >> who does could give you more of a clue. Let's hope so, anyway ... >> >> regards >> Steve > > I think I've come up with something that will work. I use PIL > Image.getcolors() to get colors and take the top 10 colors of my > background page. I then calculate the average of the R, G, B > components. That becomes my reference. Then I read a page and > make the same calculation. I then calculate the absolute value > of the difference of R, G, B of the two values. Sum those > together gives something like the average difference between > the two average colors (at least that is what I think it does). > This seems to give me small numbers when the pages are the same > and large numbers when they are different. It isn't super fast > but it is working. > > Thanks for pushing me in the right direction. > > -Larry Well done! Thanks for letting me know that the basic approach was correct. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden ------------------ Asciimercial --------------------- Get on the web: Blog, lens and tag your way to fame!! holdenweb.blogspot.com squidoo.com/pythonology tagged items: del.icio.us/steve.holden/python All these services currently offer free registration! -------------- Thank You for Reading ---------------- From simonkagwe at yahoo.com Mon Jun 25 08:48:07 2007 From: simonkagwe at yahoo.com (simon kagwe) Date: Mon, 25 Jun 2007 12:48:07 +0000 (UTC) Subject: Changing sound volume References: <1182727056.516883.241390@o61g2000hsh.googlegroups.com> Message-ID: > And finally a way that might work using ctypes: > > http://mail.python.org/pipermail/python-win32/2006-March/004436.html > > Mike Hi, Thanks for your reply. I had already read about the Snack, but I can't use it since my program uses wxPython for the GUI and Snack requires tk. The best option was the ctypes method you told me about. I used the code in the sample, but I am getting the following error: exceptions.WindowsError Error 11 while setting volume The author of the code claims it works. What could be causing the above error? [ I am using Python 2.4.4 and ctypes 1.0.1 ] Regards, Simon From allison.william at nospam.gmail.com Tue Jun 19 11:20:08 2007 From: allison.william at nospam.gmail.com (William Allison) Date: Tue, 19 Jun 2007 11:20:08 -0400 Subject: Python IDE In-Reply-To: <5dq3n9F359hp0U1@mid.individual.net> References: <1182249585.535675.143460@m36g2000hse.googlegroups.com> <1182259143.375798.283620@k79g2000hse.googlegroups.com> <5dq3n9F359hp0U1@mid.individual.net> Message-ID: Bjoern Schliessmann wrote: > BartlebyScrivener wrote: >> VIM > > *clap-clap* > > BTW, are there tutorials on the more arcane vim functions that come > in handy with Python? > > Regards, > > > Bj?rn > Not a tutorial, but I found this little snippet: http://www.ibiblio.org/obp/pyBiblio/tips/elkner/vim4python.php I thought the last line was especially neat. Will From info at namedrive.com Sun Jun 10 18:39:30 2007 From: info at namedrive.com (en.wikipedia.org) Date: Sun, 10 Jun 2007 22:39:30 GMT Subject: Tits Live Webcams Boobs all naturals Message-ID: http://www.tits.sc/ The Best Resource for Tits on the Net. From martin at v.loewis.de Thu Jun 28 00:51:05 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Thu, 28 Jun 2007 06:51:05 +0200 Subject: glob.glob standardization In-Reply-To: <1182982000.940609.201250@k79g2000hse.googlegroups.com> References: <1182982000.940609.201250@k79g2000hse.googlegroups.com> Message-ID: <46833E39.4020301@v.loewis.de> > Don't you think it would be more convenient for glob.glob to return > file names only in any case, like os.listdir do? No. Use glob.glob1 if you want a list of files. Regards, Martin From stefan.sonnenberg at pythonmeister.com Tue Jun 5 08:07:44 2007 From: stefan.sonnenberg at pythonmeister.com (Stefan Sonnenberg-Carstens) Date: Tue, 05 Jun 2007 14:07:44 +0200 Subject: subprocess leaves child living In-Reply-To: References: Message-ID: <46655210.10707@pythonmeister.com> Thomas Dybdahl Ahle schrieb: > Hi, When I do a small program like > > from subprocess import Popen > popen = Popen(["ping", "google.com"]) > from time import sleep > sleep(100) > > start it and kill it, the ping process lives on. > Is there a way to ensure that the ping process is always killed when the > python process is? > I can't use atexit, as ping then isn't killed when python is killed "in > the hard way" > Calling popen.close() perhaps ? You basically open a pipe, which spawns a shell and the command is then started in there. So, if your program quits, the spawned shell is still alive, only the pipe is dead. From streamservenl at gmail.com Wed Jun 20 11:22:01 2007 From: streamservenl at gmail.com (jvdb) Date: Wed, 20 Jun 2007 08:22:01 -0700 Subject: How to hide a program? In-Reply-To: References: <1182347596.414718.117190@w5g2000hsg.googlegroups.com> Message-ID: <1182352921.305431.72290@k79g2000hse.googlegroups.com> On 20 jun, 17:05, Larry Bates wrote: > jvdb wrote: > > Hi all, > > > I've created a program that receives files and opens the corresponding > > program (for example adobe acrobat). However, when started, i would > > like to see nothing of the running program. I only want to see the > > program that will be opened. > > Is it possible to start a program 'hidden' or minimized to at least > > the system tray? And, if yes., could some one help me on this? > > > Thanks already! > > > Jeroen > > You can do this with: > > import win32process > > STARTUPINFO=win32process.STARTUPINFO() > STARTUPINFO.dwX=0 > STARTUPINFO.dwY=0 > STARTUPINFO.dwXSize=800 > STARTUPINFO.dwYSize=600 > execute_target="enter program to run here" > commandLine=None > processAttributes=None > threadAttributes=None > bInheritHandles=0 > dwCreationFlags=0 > currentDirectory=None > # > # Start the program > # > win32process.CreateProcess(execute_target, > commandLine, > processAttributes, > threadAttributes, > bInheritHandles, > dwCreationFlags, > newEnvironment, > currentDirectory, > STARTUPINFO) > > -Larry Bates Hi Larry, The thing is, i don't want to see anything of my program, just the launched program. I already have the program working. But when i create an executable of it with py2exe and start it, i don't want to see that it is running, perhaps just in the systemtray. That is my problem. thanks! Jeroen From tjreedy at udel.edu Fri Jun 1 11:57:50 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 1 Jun 2007 11:57:50 -0400 Subject: Python 2.5.1 broken os.stat module References: <1180648618.295955.68600@x35g2000prf.googlegroups.com><465fa702$0$2944$9b622d9e@news.freenet.de> Message-ID: "Joe Salmeri" wrote in message news:y7SdnT6ey42WlP3bnZ2dnUVZ_segnZ2d at comcast.com... | I hope I have provided enough information for you to reproduce the bug so | that a solution can be found. If, when discussion is concluded here, you still think there is a bug, file a report on SF. Make a concise summary in the comments section and attach a file with the output from your experiments. You may have to submit the attachment separately after first submitting the report. Keep in mind that all the 'you's who might fix this are volunteers just like you. tjr From __peter__ at web.de Fri Jun 22 03:11:14 2007 From: __peter__ at web.de (Peter Otten) Date: Fri, 22 Jun 2007 09:11:14 +0200 Subject: why __repr__ affected after __getattr__ overloaded? References: <1182483043.850101.110890@i13g2000prf.googlegroups.com> <1182491330.343267.122010@q19g2000prn.googlegroups.com> <1182491802.112209.322440@e9g2000prf.googlegroups.com> <1182494606.966742.63710@e9g2000prf.googlegroups.com> Message-ID: Roc Zhou wrote: > I'm sorry but I still have a question, look at this example: >>>> class test: > ... def __init__(self): > ... self.x = 1 > ... def __getattr__(self, attr_name): > ... print attr_name > ... if attr_name == 'y': > ... return 2 > ... else: > ... raise AttributeError, attr_name > ... >>>> t = test() >>>> t.x > 1 >>>> t.y > y > 2 >>>> print t.x > 1 >>>> print t > __str__ > __repr__ > <__main__.test instance at 0xb7f6d6cc> > > Since __str__ and __repr__ does not exist because their names was > printed, why not the "AttributeError" be raised? Because classic classes invoke t.__getattr__(self, "__repr__") and expect that to return a proper __repr__() method -- unless __getattr__() raises an AttributeError: >>> class Test: ... def __getattr__(self, name): ... if name == "__repr__": ... raise AttributeError ... return "" % name ... >>> t = Test() >>> t <__main__.Test instance at 0x401d42ac> If you use newstyle classes you won't run into that particular problem: >>> class Test(object): ... def __getattr__(self, name): ... return "" % name ... >>> t = Test() >>> t <__main__.Test object at 0x401d426c> >>> t.yadda "" From gur.tom at gmail.com Tue Jun 19 06:39:45 2007 From: gur.tom at gmail.com (Tom Gur) Date: Tue, 19 Jun 2007 10:39:45 -0000 Subject: Python IDE Message-ID: <1182249585.535675.143460@m36g2000hse.googlegroups.com> Hi, which IDE would you recommend for a python ? From stephenhorne100 at aol.com Tue Jun 5 11:26:10 2007 From: stephenhorne100 at aol.com (Ninereeds) Date: Tue, 05 Jun 2007 08:26:10 -0700 Subject: *Naming Conventions* In-Reply-To: <1180990280.960271.235550@h2g2000hsg.googlegroups.com> References: <1180909218.939713.112010@q69g2000hsb.googlegroups.com> <1180990280.960271.235550@h2g2000hsg.googlegroups.com> Message-ID: <1181057170.894940.320890@o5g2000hsb.googlegroups.com> Google Groups appears to have thrown away my original reply, so sorry if this appears twice... On Jun 4, 9:51 pm, "bruno.desthuilli... at gmail.com" wrote: > 'i' and 'j' are the canonical names for for loops indices in languages > that don't support proper iteration over a sequence. Using them for > the iteration variable of a Python for loop (which is really a > 'foreach' loop) would be at best confusing. Without wanting to start a religious war, I disagree. In practice, I believe most programmers associate those short names with pretty much any loop variable, irrespective of data type, based primarily on the simple fact that it's looping over a set of values whose meaning is obvious from context. That declaration is made after decades of working with other peoples code as well as my own. Don't believe me? Take a look at some code that uses C++ iterators, for example, or some C code that uses pointers as iterators, or some Ada code that loops over an enumerated type, etc etc. It won't find you long to realise that 'i' and 'j' are very common names for those too. I've seen 'i' used in "iterations" over lists in Scheme, OCaml and Haskell, whether done using tail recursion or list comprehensions or whatever. 'x' is more common, as with 'x:xs' patterns used to pick the head 'x' from a list in OCaml or Haskell, but then 'x' looks scarily like an ordinate we can't have that ;-) Anyway, why should 'indexes' always be numeric... > > for i in validanswers: > > if myAnswers.current in myAnswers.validList [i]: > > MyOptions['style'] = i > > And this is *exactly* what one should not do in Python. If you want a > generic name here, use 'item' instead. In this code, 'i' is appears to be just an answer identifier. It is used to identify for which answer in the validList you are looking for. It may well even be a numeric index (or some other kind of key), from what we can see in the example. "item" says nothing that "i" does not. If nothing else, you could always say that 'i' is short for 'item' or 'id' or whatever. > since the use of 'self' is mandatoy. That is true, making 'm' prefixes pointless in Python, but that's what comes from working with many different language. You don't always keep them neatly compartmentalised in your head. Habits can be very strong, and there is not always any strong reason to try to break them. Which is why you will still occasionally see 'm' prefixes in Python code. Actually, in *my* Python code you're still more likely to see 'f' (standing for field) prefixes - a convention I adopted in C++ at a time when I thought 'm' better suited macros, and when I'd never yet seen the 'm' for member prefix since most C++ code I'd seen still used the Hungarian conventions. It's a bad habit that I still haven't fully broken. > 1/ parameters names *are* local As they are in C and C++. Not just in terms of scoping, but in terms of being local variables too... int factorial (int p) { int l = 1; while (p > 1) { l *= p; p--; } return l; } def factorial (p) : l = 1 while p > 1 : l *= p; p -= 1 return l Updating parameters when you could just as easily update locals is of course bad style in either language - and some would say that any updating of parameters is bad style - but the point is that C and Python do the same thing. This example does illustrate another useful fact about the 'l' and 'p' prefixes - there are times when the prefix is all you need to specify the whole name, since there really is nothing else that can be usefully be said. > 2/ pythonic methods and functions tends to be short, so you usually > know which names are params. Well written functions and methods in any language tend to be short, but even so, there are times when a convention that distinguishes the two kinds of names without needing to think up distinct names is convenient. I wasn't suggesting that this convention should be universally adopted in Python or that it was relevant to Thorstens example even - but it is common in many languages (not just C++), and it does sometimes help resolve the how-can-I-give-these-meaningfully-different-names issue. > Python has a pretty good support for computed attributes (look for > 'property'), so you don't need explicit getters/setters. I may not use Python as my first and only language, but I have been using it since version 1.4 and I am perfectly aware of properties in Python, as I am in other languages. I am aware, for example, that they are relatively new additions to the language, that they are not used in a lot of code, and that you still need named getter and setter functions to redirect the property access to even if these names are only referred to in the property definition. All of which is mostly besides the point. More and more programmers are multilingual these days, and scripting languages such as Python are more likely second languages than first. Having a hard rule that conventions from one language should never leak into another, and that Python code should be somehow 'pure', is pointless, particularly when those conventions are common in many languages. Thorsten was having difficulty in finding distinct names, and I described a common naming convention that is often useful for this. I don't think I was wrong to do that. From aleax at mac.com Thu Jun 14 10:58:40 2007 From: aleax at mac.com (Alex Martelli) Date: Thu, 14 Jun 2007 07:58:40 -0700 Subject: Python-URL! - weekly Python news and links (Jun 11) References: Message-ID: <1hzou3t.1ptd8951hrox22N%aleax@mac.com> Gabriel Genellina wrote: > QOTW: "That's the Martellibot for you. Never use a word where a paragraph > with explanatory footnotes will do. > > Sigh. I miss him on c.l.py." - Simon Brunning Funny -- didn't Simon write this in 2005 referring to an essay of mine that I had posted in 2002, ? Longest "week" on record, unless I'm missing something!-) Alex From Graham.Dumpleton at gmail.com Wed Jun 13 04:01:37 2007 From: Graham.Dumpleton at gmail.com (Graham Dumpleton) Date: Wed, 13 Jun 2007 08:01:37 -0000 Subject: cgi.FieldStorage() not working on Windows In-Reply-To: <1181703494.047837.26120@i38g2000prf.googlegroups.com> References: <1181661435.258140.17800@x35g2000prf.googlegroups.com> <1181692790.432649.273820@i13g2000prf.googlegroups.com> <1181703494.047837.26120@i38g2000prf.googlegroups.com> Message-ID: <1181721697.803594.208260@q19g2000prn.googlegroups.com> On Jun 13, 12:58 pm, arorap wrote: > Thanks for your reply. > > The reason I want to run it as CGI (even though mod_php is available > on my local computer Why do you keep mentioning mod_php, surely you mean mod_python. > is that the target machine to which I will > finally be uploading my scripts runs CGI. > > cgihandler should work just like CGI. I wouldn't rely on it being exactly the same. The way it works uses a number of kludges. Also, the mod_python.cgihandler code in mod_python doesn't really get much attention from mod_python developers anymore and not sure if it was even specifically retested when mod_python 3.3 was released. > Any clue why the > cgi.FieldStorage()might not be working ? Have no idea why it doesn't work as works as written on MacOS X even when mod_python.cgihandler is used. You'll have to get someone else who has Windows to try it. You might be better off going to the mod_python mailing list to get help, or just use plain old CGI instead since using mod_python isn't really going to gain you much anyway. Graham > On Jun 12, 7:59 pm, Graham Dumpleton > wrote: > > > On Jun 13, 1:17 am,arorap wrote: > > > > I've mod_php installed with Apache 2.2. In one of my folders, I'm > > > using the cgihandler as the PythonHandler as my target host runs > > > python only as CGI. Here cgi.FieldStorage() doesn't seem to work. I > > > can see the form data in sys.stdin but cgi.FieldStorage() returns an > > > empty dictionary. Here's the code for the test script I am posting to > > > - > > > > -- > > > #!/usr/bin/python > > > > import os > > > import cgi > > > import sys > > > > print "Content Type: text/plain\n\n" > > > print "Hello CGI World !\n" > > > > for key in os.environ: > > > print key + "= " + os.environ[key] > > > > print cgi.FieldStorage() > > > > print sys.stdin.read() > > > -- > > > > And here's the output I see .. > > > > -- > > > Hello CGI World ! > > > > HTTP_REFERER=http://learnpython/form.htm > > > SERVER_SOFTWARE= Apache/2.2.4 (Win32)mod_python/3.3.1 Python/2.5.1 > > > SCRIPT_NAME= /mptest.py > > > SERVER_SIGNATURE= > > > REQUEST_METHOD= POST > > > SERVER_PROTOCOL= HTTP/1.1 > > > QUERY_STRING= abc=ayz > > > PATH= C:\Program Files\Internet Explorer;;C:\WINDOWS\system32;C: > > > \WINDOWS;C:\WINDOWS\System32\Wbem;q:\bin;m:\cm\clearcase\bin;M:\PERL\NT > > > \EXEC\BIN;m:\cm\clearcase\bin\nt;M:\Perl\NT\EXEC\BIN;m:\perl\nt\exec > > > \bin;m:\cm\clearcase\utils;q:\bin;m:\opus;m:\tvcs;C:\highc331\bin;C: > > > \Program Files\Rational\ClearCase\bin;C:\Program Files\Rational\common > > > CONTENT_LENGTH= 86 > > > HTTP_USER_AGENT= Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; > > > SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727) > > > HTTP_CONNECTION= Keep-Alive > > > SERVER_NAME= learnpython > > > REMOTE_ADDR= 127.0.0.1 > > > PATHEXT= .COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH > > > SERVER_PORT= 80 > > > SERVER_ADDR= 127.0.0.1 > > > DOCUMENT_ROOT= D:/Projects/LearnPython/www > > > COMSPEC= C:\WINDOWS\system32\cmd.exe > > > SCRIPT_FILENAME= D:/Projects/LearnPython/www/mptest.py > > > SERVER_ADMIN= puneet.ar... at tekelec.com > > > HTTP_HOST= learnpython > > > SystemRoot= C:\WINDOWS > > > HTTP_CACHE_CONTROL= no-cache > > > REQUEST_URI= /mptest.py?abc=ayz > > > HTTP_ACCEPT= */* > > > WINDIR= C:\WINDOWS > > > GATEWAY_INTERFACE= Python-CGI/1.1 > > > REMOTE_PORT= 1081 > > > HTTP_ACCEPT_LANGUAGE= en-us > > > CONTENT_TYPE= application/x-www-form-urlencoded > > > HTTP_ACCEPT_ENCODING= gzip, deflate > > > > FieldStorage(None, None, []) > > > > firstName=puneet&address=hawaii > > > -- > > > > I am posting to this script using a form with two text fields named > > > firstName and address. > > > > any clue where am I going wrong ? > > > You don't need mod_python/cgihandler to run CGI scripts. Rather than > > bring mod_python into the picture and confuse things, set up Apache to > > run your script as a traditional CGI script instead. > > > BTW, the fact that mod_python is loaded means that CGI scripts aren't > > the only way of using Python available to you as you seem to think. > > So, suggest you do some research as to what the differences are > > between CGI and mod_python. From gagsl-py2 at yahoo.com.ar Fri Jun 22 03:08:39 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 22 Jun 2007 04:08:39 -0300 Subject: why __repr__ affected after __getattr__ overloaded? References: <1182483043.850101.110890@i13g2000prf.googlegroups.com> <1182491330.343267.122010@q19g2000prn.googlegroups.com> <1182491802.112209.322440@e9g2000prf.googlegroups.com> <1182494606.966742.63710@e9g2000prf.googlegroups.com> Message-ID: En Fri, 22 Jun 2007 03:43:26 -0300, Roc Zhou escribi?: > I'm sorry but I still have a question, look at this example: >>>> class test: > ... def __init__(self): > ... self.x = 1 > ... def __getattr__(self, attr_name): > ... print attr_name > ... if attr_name == 'y': > ... return 2 > ... else: > ... raise AttributeError, attr_name > ... >>>> t = test() >>>> t.x > 1 >>>> t.y > y > 2 >>>> print t.x > 1 >>>> print t > __str__ > __repr__ > <__main__.test instance at 0xb7f6d6cc> > > Since __str__ and __repr__ does not exist because their names was > printed, why not the "AttributeError" be raised? This is the implementation of str() in action; tries to find a __str__ method and fails; tries to find a __repr__ instead and fails; then uses the default representation. See -- Gabriel Genellina From gregpinero at gmail.com Mon Jun 25 02:22:25 2007 From: gregpinero at gmail.com (gregpinero at gmail.com) Date: Mon, 25 Jun 2007 06:22:25 -0000 Subject: Chroot Jail Not Secure for Sandboxing Python? In-Reply-To: <467f55f7$0$20850$9b622d9e@news.freenet.de> References: <1182748892.916068.146780@p77g2000hsh.googlegroups.com> <467f55f7$0$20850$9b622d9e@news.freenet.de> Message-ID: <1182752545.475065.30310@k79g2000hse.googlegroups.com> On Jun 25, 1:43 am, "Martin v. L?wis" wrote: > gregpin... at gmail.com schrieb: > > > This wiki page suggests using a chroot jail to sandbox Python, but > > wouldn't running something like this in your sandboxed Python instance > > still break you out of the chroot jail: > > > os.execle ('/usr/bin/python','-c','import os; os.execlp("/bin/sh")', > > {}) > > Depending on how the chroot jail is set up, this command might not > work - in the jail, /bin/sh might not exist. This was my thought too. I just figured there was something special about this command that brought one to the "real" Python intrepreter and then to the real "/bin/sh". That's odd, my ISP seem adament that this is a way to break out. I'll just have to put in the work to test to locally I guess. > > So is a chroot jail not adequate for sandboxing Python? > > You have to define your threat model. If the threat to prevent is > a malicious user getting at your data, or spreading a virus > through your files, then chroot is perfectly adequate. Yeah, sounds like my threat model. Maybe prevent someone sending spam, or DOS from my server too. -Greg From bignose+hates-spam at benfinney.id.au Sat Jun 2 20:49:49 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sun, 03 Jun 2007 10:49:49 +1000 Subject: Jinja 1.1 Released In-Reply-To: (Armin Ronacher's message of "Sat, 02 Jun 2007 06:01:25 -0700") References: Message-ID: <878xb1zwsy.fsf@benfinney.id.au> Armin Ronacher writes: > Jinja 1.1 Released > ================== > > Jinja 1.1 codenname sinka is out! And with more changes then ever. > Here a small summary of the new features and improvements: This gives the reader no information about what Jinja actually is. It's far preferable to have a "What is Foo?" section in any new-release-of-Foo announcement for a project. -- \ "The future always arrives too fast, and in the wrong order." | `\ -- Alvin Toffler | _o__) | Ben Finney From tijs_news at bluescraper.nl Fri Jun 1 06:08:12 2007 From: tijs_news at bluescraper.nl (Tijs) Date: Fri, 01 Jun 2007 12:08:12 +0200 Subject: file reading by record separator (not line by line) References: Message-ID: <465ff00c$0$323$e4fe514c@news.xs4all.nl> Steve Howell wrote: > > > I think itertools.groupby() is usually the key > batteries-included component in elegant solutions to > this problem, but I wonder if the Python community > couldn't help a lot of newbies (or insufficiently > caffeinated non-newbies) by any of the following: > Well, I'm not a newbie, and I always make sure to be thoroughly caffeinated before sitting down for coding. But I think the itertools example in the parent post shows a problem with that package: unless you have intimate knowledge of the package, it is not clear what the code does when reading it. In other words, it is not intuitive. Perhaps a dedicated "block-read" module that wraps any read()-able object would be better. At least it would immediately be clear what the code means. from blockread import BlockReader b = BlockReader(f, boundary='>') for block in b: # whatever -- Regards, Tijs From half.italian at gmail.com Wed Jun 13 00:17:36 2007 From: half.italian at gmail.com (half.italian at gmail.com) Date: Tue, 12 Jun 2007 21:17:36 -0700 Subject: Bytes/File Size Format Function In-Reply-To: <1181706472.008233.80050@a26g2000pre.googlegroups.com> References: <1181706472.008233.80050@a26g2000pre.googlegroups.com> Message-ID: <1181708256.687657.227740@d30g2000prg.googlegroups.com> On Jun 12, 8:47 pm, samuraisam wrote: > Quick file size formatting for all those seekers out there... > > import math > > def filesizeformat(bytes, precision=2): > """Returns a humanized string for a given amount of bytes""" > bytes = int(bytes) > if bytes is 0: > return '0bytes' > log = math.floor(math.log(bytes, 1024)) > return "%.*f%s" % ( > precision, > bytes / math.pow(1024, log), > ['bytes', 'kb', 'mb', 'gb', 'tb','pb', 'eb', 'zb', 'yb'] > [int(log)] > ) Life is odd. I just came to the group with the specific purpose of asking this exact question. Who are you? :) Thanks! ~Sean From gagsl-py2 at yahoo.com.ar Mon Jun 25 02:50:10 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 25 Jun 2007 03:50:10 -0300 Subject: socket on cygwin python References: <1182748882.617588.190230@c77g2000hse.googlegroups.com> <467f5209$0$26251$9b622d9e@news.freenet.de> <1182751425.986905.184460@o61g2000hsh.googlegroups.com> Message-ID: En Mon, 25 Jun 2007 03:03:45 -0300, escribi?: > So I tried to find a binary files on Python.org, but I can't find it. > Could you tell me the binary location for the file? Thank you. Go to http://www.python.org/ Click on DOWNLOAD on the left Choose the version/release/flavor you want. -- Gabriel Genellina From no-spam at no-spam-no-spam.invalid Sat Jun 9 12:50:49 2007 From: no-spam at no-spam-no-spam.invalid (robert) Date: Sat, 09 Jun 2007 18:50:49 +0200 Subject: piping data stream through GPG In-Reply-To: References: Message-ID: robert wrote: > I played around trying to encrypt/decrypt data through GPG on the fly > (or worse - by using a file) (on Windows first - later to try on Linux too) > > Using os.popen3 like > > >>> i,o,e=os.popen3('gpg -e -r Robert') > >>> # i.write('y\n') > >>> i.write('wefwef') > >>> i.close() > >>> # e.read(1) > >>> o.read(1) > > hangs on o.read or e.read. > > So its quite dark. Just a totally non-existing userid (-r) will result > significantly different like > > >>> i.write('wefwef') > Traceback (most recent call last): > File "", line 1, in ? > IOError: [Errno 22] Invalid argument > > > GPG asks confirmation stuff (and pwd upon -d or -c) on the command line. > How to get all this the right way? > > I basically can handle it now by a os.popen3 cmd like 'gpg -e -r Robert --batch --always-trust', 'gpg -d -r Robert --batch --always-trust --passphrase-fd 0' and by using a thread for feeding the child_stdin stream (necessary for files of significant length / more than buffers) Robert From cody314 at gmail.com Mon Jun 4 18:59:49 2007 From: cody314 at gmail.com (Cody Brown) Date: Mon, 04 Jun 2007 22:59:49 -0000 Subject: Who uses Python? In-Reply-To: <1180985830.288414.208850@q69g2000hsb.googlegroups.com> References: <1180985830.288414.208850@q69g2000hsb.googlegroups.com> Message-ID: <1180997989.935328.73060@n15g2000prd.googlegroups.com> I went through my who undergrad experience without touching python (I've hear of it, but never used it). Now starting to work in an Research Lab Seismic processing of data, we use it all the time! That and Madagascar pyton interface. ~code From twisted0n3 at gmail.com Fri Jun 22 18:38:04 2007 From: twisted0n3 at gmail.com (Twisted) Date: Fri, 22 Jun 2007 22:38:04 -0000 Subject: The Modernization of Emacs In-Reply-To: References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182344981.372713.298580@w5g2000hsg.googlegroups.com> <1182370884.853838.321440@c77g2000hse.googlegroups.com> <2jpok4-ajt.ln1@zoogz.gregorie.org> Message-ID: <1182551884.239660.209700@x35g2000prf.googlegroups.com> On Jun 22, 11:52 am, Bjorn Borud wrote: > [Martin Gregorie ] > | > | Yep, and the same people think a command line is to be avoided at all > | costs. "I mean, its so /last century/ and you can't do anything useful > | with it anyway". I think a command line can be useful as a way to directly talk to something's brain. More GUI apps should have a command processor you can access to do something arcane once in a while. The other thing a command processor is good for is providing automation support. Windows is definitely weak on allowing things like editors to be embedded and used as components by other applications. OLE makes it theoretically possible to e.g. use Winword in an IDE but who'd want to? It also doesn't provide a system-wide way to select particular components to do particular jobs -- the closest thing would be splitting comctl32.dll into separate dlls for each common task or dialog and allowing third-party drop-in replacements to be found in a user-specific directory that override the defaults. That sort of modularity and choice is alien to MS thought patterns however. Combining the flexibility of componentry in Unix with the graphical power of Windows might lead to something awesome ... which makes KDE and Gnome things to keep eyes on in the future. > I have observed similar opinions in other non-computer-freaks. people > who see the computer only as a tool and are only interested in getting > the job done. they have a surprising preference for Linux. But not emacs, I'll bet. I think emacs appeals to people who like dealing with the mechanics of emacs or fiddling with and extending the darn thing. But most people just want to get the job done, and the editor or other tools they use have to get out of the way and simply let them work. If their attention keeps being dragged forcible from THE JOB to THE TOOL and how to make this cantankerous thing do *this*? then there is a problem. If I sit down at a windows text editor (or even kwrite or similar) I can just focus on the job. Faced with emacs or most other text-mode editors (but not MS-DOS Edit, interestingly) the editor keeps intruding on my focus. Oops. Elsewhere, you mentioned 3 second attention spans -- I think you'll find people are much more willing to spend 3 hours of attention on their task than 3 seconds on your favorite tool. When the tool intrudes into the user's attention (either by misbehaving, e.g. crashing, or by confounding the user as to how to do what they want to do next), then a problem is evident. From twisted0n3 at gmail.com Sun Jun 24 20:32:06 2007 From: twisted0n3 at gmail.com (Twisted) Date: Mon, 25 Jun 2007 00:32:06 -0000 Subject: The Modernization of Emacs: terminology buffer and keybinding In-Reply-To: References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182272495.990807.99110@a26g2000pre.googlegroups.com> <87tzt3ihev.fsf@kobe.laptop> <1182370216.961241.6960@n60g2000hse.googlegroups.com> <85zm2ufjpb.fsf@lola.goethe.zz> <1182372592.803332.288260@u2g2000hsc.googlegroups.com> <1182373919.262388.100740@c77g2000hse.googlegroups.com> <85r6o6fhkb.fsf@lola.goethe.zz> <1182375045.626510.188170@m36g2000hse.googlegroups.com> <85myyufgwj.fsf@lola.goethe.zz> <1182375528.985142.293900@q69g2000hsb.googlegroups.com> <1182545268.055596.228700@i38g2000prf.googlegroups.com> <1182661040.286559.150880@q75g2000hsh.googlegroups.com> Message-ID: <1182731526.329068.101540@c77g2000hse.googlegroups.com> On Jun 24, 7:19 pm, Robert Uhl wrote: > Twisted writes: > > > Of course, if emacs let you keep THREE windows open and visible at the > > same time, instead of being limited to one or a horizontally split two > > ... and a cramped 80x10 or so each, at that ... > > I have two frames open right now: one 80x70, the other around 180x70 > (characters, not pixels). One isn't split at all; the other is split > into four windows, horizontally and vertically. Then you're obviously not using the One True Emacs I am criticizing, which is a console app. If we're not talking about the same piece of software (and the one the fanatics evangelize about) then this is pointless. > emacs has continued doing its own thing, mostly because that thing is > better. The CUA standards (there exists an emacs package if you really > want them) are broken and lame--I and most other don't wish to cripple > our text editor of choice. "CUA standards"? I'm sorry, I don't speak Botswanan. If you mean Windows standards like for cut, copy, and paste, "broken and lame" is obviously in the eye in the beholder, and something 97% of computer users are used to is the defacto standard, so it's the other 3% that are "broken and lame". ;) > When you start emacs in a text console, you see this: > > Welcome to GNU Emacs, one component of the GNU/Linux operating system. > > Type C-l to begin editing. > > Get help C-h (Hold down CTRL and press h) > Emacs manual C-h r > Emacs tutorial C-h t Undo changes C-x u Really? That is not what I recall seeing. Are you talking about emacs- the-text-mode-editor, or emacs-the-hybrid-somethingorother-when-you- happen-to-run-it-from-the-command-prompt-on-unix? Because I've been discussing the former. > Buy manuals C-h C-m How crass. First I've seen anything open source/"free" software that makes sales pitches at you. Mostly I've only seen that with closed-source Windows "free"ware loaded with adware, and with shareware that nags you to register or otherwise spend money with its author. And with actual paid products, particularly those from Intuit which act as Intuit's front-line salesmen by trying to constantly upsell you and sell stuff to your friends and relatives. Er, thanks but no thanks. (I don't personally spend a dime on any Intuit products. I unfortunately know people who do. One version of some accounting software of theirs even spammed all of a user's email contacts, by God. Where are those Russian spammer-targeting hitmen when you need them?) > Activate menubar F10 or ESC ` or M-` Definitely not the stock text-mode emacs I've had my runins with in the past, but some kind of hybrid or offshoot, then. > Clicking within the document's window isn't obvious?!? Clicking within the document's window is obvious but doesn't work, unless you're using something other than vanilla emacs at least. It did of course work in MS-DOS Edit, later versions. > No, we're discussing emacs, a text editor which runs in both a GUI and a > text console. Which can display images. It's cool like that. No, we're discussing ... oh, nevermind. It looks like there are several utterly different pieces of software that have one thing in common - the name "emacs". Anyone can dodge or seem to rebut a criticism of one of them by describing how another of them isn't like that. :P > > At least Windows 3.1 had most apps have the same keys for the vast > > majority of commands, and those were the right keys. Emacs has all the > > applications have the vast majority of their commands use the same > > WRONG keys. > > Neither is right nor wrong; you're just used to one. The emacs keys are > certainly more flexible and powerful, though. Some might consider them > right for that reason. The Windows keys are familiar to 97% of the population. Some might consider them right for that reason. This is also a change from your earlier position that they were, and I quote, "broken and lame", assuming you mean the same stock Windoze keybindings you meant with the cryptic term "CUA standards". > > Search is usually ctrl+f, type something, hit enter in my experience. > > Unless you want regexp search. And if you want to find again it can be > interesting. I rarely want regexp search, and if I want it I can use Notetab, a notepad replacement with tabbed MDI and yes, regexp search. A few tabs and a space keypress to turn it on after ctrl+f. As for "find again" hitting enter additional times is the usual method, in Notetab, Notepad, and elsewhere. > > And I can use any text editor I want to edit HTML. > > You could use Notepad no doubt; you could also use a Turing machine. I > prefer to use a useful tool. Painting it as a choice between Notepad and emacs is the fallacy of false dichotomy. There's Notetab (useful, but non-free) and lots of (sometimes free) other text editors (for Windows and for other platforms). Some specialize in HTML editing the way Eclipse's built-in editor specializes in Java editing (and with plugins, can be made to specialize in, say, C instead). > No, as I've said over and over and over again, emacs is not what you > think it is. It has a GUI; it has colours; it can display images; it > can use the native widget set. It can even be configured to use native > keybindings, although that way lies madness. One thing I agree on regarding emacs is the phrase "that way lies madness". I'm amending that belief to include participating in Usenet discussions about emacs, as well as actually trying to use emacs. Given that everyone seems to mean a distinct piece of software by the term "emacs" it's a wonder anything coherent can be said about "emacs" at all. Actually, the one constant to emerge in all of this is C-h being associated with accessing the help in all of these various emacses. And we all know that that results in backspace doing surprising things for a text editor. :P > Hah! Dude, I don't use Windows--I've better things to do with my life. Xemacs then, or whatever they're calling the bolted-on-an-X-GUI-and- the-rivet-job-shows-from-1000-paces version these days. From frank at chagford.com Mon Jun 11 11:33:32 2007 From: frank at chagford.com (Frank Millman) Date: Mon, 11 Jun 2007 08:33:32 -0700 Subject: Postpone creation of attributes until needed In-Reply-To: <1181575378.910750.281590@d30g2000prg.googlegroups.com> References: <1181553891.447344.109390@g4g2000hsf.googlegroups.com> <1181559496.911368.219210@p77g2000hsh.googlegroups.com> <1181564855.890242.116840@m36g2000hse.googlegroups.com> <1181569088.048872.254700@m36g2000hse.googlegroups.com> <1181572626.761699.158130@n4g2000hsb.googlegroups.com> <1181575378.910750.281590@d30g2000prg.googlegroups.com> Message-ID: <1181576012.001222.212750@q75g2000hsh.googlegroups.com> On Jun 11, 5:22 pm, George Sakkis wrote: > On Jun 11, 10:37 am, Frank Millman wrote: > > > You never *need* decorators, in the sense it's just syntax sugar for > things you might do without them, but they're handy once you get your > head around them. > > > Actually I did spend a bit of time trying to understand it before > > posting, and I have a question. > > > It seems that this is now a 'read-only' attribute, whose value is > > computed by the function the first time, and after that cannot be > > changed. It would probably suffice for my needs, but how easy would it > > be to convert it to read/write? > > It's straightforward, just define a setter wrapper and pass it in the > property along with the getter: > > def cachedproperty(func): > name = '__' + func.__name__ > def getter(self): > try: return getattr(self, name) > except AttributeError: # raised only the first time > value = func(self) > setattr(self, name, value) > return value > def setter(self, value): > setattr(self, name, value) > return property(getter,setter) > Wonderful - this is very educational for me :-) Thanks very much Frank From jackie_python at yahoo.ca Sat Jun 23 21:39:08 2007 From: jackie_python at yahoo.ca (Jackie Wang) Date: Sat, 23 Jun 2007 21:39:08 -0400 (EDT) Subject: automatically pdf files generating Message-ID: <599549.63929.qm@web57508.mail.re1.yahoo.com> Hi, all, There are 50 folders in my hard driver C: C:\01.c:\02,...,c:\50 There are 4 pictures in each folder: 1.jpg,2.jpg,3.jpg,4.jpg For each folder, I want to print the 4 pictures into a single-paged pdf file (letter sized; print horizontally). All together, I want to get 50 pdf files with names: 01.pdf,02.pdf,...,50.pdf. Is it possible to use Python to realized the above process? I know there is a module named "reportlab". Is there any easy command in the module to do my job? Thanks Jackie --------------------------------- Be smarter than spam. See how smart SpamGuard is at giving junk email the boot with the All-new Yahoo! Mail -------------- next part -------------- An HTML attachment was scrubbed... URL: From walterbyrd at iname.com Tue Jun 5 12:50:18 2007 From: walterbyrd at iname.com (walterbyrd) Date: Tue, 05 Jun 2007 09:50:18 -0700 Subject: Who uses Python? In-Reply-To: <1181034089.239173.282900@g4g2000hsf.googlegroups.com> References: <1180985830.288414.208850@q69g2000hsb.googlegroups.com> <1181028719.829671.22230@a26g2000pre.googlegroups.com> <1181034089.239173.282900@g4g2000hsf.googlegroups.com> Message-ID: <1181062218.780387.219200@n4g2000hsb.googlegroups.com> On Jun 5, 3:01 am, Maria R wrote: > I tend to agree with some earlier poster that if you use Python you > are, in a sense, a programmer :o) > Yes, in a sense. But, in another sense, that is sort of like saying that people who post on message boards are "writers." I should have been more clear, when I posted "programmers" I meant "professional programmers" i.e. people who develop software applications for a living. I am getting the idea that most python "programmers" use python more like a tool, rather than as their primary specialization. In other words, python is usually not the primary specialization. I think this is different than other languages, such as Java, or even PHP. Few python users are specifically "python programmers" rather, they are data analysts, scientists, etc. who use python in the same way that some might use excel - as a tool. BTW: I am seriously impressed with the stuff that many here are doing with python. And I would like to thank those who responded to my post. From henriklied at gmail.com Mon Jun 25 19:29:51 2007 From: henriklied at gmail.com (Henrik Lied) Date: Mon, 25 Jun 2007 23:29:51 -0000 Subject: Face Recognition Message-ID: <1182814191.138864.80450@w5g2000hsg.googlegroups.com> Hi there! Has anyone made effort to try to create a python binding to a facial recognition software [1]? For those of you with some experience - would this be very hard? [1] An example: http://www.cs.colostate.edu/evalfacerec/ From gagsl-py2 at yahoo.com.ar Tue Jun 12 21:23:06 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 12 Jun 2007 22:23:06 -0300 Subject: Accessing global namespace from module References: <1181577768.728377.262720@m36g2000hse.googlegroups.com> <200706112119.16124.techlist@pathfinder.phys.utk.edu> <200706121737.45404.techlist@pathfinder.phys.utk.edu> Message-ID: En Tue, 12 Jun 2007 18:37:45 -0300, Reuben D. Budiardja escribi?: >> import sys >> from types import ModuleType as module >> >> def setup(namespace): >> plotModule = module('plot') >> for key,value in namespace.items(): >> if key[:2] != '__': >> setattr(plotModule, key, value) >> sys.modules['plot'] = plotModule >> > > Hm.. apparently this works for function but doesn't work for method :(. > Do you > know of any reason ? Do you mean, it doesn't work for classes? What kind of error do you get? -- Gabriel Genellina From kf9150 at gmail.com Thu Jun 21 16:14:58 2007 From: kf9150 at gmail.com (kf9150 at gmail.com) Date: Thu, 21 Jun 2007 20:14:58 -0000 Subject: sqlite newbie questions In-Reply-To: References: <1182453849.251898.127630@d30g2000prg.googlegroups.com> Message-ID: <1182456898.661723.274330@a26g2000pre.googlegroups.com> Thank you Carsten. Problem solved. From cieslak.dariusz at gmail.com Wed Jun 27 15:08:31 2007 From: cieslak.dariusz at gmail.com (cieslak.dariusz at gmail.com) Date: Wed, 27 Jun 2007 12:08:31 -0700 Subject: ANN: PyDAO - Python Hibernate-like Object-Relational Mapper Message-ID: <1182971311.915529.173050@k79g2000hse.googlegroups.com> PyDAO is very thin object-relational mapper similar to Hibernate (but much simpler). It's created to speed-up application development. It's very simple, but powerful, based on POPO (Plain Old Python Objects). http://aplikacja.info/PyDAO.html Main features: - can use any database that has DB-API interface (MySQLdb, psycopg tested) - can work without database at all (useful for early phases of development) - speeds up unit testing (dedicated in memory database) What is not handled: - automatic scheme generation - separate query language - automated handling of associations (replaced by filtering by foreign keys) Here's an example how to use PyDAO: class User: def __init__(self): self.id = None self.login = None self.password = None dao = pydao.InMemoryDao() # filling database user = User() user.login = "user1" user.password = "roh8OoPh" dao.save(user) # filtering based on example userSearch = User() userSearch.login = "user1" userList = dao.list(userSearch) # updating user.password = "eew8Me8g" dao.update(user) Enjoy! -- Dariusz Cieslak http://aplikacja.info - custom software systems From deets at nospam.web.de Thu Jun 14 12:03:24 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 14 Jun 2007 18:03:24 +0200 Subject: Method much slower than function? In-Reply-To: <1372ji3jvf3629b@corp.supernews.com> References: <1181781612.939800.238890@q19g2000prn.googlegroups.com> <1181799961.148499.32210@o11g2000prd.googlegroups.com> <1372ji3jvf3629b@corp.supernews.com> Message-ID: <5dd76cF33lmbeU1@mid.uni-berlin.de> Grant Edwards schrieb: > On 2007-06-14, Leo Kislov wrote: >> On Jun 13, 5:40 pm, ido... at gmail.com wrote: >>> Hi all, >>> >>> I am running Python 2.5 on Feisty Ubuntu. I came across some code that >>> is substantially slower when in a method than in a function. >>> >>>>>> cProfile.run("bar.readgenome(open('cb_foo'))") >>> 20004 function calls in 10.214 CPU seconds >>>>>> cProfile.run("z=r.readgenome(open('cb_foo'))") >>> 20004 function calls in 0.041 CPU seconds >>> >> I suspect open files are cached > > They shouldn't be. > >> so the second reader picks up where the first one left: at the >> of the file. > > That sounds like a bug. Opening a file a second time should > produce a "new" file object with the file-pointer at the > beginning of the file. It's a OS thing. Diez From andreas_eder at gmx.net Sun Jun 24 16:13:23 2007 From: andreas_eder at gmx.net (Andreas Eder) Date: Sun, 24 Jun 2007 22:13:23 +0200 Subject: The Modernization of Emacs: terminology buffer and keybinding References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182272495.990807.99110@a26g2000pre.googlegroups.com> <87tzt3ihev.fsf@kobe.laptop> <1182370216.961241.6960@n60g2000hse.googlegroups.com> <85zm2ufjpb.fsf@lola.goethe.zz> <1182372592.803332.288260@u2g2000hsc.googlegroups.com> <1182373919.262388.100740@c77g2000hse.googlegroups.com> <85r6o6fhkb.fsf@lola.goethe.zz> <1182375045.626510.188170@m36g2000hse.googlegroups.com> <85myyufgwj.fsf@lola.goethe.zz> <1182375528.985142.293900@q69g2000hsb.googlegroups.com> <1182545268.055596.228700@i38g2000prf.googlegroups.com> <1182547318.325617.16370@o11g2000prd.googlegroups.com> <1182657564.912472.55570@g4g2000hsf.googlegroups.com> Message-ID: <86645drtzw.fsf@eder.homelinux.net> Hi Twisted, >>>>> "Twisted" == Twisted writes: Twisted> * The operating system where you can do powerful stuff with a command Twisted> line and a script or two, but can also get by without either. (Windows Twisted> fails the former. Linux fails the latter.) Twisted> * For that matter, the operating system whose GUI takes the concept Twisted> behind OLE to its logical conclusion, and lets the user separately Twisted> choose and configure their text editing, this-editing, that-editing, Twisted> whosit-viewing, and the like components, and those components are used Twisted> in building more complex applications. All the alternatives would of Twisted> course adhere to a common interface for a particular sort of Twisted> component, of course. (An OO language like Java lends itself to this, Twisted> what with interfaces and inheritance and dynamic Twisted> class loading!) Have a look at Genera, the OS of the Lisp Machines. It offers all that and much more. Unfortunately it is almost non existent nowadays. 'Andreas -- Wherever I lay my .emacs, there's my $HOME. From gagsl-py2 at yahoo.com.ar Tue Jun 19 15:32:16 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 19 Jun 2007 16:32:16 -0300 Subject: Windows XMLRPC Service References: <1182137125.879556.319030@g37g2000prf.googlegroups.com> <1182235519.964013.146800@a26g2000pre.googlegroups.com> <1182275830.571891.278580@n15g2000prd.googlegroups.com> Message-ID: En Tue, 19 Jun 2007 14:57:10 -0300, escribi?: >> > #win32event.WAIT_TIMEOUT = 2 --- This just makes the loop >> > never execute because >> > # the WaitFor... part always returns 258 >> >> WAIT_TIMEOUT is 258. How do you see it is 2? >> py> import win32event >> py> win32event.WAIT_TIMEOUT >> 258 > > I meant here that *if* I set the WAIT_TIMEOUT to 2, then I see that > behavior. Ah, ok! I should have stated clearly that WAIT_TIMEOUT is a Windows predefined constant, not your desired timeout value. > Thank you again Gabriel. I'll post back with something complete. Yes, please, a working example would be nice for future readers... -- Gabriel Genellina From darder at gmail.com Sun Jun 10 17:44:00 2007 From: darder at gmail.com (Rafael Darder Calvo) Date: Sun, 10 Jun 2007 18:44:00 -0300 Subject: memory efficient set/dictionary In-Reply-To: <1181492122.508277.209500@n4g2000hsb.googlegroups.com> References: <1181485676.481109.234980@c77g2000hse.googlegroups.com> <1181492122.508277.209500@n4g2000hsb.googlegroups.com> Message-ID: <4234e23c0706101444v6669e10dk6c208873613b0ad9@mail.gmail.com> > > > Please recommend a module that allows persistent set/dict storage + > > > fast query that best fits my problem, > > > > What is the problem you are trying to solve? How many keys do you have? > > Corpus processing. There are in the order of billions to tens of > billions keys (64bit integers). > I would recommend you to use a database since it meets your requirements (off-memory, fast, persistent). The bsdddb module (berkeley db) even gives you a dictionary like interface. http://www.python.org/doc/lib/module-bsddb.html regards, Rafa From pruyu.chen at gmail.com Wed Jun 13 05:25:48 2007 From: pruyu.chen at gmail.com (Allen) Date: Wed, 13 Jun 2007 02:25:48 -0700 Subject: In C extension .pyd, sizeof INT64 = 4? In-Reply-To: <466f6ab7$0$19414$9b622d9e@news.freenet.de> References: <1181642594.963433.132750@g37g2000prf.googlegroups.com> <466efcdf$0$13674$9b622d9e@news.freenet.de> <1181696426.081185.63170@a26g2000pre.googlegroups.com> <1181699066.050774.302040@x35g2000prf.googlegroups.com> <466f6ab7$0$19414$9b622d9e@news.freenet.de> Message-ID: <1181726748.768278.233100@i38g2000prf.googlegroups.com> On 6 13 , 11 55 , "Martin v. L?wis" wrote: > > I used INT64 and initialize its value from PyArg_ParseTuple. > > The code is PyArg_ParseTuple(args, "l", &nValue). > > It should be PyArg_ParseTuple(args, "L", &nValue). > > That's still incorrect. For the L format flag, use PY_LONG_LONG, > not your own INT64 type. More generally: always use the type > documented in > > http://docs.python.org/api/arg-parsing.html > > Regards, > Martin PY_LONG_LONG is decleared as __int64 on windows. There is no difference. Regards, Allen Chen From gagsl-py2 at yahoo.com.ar Wed Jun 13 02:28:25 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 13 Jun 2007 03:28:25 -0300 Subject: Problem Inheriting from "str" Class References: <1181714476.330693.254340@q19g2000prn.googlegroups.com> Message-ID: En Wed, 13 Jun 2007 03:01:16 -0300, bcwhite at pobox.com escribi?: > I'm writing a program and want to create a class that is derived from > the "str" base type. When I do so, however, I have problems with the > __init__ method. When I run the code below, it will call my new > __init__ method when there is zero or one (value) parameter. However, > if I try to pass two parameters or a named parameter, then it dies > with an error indicating that it's actually trying to call the > "str:__init__" method instead. __init__ is rather useless for immutable types. You have to override __new__ instead. See -- Gabriel Genellina From kay.schluehr at gmx.net Sun Jun 24 04:24:44 2007 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Sun, 24 Jun 2007 01:24:44 -0700 Subject: is this a valid import sequence ? In-Reply-To: <1i0694u.1n6evsntoei0wN%aleax@mac.com> References: <4f97$467c254d$d443bb3a$9522@news.speedlinq.nl> <137qo1egg4v1k04@corp.supernews.com> <1i0694u.1n6evsntoei0wN%aleax@mac.com> Message-ID: <1182673484.969075.237870@w5g2000hsg.googlegroups.com> On Jun 24, 2:51 am, a... at mac.com (Alex Martelli) wrote: > Since that global statement is utterly useless > (it's impossible to read and understand any substantial amount of Python > code without realizing that accessing a variable not locally assigned > means you're accessing a global, so the "self-documenting" character > claimed for that redundancy is quite fallacious), it IS perfectly > suitable to take away, and so it's at least a serious imperfection. Allow me a pun: self is pretty self-documenting. With Python 3.0 we finally get even two declarations for accessing a name for assignment from an outer scope. Maybe the Python Zen should be altered in the following way: - Namespaces are one honking great idea -- let's do more of those! + Accessor declaratives are one honking great idea -- let's do more of those! Kay From kyosohma at gmail.com Sun Jun 24 19:17:36 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Sun, 24 Jun 2007 23:17:36 -0000 Subject: Changing sound volume In-Reply-To: References: Message-ID: <1182727056.516883.241390@o61g2000hsh.googlegroups.com> On Jun 23, 7:47 am, simon kagwe wrote: > Hi, > > I am playing sounds using the winsound module. Is there a way I can change the > volume? The docs don't mention anything about controlling the volume, so I doubt it's possible with winsound. However, I found this in the archives: http://mail.python.org/pipermail/edu-sig/2001-December/001899.html It's some kind of wrapper for Snack that allows you to mess with the volume. This site talks about Snack, winsound and another module: http://www.zak.co.il/gpl/misc/eng/pythonsound.html And finally a way that might work using ctypes: http://mail.python.org/pipermail/python-win32/2006-March/004436.html Mike From nick at craig-wood.com Mon Jun 18 15:30:05 2007 From: nick at craig-wood.com (Nick Craig-Wood) Date: Mon, 18 Jun 2007 14:30:05 -0500 Subject: avoid script running twice References: <4676AB35.7060500@chamonix.reportlab.co.uk> Message-ID: Tim Williams wrote: > You can also do this by holding a file open in write mode until the > script has finished. > > try: > open('lock.txt','w') > my_script() > except: > #print script is already running That only works under windows >>> f=open('lock.txt','w') >>> g=open('lock.txt','w') >>> f.write('hi') >>> g.write('ho') >>> f.close() >>> g.close() >>> open('lock.txt').read() 'ho' >>> The best cross platform way to create a lock is creating a directory. It is atomic on both windows and linux anyway. try: os.mkdir("lock") except OSError: print "locked!" else: try: do_stuff() finally: os.rmdir("lock") (untested) -- Nick Craig-Wood -- http://www.craig-wood.com/nick From kyosohma at gmail.com Thu Jun 21 11:49:56 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Thu, 21 Jun 2007 08:49:56 -0700 Subject: Adding Python to the path in Windows In-Reply-To: <1182440715.401553.37590@n60g2000hse.googlegroups.com> References: <1182437575.810986.205610@n2g2000hse.googlegroups.com> <1182439377.009844.320760@q75g2000hsh.googlegroups.com> <1182439800.148330.221600@p77g2000hsh.googlegroups.com> <1182440715.401553.37590@n60g2000hse.googlegroups.com> Message-ID: <1182440996.339856.260130@p77g2000hsh.googlegroups.com> On Jun 21, 10:45 am, kyoso... at gmail.com wrote: > On Jun 21, 10:30 am, k... at thenortheastgroup.com wrote: > > > > > On Jun 21, 11:22 am, kyoso... at gmail.com wrote: > > > > If your users aren't programmers, then why not just run Python over > > > the network? That's what we do at my place of employment. The only > > > machines that have Python actually installed are development machines. > > > > Mike > > > Mike, > > > I place the scripts on the server, but hadn't thought of placing an > > entire Python installation on the server. I just tried it and it > > seems to work. It shouldn't cause any problems? That might actually > > work out really well too. Thanks for the suggestion. > > We've been running python scripts over the network for more than a > year. The only issues I can think of is that at first it didn't always > find that weird Python dll file, but once we got that on the server, > that problem went away too. > > Mike I should probably mention that if you have some complicated GUI's, they will probably load slowly over the network. And I did notice that scripts using WMI and pyWin32 modules can be slower than they ought to be. Just something to keep in mind if you have a slow connection. We have a T1 out to a remote location and it's caused some minor issues using anything of that nature. Mike From techlist at pathfinder.phys.utk.edu Mon Jun 11 21:19:15 2007 From: techlist at pathfinder.phys.utk.edu (Reuben D. Budiardja) Date: Mon, 11 Jun 2007 21:19:15 -0400 Subject: Accessing global namespace from module In-Reply-To: References: <1181577768.728377.262720@m36g2000hse.googlegroups.com> <1181593775.957808.136050@m36g2000hse.googlegroups.com> Message-ID: <200706112119.16124.techlist@pathfinder.phys.utk.edu> On Monday 11 June 2007 17:10:03 Gabriel Genellina wrote: > En Mon, 11 Jun 2007 17:29:35 -0300, reubendb escribi?: > > On Jun 11, 3:30 pm, "Gabriel Genellina" > > > > wrote: > >> En Mon, 11 Jun 2007 15:18:58 -0300, reubendb > >> > >> escribi?: > >> > The problem is I don't define the functions AddPlot() and DrawPlots(). > >> > It's built into the python interpreter of the CLI version of the > >> > program I mentioned, and they are defined on the main script. I load > >> > the main script using something like "software -cli -s > >> > mainscript.py". > >> > In the mainscript.py I import myModule, but of course myModule does > >> > not have access to the functions defined in the global namespace of > >> > mainscript.py. > >> > >> Don't you have some import statements at the top of mainscript.py that > >> are > >> responsible for bringing AddPlot and DrawPlots into the current > >> namespace? > >> Import the same things in your second module. > > > > No, I *don't* have any import statement mainscript.py. When using this > > software's CLI, AddPlot and DrawPlots are available to me > > automagically from mainscript.py. Hence my question: How do I make > > this available from other module. Is there any way at all ? > > Yes: create your own module on-the-fly, using the recipe posted earlier by > John Krukoff. > If there are many functions, try enumerating them all: > > import sys > from types import ModuleType as module > > plotModule = module('plot') > for key,value in globals().items(): > if key[:2] != '__': > setattr(plotModule, key, value) > > sys.modules['plot'] = plotModule Great ! That seems to work, thanks a lot. One last question. Do I have to do this for ever script I write, or can I put this into separate file and "include" it somehow ? I am going to have several mainscripts.py, and all is going to import myModule that will need access to this plots subroutine. It'll be great if I can put this trick on a single file that is included by the main scripts, to avoid violating DRY principle. Thanks for all the help. RDB -- Reuben D. Budiardja From mina86 at tlen.pl Fri Jun 22 08:33:43 2007 From: mina86 at tlen.pl (Michal Nazarewicz) Date: Fri, 22 Jun 2007 14:33:43 +0200 Subject: The Modernization of Emacs: terminology buffer and keybinding References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182272495.990807.99110@a26g2000pre.googlegroups.com> <87tzt3ihev.fsf@kobe.laptop> <1182370216.961241.6960@n60g2000hse.googlegroups.com> <85zm2ufjpb.fsf@lola.goethe.zz> <1182372592.803332.288260@u2g2000hsc.googlegroups.com> <1182373419.522607.14500@g4g2000hsf.googlegroups.com> <1182374902.920671.171900@k79g2000hse.googlegroups.com> Message-ID: <87tzt0rwwo.fsf@erwin.mina86.com> Twisted writes: > On Jun 20, 5:03 pm, Kaldrenon wrote: >> I still have a good deal to learn, even of the basics, but I've toyed >> with it casually for a little bit (a total of two hours at most, but >> almost certainly less) and I already know enough that finding out how >> to do anything else IS trivial. It's not a program whose controls >> throw themselves at you, exactly, but with a touch of patience and a >> genuine interest in learning, it's not too bad. > > I don't know what software you're describing, but it's obviously not > emacs, unless there have been some HUGE changes to (at minimum) the > help and pane-navigation (er, excuse me, "window"-navigation) > controls... I don't know about *your* version of Emacs but in *my* version one can switch windows using mouse. I think that's pretty easy especially for beginners who are used to Windows. There was also a Help menu on menu bar but I disabled menu bar since keybindings are more convenient for me. -- Best regards, _ _ .o. | Liege of Serenly Enlightened Majesty of o' \,=./ `o ..o | Computer Science, Michal "mina86" Nazarewicz (o o) ooo +-------ooO--(_)--Ooo-- From needpassion at gmail.com Mon Jun 4 19:03:39 2007 From: needpassion at gmail.com (mike) Date: Mon, 04 Jun 2007 16:03:39 -0700 Subject: how to print out each single char from a string in HEX format? Message-ID: <1180998219.005688.323200@r19g2000prf.googlegroups.com> guys, I've researched python pretty much but still have no idea how to print out each single character from a string in HEX format? Hope someone can give me some hints. Thanks a lot. e.g. ###here is a string a='01234' ###how to print out it out in this way 0x31 0x31 0x32 0x33 0x34 From bignose+hates-spam at benfinney.id.au Fri Jun 22 01:01:07 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 22 Jun 2007 15:01:07 +1000 Subject: Google breaks international charset messages References: <1182337500.638044.63470@e9g2000prf.googlegroups.com> <46791592$0$5719$edfadb0f@dread14.news.tele.dk> <1182346499.123234.279880@e9g2000prf.googlegroups.com> <1182417604.446766.47660@e9g2000prf.googlegroups.com> <87odj8x4tt.fsf_-_@benfinney.id.au> Message-ID: <877ipwvazw.fsf@benfinney.id.au> "Evan Klitzke" writes: > Ironically, you're sending out us-ascii encoded emails as well. Yes, because I was (a) replying to a message already in that encoding, and (b) that encoding was sufficient to encode all the characters in my message. Where the original poster's message says that he posted a message with Chinese characters, and the message was munged by Google to the "us-ascii" charset. -- \ "It is seldom that liberty of any kind is lost all at once." | `\ -- David Hume | _o__) | Ben Finney From sk8in_zombi at yahoo.com.au Sat Jun 9 09:10:38 2007 From: sk8in_zombi at yahoo.com.au (Mr SZ) Date: Sat, 9 Jun 2007 23:10:38 +1000 (EST) Subject: running python scripts via crontab Message-ID: <501094.52491.qm@web54509.mail.yahoo.com> Hello all, I wrote a simple python script to send mail via smtp to my gmail acc.I can run it as python /home/phil/Desktop/smtp.py but when I add the same to my crontab as * * * * * /usr/bin/python2.5 /home/phil/Desktop/smtp.py ,it doesn't run.I checked the process by using top command and python did start a thread but died soon. I need some help here. The python script uses tls-lite lib to use tls over smtp. " life isn't heavy enough,it flies away and floats far above action" --------------------------------- How would you spend $50,000 to create a more sustainable environment in Australia? Go to Yahoo!7 Answers and share your idea. -------------- next part -------------- An HTML attachment was scrubbed... URL: From jr244 at kent.ac.uk Wed Jun 6 14:05:42 2007 From: jr244 at kent.ac.uk (J. Robertson) Date: Wed, 06 Jun 2007 19:05:42 +0100 Subject: Determinant of Large Matrix In-Reply-To: References: Message-ID: <4666f6e8$1_3@mk-nntp-2.news.uk.tiscali.com> James Stroud wrote: > Hello All, > > I'm using numpy to calculate determinants of matrices that look like > this (13x13): > > [[ 0. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1.] [snip] > But I have a feeling I'm exceeding the capacity of floats here. Does > anyone have an idea for how to treat this? Is it absurd to think I could > get a determinant of this matrix? Is there a python package that could > help me? > > Many thanks for any answers. > > James in order to verify that this result is correct, you could get the eigenvector and eigenvalues of this matrix (for example with numpy.linalg.eig) and check that they make sense; the determinant simply is the product of all the eigenvalues. gd luck From jorgen.maillist at gmail.com Tue Jun 12 05:14:43 2007 From: jorgen.maillist at gmail.com (Jorgen Bodde) Date: Tue, 12 Jun 2007 11:14:43 +0200 Subject: Adding a DB regs to a wx listbox In-Reply-To: <1181632484.631143.26370@z28g2000prd.googlegroups.com> References: <1181632484.631143.26370@z28g2000prd.googlegroups.com> Message-ID: <11e49df10706120214o4474bd75j4633140174118283@mail.gmail.com> self.list_box_1_copy.Append( your_item ) In the wxWidgets help: http://www.wxwidgets.org/manuals/2.8.0/wx_wxcontrolwithitems.html#wxcontrolwithitems And in the wxPython help: http://www.wxpython.org/docs/api/wx.ItemContainer-class.html Regards, - Jorgen On 6/12/07, Marcpp wrote: > Hi, I need add to a listbox a list of items extracted from a database. > This is that I've do: > > class tasques(wx.Frame): > def __init__(self, *args, **kwds): > .... > self.list_box_1_copy = wx.ListBox(self, -1, choices=[], > style=wx.LB_SINGLE|wx.LB_ALWAYS_SB) > ... > > How I add the list to choices? > > -- > http://mail.python.org/mailman/listinfo/python-list > From koara at atlas.cz Sun Jun 10 12:15:22 2007 From: koara at atlas.cz (koara) Date: Sun, 10 Jun 2007 09:15:22 -0700 Subject: memory efficient set/dictionary In-Reply-To: References: <1181485676.481109.234980@c77g2000hse.googlegroups.com> Message-ID: <1181492122.508277.209500@n4g2000hsb.googlegroups.com> Hello Steven, On Jun 10, 5:29 pm, Steven D'Aprano wrote: > > ... > How do you know it won't fit in main memory if you don't know the > overhead? A guess? You've tried it and your computer crashed? exactly > > Please recommend a module that allows persistent set/dict storage + > > fast query that best fits my problem, > > Usually I love guessing what people's problems are before making a > recommendation, but I'm feeling whimsical so I think I'll ask first. > > What is the problem you are trying to solve? How many keys do you have? Corpus processing. There are in the order of billions to tens of billions keys (64bit integers). > Can you group them in some way, e.g. alphabetically? Do you need to search > on random keys, or can you queue them and do them in the order of your > choice? Yes, keys in sets and dictionaries can be grouped in any way, order doesn't matter. Not sure what you mean. Yes, i need fast random access (at least i do without having to rethink and rewrite everything, which is what i'd like to avoid with the help of this thread :-) Thanks for the reply! From nagle at animats.com Fri Jun 22 02:46:01 2007 From: nagle at animats.com (John Nagle) Date: Thu, 21 Jun 2007 23:46:01 -0700 Subject: PEP 3107 and stronger typing (note: probably a newbie question) In-Reply-To: <1182448413.966430.299590@m36g2000hse.googlegroups.com> References: <1182448413.966430.299590@m36g2000hse.googlegroups.com> Message-ID: Kay Schluehr wrote: > That's simply because no one knows about the effects it has on Pythons > programming practices. Hence it is outsourced to "3rd party packages" > and these can be x-compilers as well that do all the inference stuff > and translate to Pyrex, C++, D or any other language having an > appropriate bridge. This stuff is simply beyond Python 3.0 and might > be addressed in subsequent versions such as Python 3.1 or Python 3.2 > when experiences are collected with different "annotations handlers". More interesting than optional annotations are the restrictions of ShedSkin, which forbid some changing of variable types. This allows some significant optimizations. If you accept the ShedSkin or Psyco restrictions, you get most of the performance advantages of strong typing without all the verbosity of explicit typing. PEP 3107 seems to add negative value to the language. The ability to add arbitrary attributes to parameters which can then be interpreted by some external library yet to be defined is a "l33t feature", one that's more cute than useful. Type-based dispatching is cute, but not really essential to Python. (PEAK, the main effort in that direction, seems to be defunct.) What we need are better implementations than CPython, not hokey attribute schemes bolted onto the language. We're seeing stuff go in that's easy to add to CPython, but not necessarily good for the language as a whole. John Nagle From tom at finland.com Sun Jun 3 03:47:48 2007 From: tom at finland.com (tom at finland.com) Date: Sun, 03 Jun 2007 07:47:48 GMT Subject: getting rid of leading zeros in float expotential Message-ID: Hi! I'm wondering whether there's an easy way to remove unnecessary leading zeros from my floating point number. realS = float(-1.25e-5) imgS = float(-7.6e4) print complex(realS, imgS) >> (-1.25e-005-76000j) I would like it to look like (-1.25e-5-76000j) From jackson at hotmail.com Tue Jun 5 22:16:53 2007 From: jackson at hotmail.com (Bill Jackson) Date: Tue, 05 Jun 2007 19:16:53 -0700 Subject: Which class's comparison function is called? Message-ID: For example, class A: def __init__(self,a): self.a = a def __eq__(self, other): return self.a == other.a class B: def __init__(self,b): self.b = b def __eq__(self, other): return self.b == other.b A(1) == B(1) ---> AttributeError: B instance has no attribute a B(1) == A(1) ---> AttributeError: A instance has no attribute b From the above, it seems that Python always uses the function defined by the class on the LEFT. However, I don't understand the following then: A(1) == 3 ---> AttributeError: 'int' object has no attribute a 3 == A(1) ---> AttributeError: 'int' object has no attribute a Can someone explain this? I expected 3 == A(1) to use the __eq__ function defined for 'int' objects. From peter.mosley at talk21.com Thu Jun 21 04:04:04 2007 From: peter.mosley at talk21.com (peter) Date: Thu, 21 Jun 2007 01:04:04 -0700 Subject: Python and (n)curses In-Reply-To: References: <1182211133.956524.160020@g4g2000hsf.googlegroups.com> <87y7igzapo.fsf@benfinney.id.au> <1182246189.210723.16280@w5g2000hsg.googlegroups.com> <1182325869.237652.157800@c77g2000hse.googlegroups.com> Message-ID: <1182413044.320261.69540@m36g2000hse.googlegroups.com> > You could write your own little console interface, tailored to > your needs, which is implemented using curses on Unix, and the > effbot's 'console' on Windows. Indeed, that's basically what I have done. Just can't help thinking how much simpler (and so less error prone) it would have been had there been some pre-existing crossplatform module. Peter From evan at yelp.com Mon Jun 18 13:44:48 2007 From: evan at yelp.com (Evan Klitzke) Date: Mon, 18 Jun 2007 10:44:48 -0700 Subject: avoid script running twice In-Reply-To: <9afea2ac0706181017n102c8a82xd93c0c6e819942dc@mail.gmail.com> References: <4676AB35.7060500@chamonix.reportlab.co.uk> <9afea2ac0706181017n102c8a82xd93c0c6e819942dc@mail.gmail.com> Message-ID: On 6/18/07, Tim Williams wrote: > On 18/06/07, Evan Klitzke wrote: > > On 6/18/07, Robin Becker wrote: > > > I wish to prevent a python script from running twice; it's an hourly job, but > > > can take too long. > > > > > > My simplistic script looks like > > > > > > > > > ....... > > > def main(): > > > fn = 'MARKER' > > > if os.path.isfile(fn): > > > log('%s: hourly job running already' % formatTime()) > > > else: > > > f = open(fn,'w') > > > f.write(str(os.getpid())) > > > f.close() > > > try: > > > work() > > > finally: > > > os.remove(fn) > > > > > > if __name__=='__main__': > > > main() > > > > > > but it occurs to me that I might be killed with prejudice during the long > > > running work(). Is there a smart way to avoid running simultaneously. > > > > Another method that you can use is to open up a socket on some > > predetermined port (presumably above 1024), and then have your program > > try to connect to that port and "talk" to the other program to > > determine whether or not to run (or whether to do some of the > > remaining work, etc.). > > You don't need to talk to the socket, a second script trying to create > a second socket on the same number will throw an exception and you can > exit the script cleanly without running a second copy. Just trying to bind to the port is the simplest thing to do if all you want to do is test if another instance of the script is running, because as Tim pointed out, you cannot bind to a port that another program is using. But there's also an advantage to spending the time to actual set up some sort of communication protocol using the port for two reasons: 1) if another program binds to the port, you'll be able to detect this and 2) it may be advantageous to split up the work among two (or more) processes, and you can do synchronization among the processes by having them communicate over the socket. For example, it may be the case that the first process can tell the second instance of the script "I'm almost done, if you want to help you can work on this part of the remaining problem." -- Evan Klitzke From showell30 at yahoo.com Sun Jun 3 22:38:07 2007 From: showell30 at yahoo.com (Steve Howell) Date: Sun, 3 Jun 2007 19:38:07 -0700 (PDT) Subject: Python, Dutch, English, Chinese, Japanese, etc. Message-ID: <206026.47204.qm@web33513.mail.mud.yahoo.com> The never-ending debate about PEP 3131 got me thinking about natural languages with respect to Python, and I have a bunch of mostly simple observations (some factual, some anecdotal). I present these mostly as food for thought, but I do make my own continent-by-continent recommendations at the bottom of the email. (My own linguistic biases are also disclosed at the bottom of the email.) Nationality of various technologists who use English to some degree (keywords in their languages, etc.): van Rossum -- Dutch-born, now lives in California Wall -- American Matz -- Japanese Ritchie -- American Stroustroup -- Danish-born, lives in Texas Gosling -- Canadian McCarthy -- American Torvalds -- Finnish-born (but family spoke Swedish), lives in Oregon Stallman -- American Berners-Lee -- English-born, did major work in Geneva A sampling of largish countries where English is fairly widely known: United States (82% of inhabitants speak it at home), Canada, United Kingdom, Australia, South Africa, India about China: largest country in the world by population Mandarin Chinese has 850 million speakers written Chinese dates back 4000 years, employs 5000 characters about India: second largest country in the world by population official languages: Hindi, English, and 21 others major software outsourcing center (anecdotal) Hindi is Indo-European language with distinctively different alphabet from English about Japan: 10th largest population world leader in robotics Japanese language mostly spoken in Japan major linguistic influences: Chinese, English, Dutch kanji = Chinese characters hiragana and katakana -- syllabic scripts Latin alphabet often used in modern Japanese (see wikipedia) some European alphabets: Spanish -- accented, includes digraphs ch and ll German -- accented French -- accented Italian -- accented, no J/K/W/X/Y Bringing Python to the world (all opinion here): Even in English-speaking countries, Python is greatly underutilized. Even in environments where programmers commonly use ASCII encoding, Python is greatly underutilized. Any focus on the current English/ASCII bias of Python should mostly concern Asia, due its large population, the 80/20 rule, the prevalence of different writing systems in large Asian countries, Asia's influence on technology in general, etc. (not to mention Ruby!) Asia: Python should be *completely* internationalized for Mandarin, Japanese, and possibly Hindi and Korean. Not just identifiers. I'm talking the entire language, keywords and all. Europe: Lobby EU for more funding for PyPy. Promote cultural acceptance of English-ized spelling in the context of writing software programs. North America: Marketing, marketing, marketing. South America: Focus first on translating Python documents, books, etc. to Spanish. Africa: write Python code for the XO-1 (aka $100 laptop) Australia: no worries Antartica: more Penguins than people My linguistic biases: 1) I speak American English natively. 2) I live in a very multilingual city. 3) I took 6 years of French in high school, but I get very little exposure to the language in my day-to-day life. 4) I hear a LOT of Spanish in day-to-day life, and I have first semester literacy. 5) I have never learned Arabic, Mandarin, Japanese, just to name a few major world languages. 6) I have written software that has been translated from English to other languages, but I only once been the primary person to do the actual internationalization, and it was a small project. 7) Lots of U.S.-based programmers that I have worked with speak English as their second or third language. ____________________________________________________________________________________ Yahoo! oneSearch: Finally, mobile search that gives answers, not web links. http://mobile.yahoo.com/mobileweb/onesearch?refer=1ONXIC From deets at nospam.web.de Mon Jun 11 03:27:35 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 11 Jun 2007 09:27:35 +0200 Subject: Python optimization (was Python's "only one way to do it" philosophy isn't good?) In-Reply-To: <9OVai.7525$u56.7287@newssvr22.news.prodigy.net> References: <1181368143.874341.273140@r19g2000prf.googlegroups.com> <9OVai.7525$u56.7287@newssvr22.news.prodigy.net> Message-ID: <5d4broF31klo5U1@mid.uni-berlin.de> > It's hard to optimize Python code well without global analysis. > The problem is that you have to make sure that a long list of "wierd > things", like modifying code or variables via getattr/setattr, aren't > happening before doing significant optimizations. Without that, > you're doomed to a slow implementation like CPython. > > ShedSkin, which imposes some restrictions, is on the right track here. > The __slots__ feature is useful but doesn't go far enough. > > I'd suggest defining "simpleobject" as the base class, instead of > "object", > which would become a derived class of "simpleobject". Objects descended > directly from "simpleobject" would have the following restrictions: > > - "getattr" and "setattr" are not available (as with __slots__) > - All class member variables must be initialized in __init__, or > in functions called by __init__. The effect is like __slots__, > but you don't have to explictly write declarations. > - Class members are implicitly typed with the type of the first > thing assigned to them. This is the ShedSkin rule. It might > be useful to allow assignments like > > self.str = None(string) > > to indicate that a slot holds strings, but currently has the null > string. > - Function members cannot be modified after declaration. Subclassing > is fine, but replacing a function member via assignment is not. > This allows inlining of function calls to small functions, which > is a big win. > - Private function members (self._foo and self.__foo) really are > private and are not callable outside the class definition. > > You get the idea. This basically means that "simpleobject" objects have > roughly the same restrictions as C++ objects, for which heavy compile time > optimization is possible. Most Python classes already qualify for > "simpleobject". And this approach doesn't require un-Pythonic stuff like > declarations or extra "decorators". > > With this, the heavy optimizations are possible. Strength reduction. > Hoisting > common subexpressious out of loops. Hoisting reference count updates > out of > loops. Keeping frequently used variables in registers. And elimination of > many unnecessary dictionary lookups. I won't give you the "prove it by doing it"-talk. It's to cheap. Instead I'd like to say why I don't think that this will buy you much performance-wise: it's a local optimization only. All it can and will do is to optimize lookups and storage of attributes - either functions or values - and calls to methods from within one specialobject. As long as expressions stay in their own "soup", things might be ok. The very moment you mix this with "regular", no-strings-attached python code, you have to have the full dynamic machinery in place + you need tons of guarding statements in the optimized code to prevent access violations. So in the end, I seriously doubt the performance gains are noticable. Instead I'd rather take the pyrex-road, which can go even further optimizing with some more declarations. But then I at least know exactly where the boundaries are. As does the compiler. > Python could get much, much faster. Right now CPython is said to be 60X > slower > than C. It should be possible to get at least an order of magnitude over > CPython. Regardless of the possibility of speeding it up - why should one want this? Coding speed is more important than speed of coding in 90%+ of all cases. The other ones - well, if you _really_ want speed, assembler is the way to go. I'm serious about that. There is one famous mathematical library author that does code in assembler - because in the end, it's all about processor architecture and careful optimization for that. [1] The same is true for e.g. the new Cell architecture, or the altivec-optimized code in photoshop that still beats the crap out of Intel processors on PPC-machines. I'm all for making python faster if it doesn't suffer functionality-wise. But until there is a proof that something really speeds up python w/o crippling it, I'm more than skeptical. Diez [1] http://math-atlas.sourceforge.net/faq.html#auth """ Kazushige Goto His ev5/ev6 GEMM is used directly by ATLAS if the user answers "yes" to its use during the configuration procedure on an alpha processor. This results in a significant speedup over ATLAS's own GEMM codes, and is the fastest ev5/ev6 implementation we are aware of. """ From carsten at uniqsys.com Fri Jun 1 08:52:08 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Fri, 01 Jun 2007 08:52:08 -0400 Subject: c[:]() In-Reply-To: <1180701557.3376.2.camel@dot.uniqsys.com> References: <1180504190.055427.173610@h2g2000hsg.googlegroups.com> <1180554872.3356.30.camel@dot.uniqsys.com> <465DF3DE.40404@cc.umanitoba.ca> <1180566831.239580.199300@m36g2000hse.googlegroups.com> <005401c7a31a$136f7fe0$240110ac@Muse> <135tobve86qj808@corp.supernews.com> <135tru124pie2b3@corp.supernews.com> <135tv1bjqgbmsc9@corp.supernews.com> <9qudnbFRU9QHJsLbnZ2dnUVZ_rKvnZ2d@speakeasy.net> <002f01c7a42d$f94f5d00$240110ac@Muse> <1180701557.3376.2.camel@dot.uniqsys.com> Message-ID: <1180702328.3376.5.camel@dot.uniqsys.com> On Fri, 2007-06-01 at 08:39 -0400, Carsten Haese wrote: > On Fri, 2007-06-01 at 02:19 -0700, Warren Stringer wrote: > > There is code that you type which persists and code that you type from a > > command line. Two completely different idioms. A credo inside the cell phone > > game industry is that you lose half your audience with each menu keystroke. > > That's how precious keystrokes are. > > Then why do have your users typing code into a cell phone? _.replace("do", "do you") self.drink(coffee) -- Carsten Haese http://informixdb.sourceforge.net From laurent.pointal at wanadoo.fr Thu Jun 14 13:01:41 2007 From: laurent.pointal at wanadoo.fr (Laurent Pointal) Date: Thu, 14 Jun 2007 19:01:41 +0200 Subject: In C extension .pyd, sizeof INT64 = 4? References: <1181642594.963433.132750@g37g2000prf.googlegroups.com> <466efcdf$0$13674$9b622d9e@news.freenet.de> <1181696426.081185.63170@a26g2000pre.googlegroups.com> <1181699066.050774.302040@x35g2000prf.googlegroups.com> <466f6ab7$0$19414$9b622d9e@news.freenet.de> <1181726748.768278.233100@i38g2000prf.googlegroups.com> Message-ID: <4671747b$0$27411$ba4acef3@news.orange.fr> Allen wrote: > On 6 13 , 11 55 , "Martin v. L?wis" wrote: >> > I used INT64 and initialize its value from PyArg_ParseTuple. >> > The code is PyArg_ParseTuple(args, "l", &nValue). >> > It should be PyArg_ParseTuple(args, "L", &nValue). >> >> That's still incorrect. For the L format flag, use PY_LONG_LONG, >> not your own INT64 type. More generally: always use the type >> documented in >> >> http://docs.python.org/api/arg-parsing.html >> >> Regards, >> Martin > > PY_LONG_LONG is decleared as __int64 on windows. There is no > difference. IMHO. Make your code platform independant and use your compiler capacities. If for an 'L' argument PyArg_ParseTuple requires a PY_LONG_LONG, then give it a PY_LONG_LONG and assign the parsed value into an INT64 after parsing. You dont know if PY_LONG_LONG or INT64 wil not be defined differently in the future, so use them where they are specified, do the assignment, and leave the compiler warn you if anything become invalid in the futur. My 2 cents. A+ Laurent. From bj_666 at gmx.net Sun Jun 3 16:18:07 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Sun, 03 Jun 2007 22:18:07 +0200 Subject: *Naming Conventions* References: Message-ID: In , Thorsten Kampe wrote: > Recently I wrote this code and noticed that I was completely lost in > giving these objects names to describe and distinguish them: > > for validanswer in validanswers: > if myAnswers.myanswer in myAnswers.validAnswers[validanswer]: > MyOptions['style'] = validanswer Wow, I know you don't want to talk about "spelling conventions" but here you are mixing many of them. :-) I don't know if it makes sense for your code, but maybe you can move the ``if`` condition into the class of `myAnswer` as overloaded ``in`` operator. Then this can be written as: for valid_answer in valid_answers: if valid_answer in my_answers: my_options['style'] = valid_answer > The 'tips' I got through some postings or articles on the net are: if > a function simply tests something and returns a boolean call it > > def is_(): > pass The other typical boolean test prefix is 'has_'. > like 'is_even'. > > Makes sense. The other thing I captured was to use something like > > def get_values(): > > ... Makes sense, too, but aren't all functions getting something? So you may reduce this to just `values()`. On the other hand there is the convention to name functions and methods as verbs that are "doing" something. Ciao, Marc 'BlackJack' Rintsch From steve at laniels.org Wed Jun 27 16:36:16 2007 From: steve at laniels.org (Stephen R Laniel) Date: Wed, 27 Jun 2007 16:36:16 -0400 Subject: Return name of caller function? In-Reply-To: <197779.8091.qm@web35210.mail.mud.yahoo.com> References: <20070626155646.GA28204@slaniel-laptop.itasoftware.com> <197779.8091.qm@web35210.mail.mud.yahoo.com> Message-ID: <20070627203616.GA30323@slaniel-laptop.itasoftware.com> On Wed, Jun 27, 2007 at 01:25:14PM -0700, Matthew Peter wrote: > Parsing the stack's tuple to get those attributes didn't feel reliable or pythonic. > I am likely overlooking something. Is there a brief example you could show me in the > context of using inspect to accomplish the goal I outlined above? The goal is using > a function and not a class. Thanks! The code below doesn't do the trick for you? #!/usr/bin/python import inspect def master(): print "I am the master" slave() def slave(): stack = inspect.stack() caller = stack[1][3] print "I am the slave; my caller was %s" % caller def main(): master() if __name__ == '__main__': main() -- Stephen R. Laniel steve at laniels.org Cell: +(617) 308-5571 http://laniels.org/ PGP key: http://laniels.org/slaniel.key From danb_83 at yahoo.com Sun Jun 3 19:20:53 2007 From: danb_83 at yahoo.com (Dan Bishop) Date: Sun, 03 Jun 2007 16:20:53 -0700 Subject: *Naming Conventions* In-Reply-To: References: Message-ID: <1180912853.513564.84060@p77g2000hsh.googlegroups.com> On Jun 3, 11:03 pm, Thorsten Kampe wrote: > Okay, > > I hear you saying 'not another naming conventions thread'. I've read > through Google and the 'naming conventions' threads were rather > *spelling conventions* threads. > > I'm not interested in camelCase versus camel_case or anything > mentioned in 'PEP 8 -- Style Guide for Python Code'. What I'm looking > for is hints or ideas how to name your variables and especially how to > name functions, methods and classes. In my code: * The most common form of a function/method name is verb_noun. Other common patterns are adjective_noun, noun_to_noun or noun2noun (for conversions), and noun_of_noun. * Classes nearly always have AdjectiveNoun names. * Loop indices often have single-letter names (typically i/j/k or x/ y), or names that are the singular form of the list name (e.g., "for ballot in self._ballots"). For iterating over files, I use "line". From bj_666 at gmx.net Mon Jun 25 14:10:25 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Mon, 25 Jun 2007 20:10:25 +0200 Subject: listing all property variables of a class instance References: <1182789455.818944.227660@g37g2000prf.googlegroups.com> Message-ID: In , Jay Loden wrote: > > Neil Cerutti wrote: >>> Is there a way to write a method that would list automatically >>> all the variables defined as a property (say by printing their >>> docstring and/ or their value), and only those variables? >> >> This is off the cuff. There's likely a better way. >> >> for k, v in MyClass.__dict__.iteritems(): >> if isinstance(v, property): >> print k, v.__doc__ >> > > The only way I could get this to work was to change the way the > properties were defined/initalized: That's because you iterate over the instance's `__dict__` and not over the *class* `__dict__` like Neil does. Ciao, Marc 'BlackJack' Rintsch From theller at ctypes.org Tue Jun 19 08:25:57 2007 From: theller at ctypes.org (Thomas Heller) Date: Tue, 19 Jun 2007 14:25:57 +0200 Subject: very simple shared dll with ctypes In-Reply-To: References: Message-ID: mclaugb schrieb: > I have created a simple windows small_dll.dll exporting a function that does > a computation using C and C++ classes which i wish to call from Python. I > have read lots of ctypes documentation but I still dont quite understand how > to call the function. > > As a test, I have written a much simpler mathematical function below to try > to get it to work from Python. > > I am trying to call this from python by: > >>>from ctypes import * >>>print cdll.small_dll.adder(c_double(5.343534),c_double(3.4432)) >>>2223968 > > Can someone give me a few tips to get going! You should assign the .restype and the .argtypes attributes to your function. That gives the the proper result, and you don't have to pack the arguments into c_double yourself. > The DLL declaration is below. > > #include > #if defined(_MSC_VER) > #define DLL extern "C" __declspec(dllexport) > #else > #define DLL > #endif > > DLL double adder(double a, double b){ > double c; > c=a+b; > return c; > } > from ctypes import * adder = cdll.small_dll.adder adder.restype = c_double adder.argtypes = c_double, c_double print adder(5.343534, 3.4432) Thomas From michele.simionato at gmail.com Tue Jun 5 11:17:42 2007 From: michele.simionato at gmail.com (Michele Simionato) Date: Tue, 05 Jun 2007 15:17:42 -0000 Subject: Basic Auth for simple web server In-Reply-To: <46657315$0$10618$4fafbaef@reader2.news.tin.it> References: <46657315$0$10618$4fafbaef@reader2.news.tin.it> Message-ID: <1181056662.161407.154970@q75g2000hsh.googlegroups.com> On Jun 5, 4:28 pm, Marco Aloisio wrote: > Hi, I'm a Python newbie; > I have to write a simple webserver, and I need to > implement a basic authentication as specified in the RFC2617. > I wonder if there is a Python library for doing that. > > Thanks! > > -- > Marco Aloisio Have a look at paste (http://pythonpaste.org/). For instance, to enable authentication for user foo, you can do the following from paste.auth.basic import AuthBasicHandler def only_for_foo(env, user, passwd): return user == 'foo' and passwd = 'bar' auth_app = AuthBasicHandler( myapp, 'app realm', only_for_foo) (where myapp is your WSGI application, of course). Michele Simionato From dak at gnu.org Wed Jun 20 17:40:30 2007 From: dak at gnu.org (David Kastrup) Date: Wed, 20 Jun 2007 23:40:30 +0200 Subject: The Modernization of Emacs: terminology buffer and keybinding References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182272495.990807.99110@a26g2000pre.googlegroups.com> <87tzt3ihev.fsf@kobe.laptop> <1182370216.961241.6960@n60g2000hse.googlegroups.com> <85zm2ufjpb.fsf@lola.goethe.zz> <1182372592.803332.288260@u2g2000hsc.googlegroups.com> <1182373919.262388.100740@c77g2000hse.googlegroups.com> <85r6o6fhkb.fsf@lola.goethe.zz> <1182375045.626510.188170@m36g2000hse.googlegroups.com> <85myyufgwj.fsf@lola.goethe.zz> <1182375528.985142.293900@q69g2000hsb.googlegroups.com> Message-ID: <85abuufgoh.fsf@lola.goethe.zz> Twisted writes: > On Jun 20, 5:35 pm, David Kastrup wrote: > >> But Emacs does not have a "clunky" interface. > > That's for the everyday novice-to-intermediate user to decide. And they do. > Your gnu.org email address (and attitude) clearly marks you as not a > normal user, and so your opinion doesn't count. Your email address and attitude marks you as an anonymous troll. -- David Kastrup, Kriemhildstr. 15, 44793 Bochum From nagle at animats.com Sun Jun 3 04:04:24 2007 From: nagle at animats.com (John Nagle) Date: Sun, 03 Jun 2007 01:04:24 -0700 Subject: M2Crypto-0.17 blocks python threads? In-Reply-To: References: <1180655909.402928.138290@i38g2000prf.googlegroups.com> Message-ID: <7xu8i.10371$4Y.3896@newssvr19.news.prodigy.net> Heikki Toivonen wrote: > reizes at gmail.com wrote: > >>I am having a problem with python threads and M2Crypto. It appears >>the M2Crypto used in multi-thread application blocks other threads >>from running: > > > This turned into https://bugzilla.osafoundation.org/show_bug.cgi?id=9401 > > Thanks for the report! That helps. I've been getting occasional stalls and timeouts in a multithreaded program that can have several M2Crypto operations going, and this is probably the explaination. John Nagle From pecora at anvil.nrl.navy.mil Thu Jun 28 08:48:10 2007 From: pecora at anvil.nrl.navy.mil (Lou Pecora) Date: Thu, 28 Jun 2007 08:48:10 -0400 Subject: Too many 'self' in python.That's a big flaw in this language. References: <1182942154.185461.89620@e9g2000prf.googlegroups.com> Message-ID: In article , "Jorgen Bodde" wrote: > I had the same feeling when I started, coming from a C++ background, I > forgot about self a lot, creating local copies of what should be an > assign to a class instance, or methods that could not be found because > I forgot 'self' . > > Now I am 'kinda' used to it, as every language has some draw backs > (you can't please all). But, what about something in between like only > using the dot (.) for a shorter notation? > > self.some_var = True > > Could become: > > .some_var = True > > Which basically shows about the same thing, but you leave 'self' out > of the syntax. Ofcourse it should not be allowed to break a line > between the dot and the keywords, else Python would never know what to > do; > > my_class() > .my_var = True > > Should not be parsed the same as; > > my_class().my_var = True > > Just a suggestion. I am pretty happy with self, but I could settle for > a shorter version if possible. > > - Jorgen Hmmm... I like this idea. Would you put a dot in the argument of a class method? def afcn(.,x,y): # stuff here ?? I still like it. self remains a wart on python for me after 5 years of use despite a deep love of the language and developers' community. -- -- Lou Pecora When I was a kid my parents moved a lot, but I always found them. (R.Dangerfield) From lew at noemail.lewscanon.com Sat Jun 9 07:49:32 2007 From: lew at noemail.lewscanon.com (Lew) Date: Sat, 09 Jun 2007 07:49:32 -0400 Subject: The Concepts and Confusions of Prefix, Infix, Postfix and Fully Functional Notations In-Reply-To: <1181358616.792797.97720@k79g2000hse.googlegroups.com> References: <1179936917.652372.24780@q69g2000hsb.googlegroups.com> <1180508453.226022.44230@q19g2000prn.googlegroups.com> <1181335574.107472.229370@x35g2000prf.googlegroups.com> <1181358616.792797.97720@k79g2000hse.googlegroups.com> Message-ID: Twisted wrote: > On Jun 8, 7:30 pm, "J?rgen Exner" wrote: >> xah... at gmail.com wrote: >> >> [nothing relevant to Perl] > > Perl?? Perl is even less relevant to Java than the original post, > which admittedly has some connection to pretty much all programming > languages. (Perl, on the other hand, has no connection to any known > programming language. ;) In particular, Perl code looks more like line > noise than like code from any known programming language. ;)) Hmm - I know of APL and SNOBOL. -- Lew From kelvin.you at gmail.com Thu Jun 7 07:17:34 2007 From: kelvin.you at gmail.com (=?gb2312?B?yMvR1MLkyNXKx8zs0cSjrM37vKvM7NHEsru8+7zS?=) Date: Thu, 07 Jun 2007 11:17:34 -0000 Subject: Why can not catch the inner exception Message-ID: <1181215054.826742.75930@n15g2000prd.googlegroups.com> Please see the follow code, I can not catch the exception " IOError" raised from shutil.copyfile() , why? try: if (DEST_TYPE & TYPE_FTP): fn = oname ftpc.UploadFile(f, fn) else: fn = os.path.join(dst, oname) shutil.copyfile(f, fn) .... other code.... except [IOError, FtpcException],why: num = 0 print >>sys.stderr, "can not copy '%s' to '%s': %s"%(f, fn, why) ERR_NUM += 1 I must do like this: try: if (DEST_TYPE & TYPE_FTP): fn = oname ftpc.UploadFile(f, fn) else: fn = os.path.join(dst, oname) try: shutil.copyfile(f, fn) except IOError: .... .... other code.... except [IOError, FtpcException],why: num = 0 print >>sys.stderr, "can not copy '%s' to '%s': %s"%(f, fn, why) ERR_NUM += 1 Thanks! From josiah.carlson at sbcglobal.net Mon Jun 18 15:45:30 2007 From: josiah.carlson at sbcglobal.net (Josiah Carlson) Date: Mon, 18 Jun 2007 12:45:30 -0700 Subject: Memory problem with Python In-Reply-To: <1182147350.690466.163980@d30g2000prg.googlegroups.com> References: <1182138694.632692.17590@x35g2000prf.googlegroups.com> <1182146807.758384.301000@j4g2000prf.googlegroups.com> <1182147350.690466.163980@d30g2000prg.googlegroups.com> Message-ID: <7dBdi.4945$bP5.2034@newssvr19.news.prodigy.net> Squzer Crawler wrote: > On Jun 18, 11:06 am, "sor... at gmail.com" wrote: >> On Jun 17, 8:51 pm, Squzer Crawler wrote: >> >>> i am developing distributed environment in my college using Python. I >>> am using therads in client for downloading wepages. Even though i am >>> reusing the thread, memory usage get increased. I don know why.? I am >>> using BerkelyDB for URLQueue, BeautifulShop for Parsing the webpages. >> Isn't the increased memory resulted from storing the already >> processed pages? >> >> Look first at all places where your code instantiates new >> objects - and make sure you don't keep references to such objects that >> are not needed anymore. >> >> Also, reusing threads has nothing to do with saving memory - but >> with saving on thread creation time, if I understand your problem >> description. > > what about the cyclic reference.. can i use GC in my program.. > > if so, please tell me how to implement.. i am calling the gc.collect() > at the enf of the fetching.. Will it reduce my program speed. Else in > which way i can call it..? Garbage collection should happen automatically as long as you are deleting references to objects you no longer need. If gc.garbage isn't empty, then you have unbreakable reference cycles. It seems more likely, as soring at gmail says, that you are keeping copies of the things you already parsed in memory. What you can do (if you aren't able to find the bug) is have a wrapper program that repeatedly starts up your url fetcher via os.system(). Then have your url fetcher close itself down every few hours. - Josiah From dlomsak at gmail.com Sat Jun 30 19:52:04 2007 From: dlomsak at gmail.com (dlomsak) Date: Sat, 30 Jun 2007 16:52:04 -0700 Subject: object references/memory access Message-ID: <1183247524.662884.153830@n60g2000hse.googlegroups.com> Hello, I have searched a good deal about this topic and have not found any good information yet. It seems that the people asking all want something a bit different than what I want and also don't divulge much about their intentions. I wish to improve the rate of data transfer between two python programs on the same machine. The project in question is a database server that I built (written in python) that works in conjunction with another python script for searching which is executed via Apache. Basically, I am serving a database but since the database is large, it remains in the memory of a server program. Upon submitting a search request, the search script is called by Apache. This search script makes a connection to the server, sends over the query and waits on the reply. Queries and records are represented by dictionaries and the database is a list of dictionaries. The only problem here is that for large returns, it takes more time and I'd like to transmit the data. The part that is slowing the data transmission down seems to be the fact that the data has to travel across a socket connection to be put back together on the other side. The server makes a list of dictionaries which represents the records that match the given criteria and then sends a pickle string of that object back to the client (the search script). What I'd like to do is somehow take the returned results of the search and send over a memory address through the socket and let the search script read the results directly from the server's memory rather than send it all through the sockets. There is one more solution which would work just as well for this application but would be less useful in general terms. The second method would involve some tricks with the python CGI module. I am fairly ignorant of how Apache works with the CGI module but here is what I'd like to do. I want to somehow let the server print out to the user's browser instead of the search script in order to cut out the time of sending the results over the socket. This sounds like it is not possible but I would like to know in greater detail how the CGI module and Apache work together such that the 'print' statements write out to the user's browser. Mainly, I'd like to know if there is any kind of descriptor or ID that can be passed and used by another process to print output to the user's browser instead of the script that Apache invoked. If there is not a good Pythonic way to do the above, I am open to mixing in some C to do the job if that is what it takes. I apologize if this topic has been brought up many times before but hopefully I have stated my intentions clearly enough for those with a higher knowledge of the topic to help. If the above are not possible but you have a really good idea for zipping large amounts of data from one program to another, I'd like to hear it. Thanks to all who take the time to read my request and also those with a response. From brianomorchoe at yahoo.co.uk Fri Jun 8 11:03:44 2007 From: brianomorchoe at yahoo.co.uk (Brain Murphy) Date: Fri, 8 Jun 2007 15:03:44 +0000 (GMT) Subject: Binary Message-ID: <564043.51460.qm@web27904.mail.ukl.yahoo.com> I am trying to make a programm that converts a decimal number like 79 to a binary number. where it asks you for a number then produces the binary. so far I have this: x = (input("Enter number: ")) b = 2.0 while x > 0: print x x = x/b I need it to show the remainder. like remainder 1 or 0 the put all of them in a list that is backwards. Any Ideas ___________________________________________________________ Yahoo! Answers - Got a question? Someone out there knows the answer. Try it now. http://uk.answers.yahoo.com/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From evan at yelp.com Fri Jun 22 03:41:29 2007 From: evan at yelp.com (Evan Klitzke) Date: Fri, 22 Jun 2007 00:41:29 -0700 Subject: "assert" annoyance In-Reply-To: <1182496726.460697.155530@n60g2000hse.googlegroups.com> References: <7xmyys368j.fsf_-_@ruckus.brouhaha.com> <1182494049.327182.205310@u2g2000hsc.googlegroups.com> <1182496726.460697.155530@n60g2000hse.googlegroups.com> Message-ID: On 6/22/07, Miles wrote: > On Jun 22, 2:45 am, "Evan Klitzke" wrote: > > On 6/21/07, Miles wrote: > > > > > On Jun 22, 1:31 am, Paul Rubin wrote: > > > > What I really want is for any assertion failure, anywhere in the > > > > program, to trap to the debugger WITHOUT blowing out of the scope > > > > where the failure happened, so I can examine the local frame. That > > > > just seems natural, but I don't see an obvious way to do it. > > > > > You could run the entire program through pdb: > > > ---- > > > #!/usr/bin/env python -m pdb > > > > > print "Hello!" > > > assert False > > > print "...world!" > > > ---- > > > > You can only pass one argument to a command that you invoke with the > > shebang sequence, so this won't work the way you wrote it. > > > > -- > > Evan Klitzke > > It actually does work on my system (OS X); I didn't realize it wasn't > portable. This sort of surprised me (in a good way), since I just took the one argument rule for granted. It's always bugged me that I couldn't do, say, #!/usr/bin/env python -O. So it's nice to see that OS X splits the arguments, even if this isn't completely portable! I did some research on this and it looks like a few other Unices do it too. If anyone is interested, there's a table documenting the behavior of different systems at http://www.in-ulm.de/~mascheck/various/shebang/#results Maybe I should start using a Mac ;-) -- Evan Klitzke From aaronwmail-usenet at yahoo.com Wed Jun 20 17:36:32 2007 From: aaronwmail-usenet at yahoo.com (aaronwmail-usenet at yahoo.com) Date: Wed, 20 Jun 2007 14:36:32 -0700 Subject: Edit Audio Using Python? In-Reply-To: <1182356488.189503.122180@g4g2000hsf.googlegroups.com> References: <1182353535.158899.128650@n2g2000hse.googlegroups.com> <1182356488.189503.122180@g4g2000hsf.googlegroups.com> Message-ID: <1182375392.825047.141120@w5g2000hsg.googlegroups.com> On Jun 20, 12:21 pm, Ultrus wrote: > Ah! I found this on the official website:http://www.python.org/doc/1.5.2p2/lib/module-audioop.html > > That should keep me occupied. If you think of anything interesting > however, I would be happy to know. :) I think you'll find that you have to put a lot of pieces together to manipulate audio -- it's all there, but it's not straightforward. I did it in my "skimpygimpy" audio components, which may help (especially if you ignore the stranger parts where I went off the deep end). Start by looking at the "waveTools.toneFile()" method, which, I think, writes out a wave file containing "concert A". http://skimpygimpy.sourceforge.net -- follow link to downloads... -- Aaron Watters === an apple every 8 hours will keep 3 doctors away. -- kliban From deets at nospam.web.de Sun Jun 24 09:44:35 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 24 Jun 2007 15:44:35 +0200 Subject: how to query/test the state of a qt widget? In-Reply-To: <1182644455.491518.97260@u2g2000hsc.googlegroups.com> References: <1182644455.491518.97260@u2g2000hsc.googlegroups.com> Message-ID: <5e7aq6F37in8eU1@mid.uni-berlin.de> raacampbell at gmail.com schrieb: > Hi, > > I'm writing a simple Python/Qt3 application and I am trying to write > some code in which the user presses a button and the program performs > action A or B depending upon the state of a pair of radio buttons. I > would therefore like Python to read the state of the buttons. I was > expecting this to be straightforward but I've not been able to work > out how to do it and searching on Google hasn't helped. Surely there's > a one-liner that will do what I want? It seems like an every-day sort > of problem. I'm after something like: > > if self.polPlotRadioButton.enabled==1: print "BLAH" > > I've found squish from www.froglogic.com but that seems over the top. > Possibly pythonqt.sourceforge.net has something that will solve my > problem but that wants Qt4 and at the moment I'm making heavy use of > matplotlib widgets and I've not worked out how to get them to > incorporate into a Qt4 app so I'm stuck with Qt3. > > Anyone know the answer? RTFM. The Qt-docs are extensive. And the QRadioButton-docs are pretty straight forward: http://doc.trolltech.com/3.3/qradiobutton.html#checked-prop So your code above should be if self.polPlotRadioButton.isChecked(): print "blah" Diez From doug at alum.mit.edu Fri Jun 29 13:01:17 2007 From: doug at alum.mit.edu (Douglas Alan) Date: Fri, 29 Jun 2007 13:01:17 -0400 Subject: Python's "only one way to do it" philosophy isn't good? References: Message-ID: Duncan Booth writes: >> A precondition of much of my Python code is that callers won't >> squirrel away large numbers of tracebacks for long periods of time. I >> can live with that. Another precondition of much of my code is that >> the caller doesn't assume that it is thread-safe. Another >> precondition is that the caller doesn't assume that it is likely to >> meet real-time constraints. Another precondition is that the caller >> doesn't need my functions to promise not to generate any garbage that >> might call the GC to invoked. > None of that is relevant. Of course it is. I said "large number of tracebacks" up there, and you promptly ignored that precondition in your subsequent counterexample. > Have you ever seen any code looking roughly like this? > def mainloop(): > while somecondition: > try: > dosomestuff() > except SomeExceptions: > handletheexception() Of course. > Now, imagine somewhere deep inside dosomestuff an exception is > raised while you have a file open and the exception is handled in > mainloop. If the loop then continues with a fresh call to > dosomestuff the traceback object will continue to exist until the > next exception is thrown or until mainloop returns. It's typically okay in my software for a single (or a few) files to remain open for longer than I might expect. What it couldn't handle is running out of file descriptors, or the like. (Just like it couldn't handle running out of memory.) But that's not going to happen with your counterexample. If I were worried about a file or two remaining open too long, I'd clear the exception in the mainloop above, after handling it. Python lets you do that, doesn't it? |>oug From dfabrizio51 at gmail.com Mon Jun 4 13:40:35 2007 From: dfabrizio51 at gmail.com (chewie54) Date: Mon, 04 Jun 2007 17:40:35 -0000 Subject: python for EE CAD program In-Reply-To: <1368ghphjgek559@corp.supernews.com> References: <1180964104.685598.21330@n4g2000hsb.googlegroups.com> <5cik0mF30e4avU1@mid.uni-berlin.de> <1180967112.693545.64270@p77g2000hsh.googlegroups.com> <5cinkhF30nk9aU1@mid.uni-berlin.de> <1180973771.580717.63840@m36g2000hse.googlegroups.com> <1368ghphjgek559@corp.supernews.com> Message-ID: <1180978835.775664.175780@h2g2000hsg.googlegroups.com> On Jun 4, 12:47 pm, Grant Edwards wrote: > On 2007-06-04, Chris Mellon wrote: > > > > >> Your opinions are noted, thank you, but I don't agree with > >> you. There are portions of the code that are under review for > >> patents and as such need to be protected. > > > For the record: This is not true. If you've already applied > > for the patent, you have as much legal protection as you will > > ever get. Also, since patents apply to methods and not to > > literal source, if you're trying to protect something > > patentable you have even less protection against analysis and > > disassembly than you would if you were trying to protect the > > copyright on the code. If you need to make a token effort to > > satisfy whatever legal hurdles are involved, shipping .pyc > > files (which py2exe and all the other packagers I'm aware of > > do) is just as effective as shipping executables compiled with > > C or C++. > > >> I'm investigating whether Python is the right language to use > >> for a commercial CAD application. While I think Python is a > >> great scripting language, there seems to limitations with > >> regards to packaging and distributing programs. > > > None that don't also exist in every other language in > > existence. These are fundamental issues of information theory, > > not language constraints. > > Especially since the alternative appears to be Java. Just like > Java, Python compiles to byte code that runs on a VM. > > If for some reason he's happy shipping Java VM byte-code and > not Python VM byte-code, then he can use Jython to generate > byte-code for the Java VM instead of for the Python VM. > Personally I think it's rather deluded to think that one is any > more secure than the other. > > -- > Grant Edwards grante Yow! What UNIVERSE is this, > at please?? > visi.com Honestly, thank you for your opinions and suggestions. I know this has been discussed before on this forum, but after reading the discussions, I'm still unsure about question 1. This is a big step and I want to make sure, if possible, I don't run into any show stoppers after many man hours of work. I will put the sensitive stuff and the datbase in a C extension and I think that solves question 2 for me. From george.sakkis at gmail.com Fri Jun 1 21:45:46 2007 From: george.sakkis at gmail.com (George Sakkis) Date: Sat, 02 Jun 2007 01:45:46 -0000 Subject: Comments appreciated on Erlang inspired Process class. In-Reply-To: References: <1180720090.725582.168150@m36g2000hse.googlegroups.com> Message-ID: <1180748746.848897.180550@g4g2000hsf.googlegroups.com> On Jun 1, 2:20 pm, "Brian L. Troutwine" wrote: > >http://wiki.python.org/moin/ParallelProcessing > > Ah, I'd forgotten about that page of the wiki; I hadn't seen it for a few > months. > > > Do you have any opinions about those projects listed on the above page > > that are similar to your own? My contribution (pprocess), along with > > others (processing, pp...), can offer similar facilities, but the > > styles of interfacing with spawned processes may be somewhat > > different. > > The interface was my most important design goal, in that I wanted it to be a > dead simple "Drop in some code and forget about it for a while. Retrieve the > results later as if you'd called the function yourself." sort of thing. > Secondly I wanted share nothing parallelism in order to avoid the nastier > bits of implementing concurrent code. Funny, I've been working on a similar library these days with the same primary goal, a minimal intuitive API. The closest to what I had in mind that I found in the parallel processing wiki was the Scientific.DistributedComputing package (actually there are no dependencies with the rest Scientific.* packages, the library comprises two modules and one script all in all). It's worth checking out and there's at least one idea I plan to copy (the "watchdog" thread monitoring if a process has died), but overall I found the API a bit clunky for my taste. So I rolled yet another parallel processing package and I'm glad to have a first working version ready at this point, exposing a single lightweight API and three distinct platform-independent implementations: one using multiple threads, one using multiple processes in one or more hosts (through PYRO) and one singlethreaded (for the sake of completeness, probably not very useful). I'll write up some docs and I'll announce it, hopefully within the week. George From bruno.desthuilliers at gmail.com Tue Jun 5 15:55:36 2007 From: bruno.desthuilliers at gmail.com (bruno.desthuilliers at gmail.com) Date: Tue, 05 Jun 2007 12:55:36 -0700 Subject: web development without using frameworks In-Reply-To: References: <20d6f8950706051201mba83194hcbc4d17cd2439cd@mail.gmail.com> Message-ID: <1181073336.850423.120500@q69g2000hsb.googlegroups.com> On Jun 5, 9:24 pm, Christoph Haas wrote: > On Tue, Jun 05, 2007 at 03:01:01PM -0400, Chris Stewart wrote: > > I'm interested in learning web based python without the use of fancy frameworks > > that are out there. I'm having a hard time coming up with resources and > > examples for this. Does anyone have anything that could be helpful? > > I'd say the only decent ways are either using a full-featured framework > (I favor Pylons) or write plain CGIs. Even for the later a look intohttp://wiki.python.org/moin/WebFrameworksmight be useful (I wouldn't > say that "web.py" is really a framework - and it's listed there). Or you > write plain-old CGIs with Python's "cgi" module. I have also started > like that but currently only use frameworks because the "cgi" module is > pretty limited (compared to what Perl offers) and for serious > applications not really the way to go. > I can only second Christoph's answer. Using bare CGI, you'll rapidly find you have to set up some common things like sessions, templating, url to actions dispatch etc - IOW, reinventing the (square) wheel. So unless your goal is to learn the "low-level" parts of web programming (which is a very legitimate goal - as far as I'm concerned, I'd like to see more 'web developpers' doing so), my advice is also to look for a simple, flexible, non-intrusive framework (web.py and Pylons come to mind). My 2 (euro) cents. From esj at harvee.org Sun Jun 10 20:25:14 2007 From: esj at harvee.org (Eric S. Johansson) Date: Sun, 10 Jun 2007 20:25:14 -0400 Subject: Python in the Mozilla world In-Reply-To: <695961.59234.qm@web33503.mail.mud.yahoo.com> References: <695961.59234.qm@web33503.mail.mud.yahoo.com> Message-ID: <466C966A.5000900@harvee.org> Steve Howell wrote: > --- "Eric S. Johansson" wrote: > >> Steve Howell wrote: >>> --- "Eric S. Johansson" wrote: >>> > http://www.voidspace.org.uk/python/weblog/arch_d7_2007_04_28.shtml#e702 >>>> interesting. Very interesting but I suspect the >>>> message is "don't hold your >>>> breath but don't give up hope." >>>> >>> Exactly. :) >> This is one of those things where a foundation, with >> a smart person for making >> really simple things should get some money from the >> foundation and get it built. > > Well, this is a case where smart people (including Jim > Hugunin) are getting some money from Microsoft, which > probably still has more dollars to spend than the > average foundation. And some really smart people in > the open source world (Miguel de Icaza, etc.) are > tracking to it, according to the article. this is good to know except I am somewhat cautious about the end result given that it's from Microsoft (explained below) As far as > "really simple things" goes, it doesn't really fit in > that category. I spent way too many years as a designer of software and then systems and may have found what may be a universal constant based on how people understand complexity and politics. In the beginning, almost every idea is simple. simplicity helps you get a rough go/no go estimation of project success. Simplicity helps you communicate the essential elements of the project to others so that you can get them to buy in (funding, resources). However as you develop use cases, the project gets more and more complex those in command issue to implement at the worst possible time because they are nervous about the increased complexity blowing up the budget. The really cool thing about complex systems is that it's like climbing a mountain. You never know when you reach the top until you are almost there. the simplicity doesn't emerge until you're almost done but it will emerge. If the apparent solution keeps getting more and more complex, then you really don't understand the problem and shouldn't even try to implement the solution. this is a pattern I can almost take to the bank. Simple idea, complex partial solution, simpler solution. only experience will tell you when you have gotten the most simplicity out of the solution possible. Now granted, some problems are inherently complex but if you contrast mid-understanding versus final solution, there will always be a big difference and complexity. I've always thought Microsoft interfaces were horribly horribly complex and I think it's due to two factors. The first is that they implement at the worst point in their understanding, and it's a barrier to entry for all third-party developers. If you don't agree with these ideas, that's cool. We can agree to disagree but this has been my experience over many years. > As much as I love Python, though, I still think the > future of browser-side programming for the next five > or ten years is Javascript, and I think the real > productivity gains are going to come when Javascript > libraries mature, it becomes more common knowledge > which libraries are best of breed, etc. that's really a pity. Although that is consistent with a recent announcement I thought regarding IBM and their funding of the Linux desktop accessibility. I personally hate the whole Ajax JavaScript crap because it is really inaccessible on multiple levels. a sardonic corner of my mind wonders if the productivity gains you mention it will be offset by the productivity losses caused by the unbelievably horrible debuggers and IDs available and users trying to use user applications with even worse user interfaces than we have today. But I will say, they will be prettier with all sorts of flashing colors and moving things. Skins! Don't forget the choice of skins you'll have for applications just by changing a cascading style sheet. Who needs usability when you can the color and type font of your user interface to match your whim...grumble I think your observation is far more correct than either of us want it to be. This is yet another good reason why folks should really push for a simple browser environment to replace JavaScript. I really don't think it's horribly hard but on the other hand, I don't understand the full environment (starting with a simple idea... :-) Thanks for the post. It's triggered some nice ideas in my head. From sjmachin at lexicon.net Sat Jun 2 21:56:36 2007 From: sjmachin at lexicon.net (John Machin) Date: Sat, 02 Jun 2007 18:56:36 -0700 Subject: Python 2.3 ODBC Datetime limitations In-Reply-To: References: <33cd6d8d0706011112w554ee6darea56f0977e9e3216@mail.gmail.com> <4661A4A9.60805@holdenweb.com> Message-ID: <1180835796.822148.300820@g37g2000prf.googlegroups.com> On Jun 3, 4:47 am, Tim Golden wrote: > Steve Holden wrote: > > YuePing Lu wrote: > >> Hello, > > >> Has any of you ever used Python odbc to retrieve data from a relational DB? > > >> I encountered a problem where it can't handle datetime _earlier than > >> _*1969*, and _later than _*2040*. It just returned some garbage strings > >> when I call str(my_date_object). > > > > Reading the documentation for the time module, you will see: > > > The epoch is the point where the time starts. On January 1st of that > > year, at 0 hours, the ``time since the epoch'' is zero. For Unix, the > > epoch is 1970. To find out what the epoch is, look at gmtime(0). > > > The functions in this module do not handle dates and times before the > > epoch or far in the future. The cut-off point in the future is > > determined by the C library; for Unix, it is typically in 2038. > > Maybe this is of use? > > http://timgolden.me.uk/python/win32_how_do_i/use-a-pytime-value.html which says (inter alia): """ If your datetime value is "sane" (ie is anywhere between 1970 and 2038) """ That's an interesting interpretation of "sane". FYI some real-world databases need to store dates before 1970 e.g. dates of birth of employees. The answer to the OP's question is easily determined by googling for 'dbidate' in this newsgroup, and is that (1) a dbidate object doesn't handle dates before 1970-01-01 or after The End of the Unix World in 2038 (not 1969/2040 as the OP posited). (2) the only solution if "insane dates" are required is to abandon the [outdated as Steve hinted] odbc module -- try adodb or mxODBC. From chris at shenton.org Tue Jun 5 09:44:07 2007 From: chris at shenton.org (Chris Shenton) Date: Tue, 05 Jun 2007 09:44:07 -0400 Subject: Logging: how to suppress default output when adding handlers? Message-ID: <86zm3eo6s8.fsf@Bacalao.shenton.org> I am setting up handlers to log DEBUG and above to a rotating file and ERROR and above to console. But if any of my code calls a logger (e.g., logging.error("foo")) before I setup my handlers, the logging system will create a default logger that *also* emits logs, which I can't seem to get rid of. Is there a way I can suppress the creation of this default logger, or remove it when I 'm setting up my handlers? Thanks. Sample code: import sys, logging, logging.handlers if len(sys.argv) > 1: logging.warning("Logging before setting handlers adds unwanted default logger") logging.getLogger().setLevel(logging.DEBUG) console = logging.StreamHandler() console.setLevel(logging.ERROR) console.setFormatter(logging.Formatter('%(levelname)-8s %(module)s: %(message)s')) logging.getLogger().addHandler(console) filelog = logging.handlers.RotatingFileHandler("/tmp/logtest2.log") filelog.setFormatter(logging.Formatter('%(asctime)s %(levelname)-8s %(module)s: %(message)s')) filelog.setLevel(logging.DEBUG) # NOP since default above is DEBUG, but OK logging.getLogger().addHandler(filelog) logging.debug("TEST debug") logging.warning("TEST warning") logging.error("TEST error") Sample runs, first without initial log call (good), then with one showing the default log messages in the mix (bad); I'm showing the console and tailing the logfile so they're mixed together but the timestamp indicates the file logs: chris at Bacalao:/tmp<103> tail -f /tmp/logtest2.log & chris at Bacalao:/tmp<118> python /tmp/logtest2.py 2007-06-05 09:36:27,234 DEBUG logtest2: TEST debug 2007-06-05 09:36:27,234 WARNING logtest2: TEST warning ERROR logtest2: TEST error 2007-06-05 09:36:27,239 ERROR logtest2: TEST error chris at Bacalao:/tmp<119> python /tmp/logtest2.py this gives ugly logger WARNING:root:Logging before setting handlers adds unwanted default logger DEBUG:root:TEST debug 2007-06-05 09:36:30,069 DEBUG logtest2: TEST debug WARNING:root:TEST warning 2007-06-05 09:36:30,072 WARNING logtest2: TEST warning ERROR:root:TEST error ERROR logtest2: TEST error 2007-06-05 09:36:30,073 ERROR logtest2: TEST error From simonkagwe at yahoo.com Mon Jun 4 09:17:15 2007 From: simonkagwe at yahoo.com (simon kagwe) Date: Mon, 4 Jun 2007 13:17:15 +0000 (UTC) Subject: Using pyTTS with other languages. Message-ID: Hi, I would like to create a TTS program for a local (Kenyan) language. I have installed pyTTS on my computer and it works perfectly with English sentences. However, my language is very different from English (sylabbles, pronounciation etc.) How can I go about having a TTS program that correctly speaks my language? Can pyTTS do this? I need all the help I can get. Regards, Simon. From whamil1 at entergy.com Tue Jun 12 09:01:11 2007 From: whamil1 at entergy.com (Hamilton, William ) Date: Tue, 12 Jun 2007 08:01:11 -0500 Subject: Excel file interface for Python 2.3? Message-ID: <588D53831C701746A2DF46E365C018CE01D2CABB@LITEXETSP001.etrsouth.corp.entergy.com> I'm in need of a module that will let me create Excel workbooks from within Python. Something like PyExcelerator, but it needs to work with Python 2.3. (A third-party limitation that I have no control over.) Can anyone point me to what I need? All my searches keep leading back to PyExcelerator. -- -Bill Hamilton From josiah.carlson at sbcglobal.net Mon Jun 4 03:18:51 2007 From: josiah.carlson at sbcglobal.net (Josiah Carlson) Date: Mon, 04 Jun 2007 00:18:51 -0700 Subject: magic names in python In-Reply-To: <1180939436.862957.127810@p77g2000hsh.googlegroups.com> References: <1180939436.862957.127810@p77g2000hsh.googlegroups.com> Message-ID: <9ZO8i.5956$u56.186@newssvr22.news.prodigy.net> per9000 wrote: > So my questions: > * is there a comprehensive list of magic names in python (so far i > know of __init__ and __repr__)? > * are these lists complete or can magic names be added over time (to > the python "core")? > * are magic names the same in different python versions? I don't believe that there is a full list of all __magic__ methods. The operator module has a fairly extensive listing of functions that call such methods, but I know that some have been left out. Among those that I remember off the top of my head while typing this message... __init__ __new__ __str__ __repr__ __len__ __nonzero__ __hash__ __cmp__ (__eq__, __ne__, __lt__, __gt__, __le__, __ge__) __getattr__ __setattr__ __delattr__ __getitem__ __setitem__ __delitem__ __iter__ __neg__ __not__ There's also the not-magic named, but still somewhat magic .next() method on iterators/generators. - Josiah From steve at REMOVE.THIS.cybersource.com.au Sat Jun 23 10:42:47 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sun, 24 Jun 2007 00:42:47 +1000 Subject: Adding method to a class on the fly References: <1182538969.522044.209560@q19g2000prn.googlegroups.com> <1182543862.369337.36880@z28g2000prd.googlegroups.com> <1182547065.295969.258820@g37g2000prf.googlegroups.com> <1182547724.690874.279230@g37g2000prf.googlegroups.com> <1182548694.545515.81060@e9g2000prf.googlegroups.com> <1182582129.462036.84560@m37g2000prh.googlegroups.com> Message-ID: On Sat, 23 Jun 2007 00:02:09 -0700, John Henry wrote: [snip] > Notice that the event handler for mouseClick to Button1 is done via > the function on_Button1_mouseClick. This is very simple and works > great - until you try to create the button on the fly. > > Creating the button itself is no problem. You simply do a: > > self.components['Button1'] = {'type':'Button', > 'name':'Button1', > 'position':(5, 35), > 'label':'Button1'} > > But then how do I create the on_Button1_mouseClick function? That depends on what it is supposed to do, but in general you want a factory function -- a function that returns functions. Here's a simple example: def mouseclick_factory(arg): def on_mouseClick(self, event): print "You clicked '%s'." % arg return on_mouseClick func1 = mouseclick_factory("Button 1") func2 = mouseclick_factory("this button") func3 = mouseclick_factory("something") Now let's try them out, faking the "self" and "event" parameters: >>> func1(None, None) You clicked 'Button 1'. >>> func2(None, None) You clicked 'this button'. >>> func3(None, None) You clicked 'something'. Obviously in a real application, self and event are important and can't be faked with None. Now, there are two ways of using that factory function in a class. Here is an example of both. class Parrot: def __init__(self, arg): self.bar = mouseclick_factory(arg) foo = mouseclick_factory("Foo") p = Parrot("bar") If you do it like this, there is a slight Gotcha to watch out for: as provided, foo is an instance method (and so has the self argument supplied automatically) but bar is not (and so needs the self argument to be supplied manually. >>> p.foo(None) # fake event argument You clicked 'Foo'. >>> p.bar(p, None) # self and fake event arguments You clicked 'bar'. If this is a problem -- and believe me, it will be -- you can use new.instancemethod to convert bar. [snip] > Now, knowing the new.instancemethod way, may be I can simplify the > above somewhat and improve the efficiencies but I still don't see how > one can do it without using the exec function. Rule 1: Never use exec. Exception for experts: If you know enough to never need exec, you can use it. Rule 1 is actually not quite true, but as an approximation to the truth, it is quite good. -- Steven. From exarkun at divmod.com Thu Jun 21 11:32:30 2007 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Thu, 21 Jun 2007 11:32:30 -0400 Subject: Conceptualizing Threading In-Reply-To: <1182438202.794266.279170@g4g2000hsf.googlegroups.com> Message-ID: <20070621153230.4947.557095607.divmod.quotient.3252@ohm> On Thu, 21 Jun 2007 08:03:22 -0700, JonathanB wrote: > >> You described how threads introduce a problem in your program -- that of >> generating a sequence of sequential identifiers -- but you didn't describe >> the problem that threads are solving in your program. Maybe you don't >> need them at all? What led you to threading in the first place? >> >> Jean-Paul > >Well, the problem I thought they would solve is ensuring everyone got >a sequential number. But I suppose they wouldn't solve that, since >from what I gather thread access is somewhat arbitrary. So then, here >is the crux of the issue. Worst case scenario, this program could be >accessed by 5-10 people at a time and I need each one to have the >current information. There are two places I know of that there might >be multi-access problems. Alright, so there are multiple short-lived processes. > >1) This program is so that we can track one team passing assignments >to another. Right now I have the names of everyone in team 2 in a >list. People from team one launch this program and the program grabs a >pointer (stored in a separate file). If person A launches the program >and person B launches the program before person A assigns an order, >they will both have the same pointer, so both orders will go to the >same person. And all of these processes have access to the same piece of mutable state (which happens to be stored on the filesystem). > >2) Each assignment has a distinct identifier, which increments by 1 >for each assignment (SR001001, SR001002, etc). Either these can be >assigned manually (the current method), or they can be assigned >automatically. If they are assigned manually, I need a way to show >them the most recent number (that would be easy), if they are assigned >automatically I need a way to save the number and pass the incremented >number along (just like the pointer). But I have the same problem here >as above. If two people launch the program at roughly the same time, >they will pull the same data. Since these assignments tend to come in >spurts, concurrent access is likely to be a problem. It sounds like a lock will do just fine to prevent the race condition present in the system. For example, using a class such as this one: http://twistedmatrix.com/trac/browser/trunk/twisted/python/lockfile.py#L57 you could write your code roughly like this: identifierLock = FilesystemLock("/path/to/shared/resource.lock") def getNextIdentifier(): while not identifierLock.lock(): time.sleep(0.1) try: # get the current identifier, increment the value in the # file, return the incremented value finally: identifierLock.release() and you won't have any issues with concurrent access messing up the identifier state. > >So, given those parameters (the rest of this program is a breeze, >there's a class for each person on Team 2 and the class holds some >info about them and a dictionary of assignments with the assignment >number for the key and a value of [assigner, numberAssigned], the only >other tricky thing for me has been logging because I've never had to >do much of it before), how can I prevent these problems? The only >thing that jumps out at me is a server/client model where a server >runs and compiles all the entries, spitting back the result to each >individual client. That way, all the working code lives in the server, >ensuring that the working thread always has the right information, >while the clients only pass data between the user and the server. But >I guess that isn't technically multi-threading is it. You could use a client/server as well, but the server still has to deal with concurrency somehow. It could do it in a manner similar to the one I described above, or it might make sense for it to do something entirely different - it depends on a lot of details about what the implementation of the server looks like. You're right that that isn't multi-threading, though. Jean-Paul From evan at yelp.com Wed Jun 20 04:00:18 2007 From: evan at yelp.com (Evan Klitzke) Date: Wed, 20 Jun 2007 01:00:18 -0700 Subject: Python IDE In-Reply-To: References: <1182249585.535675.143460@m36g2000hse.googlegroups.com> <1182259143.375798.283620@k79g2000hse.googlegroups.com> <5dq3n9F359hp0U1@mid.individual.net> Message-ID: On 6/19/07, Evan Klitzke wrote: > On 6/19/07, Bjoern Schliessmann > wrote: > > BartlebyScrivener wrote: > > > VIM > > > > *clap-clap* > > > > BTW, are there tutorials on the more arcane vim functions that come > > in handy with Python? > > I don't know of any vim functions that are python specific, but to me > the two somewhat arcane things that are really important to using vim > efficiently in programming in general are window splitting and > folding. Folding can be immensely useful for moving through files and > keeping important information visible. Ctags is also useful -- it > lets you jump to where the class/function under the cursor is defined. > Window tabbing is also new as of vim 7, but I prefer window splits. > You'll probably want to write some vim macros to help you use the > window splits more efficiently (e.g. to to move up a split and > maximize it in one key stroke). > > There's a script on vim.org for using the unittest module with the > :make command, which is also useful if you use that module a lot. And > of course if you build vim with python support, you can script vim > using python! > > Another thing I've noticed is that there are a couple of different > work flows that people have for testing code they're writing in vim. > The simplest way to run a script is with ":!python %" (sans quotes), > which runs the script with the output going to vim which pretends to > be a terminal. I think this is sort of suboptimal because vim isn't a > real terminal so some programs will act strangely this way. The > workflow I have is a screen session with vim in one (or more) > "windows" and another "window" that is just a shell, which I run my > scripts in. Another method that I've seen is to just background vim > with Ctrl-Z, run the program, and then foreground the vim session to > go back to the code. Either way, I think running your session in > screen is really, really useful because you can do a search through > the screen buffer for occurrences of certain words (I tend to do a > backwards search, with Ctrl-a [ ?search_term), which can help you > search through the output of your program quickly when things go awry. > IF you're a fan of screen (or want to use it), I have a pretty nifty > .screenrc that I use that shows the screen "windows" on a status line > at the bottom with some other nifty information (the hostname of the > machine screen is running on, the load information, and the time) as > well, plus support for 256 colors, which lets you use those nice 256 > color vim colorschemes. If you're interested you can grab it at > http://eklitzke.org/files/.screenrc Oh, one more that I forgot is Bicycle Repair Man. I haven't used it a lot, but it looks really interesting -- it's a tool designed to facilitate refactoring Python code. You can use it with vi or emacs. For those that are interested, you can read more about it at http://bicyclerepair.sourceforge.net/ -- Evan Klitzke From http Sat Jun 16 13:51:33 2007 From: http (Paul Rubin) Date: 16 Jun 2007 10:51:33 -0700 Subject: Python's "only one way to do it" philosophy isn't good? References: <1181368143.874341.273140@r19g2000prf.googlegroups.com> <1hzrsp4.7vjuav1aegg0tN%aleax@mac.com> <7SSci.35627$G23.1695@newsreading01.news.tds.net> Message-ID: <7xejkb23fe.fsf@ruckus.brouhaha.com> Neil Cerutti writes: > I vote for C++ as being astoundingly complex. But it provides > complex features, e.g.,the machanisms it provides to deal with > multiple inheritance, or generic, type-safe code. It gets off-topic but I'm not sure what advantage templates are supposed to have over ML-like polymorphism. From jeff at taupro.com Tue Jun 12 03:39:51 2007 From: jeff at taupro.com (Jeff Rush) Date: Tue, 12 Jun 2007 02:39:51 -0500 Subject: Calling for Python Writers/Authors Message-ID: <466E4DC7.5010906@taupro.com> For those who write books and articles, I've established a wiki page just as we already have a page for those who offer training services for Python. If you would like to be reachable by those needing writing services of various kinds, please add yourself to the list, along with some indication of what you prefer to work on, your portfolio of work and your experience level: http://wiki.python.org/moin/PythonWriters I'm open to creative ideas on how to format the information. A link to the page has been added to the sidebar menu under "Community". Jeff Rush Advocacy Coordinator From vel.accel at gmail.com Thu Jun 21 08:47:32 2007 From: vel.accel at gmail.com (D.Hering) Date: Thu, 21 Jun 2007 12:47:32 -0000 Subject: Downloading from a clean url In-Reply-To: References: <1182392457.751054.173500@n60g2000hse.googlegroups.com> Message-ID: <1182430052.176397.289060@q75g2000hsh.googlegroups.com> Evan Klitzke wrote: > On 6/20/07, D.Hering wrote: > > General: > > How do I download a page's data from a clean url. > > > > Specific: > > I'm using PyQt's QHttp and QUrl classes for requests and acquiring the > > response, but I can't figure out how to access a page's data without > > knowing the file of the url's path. For instance http://kde.org > > If the page is omitted, as in your example of http://kde.org, the page is / Right, but so far I'm not able to get a response unless I actually provide the actual page and it's extension in the path of the url. For instance /page.html or /this/path/to/page.html ...etc. > > > -- > Evan Klitzke From mccredie at gmail.com Fri Jun 1 19:10:55 2007 From: mccredie at gmail.com (Matimus) Date: Fri, 01 Jun 2007 23:10:55 -0000 Subject: Get ClassID of different versions of program with same ProgID In-Reply-To: <1180735905.211414.62360@k79g2000hse.googlegroups.com> References: <1180735905.211414.62360@k79g2000hse.googlegroups.com> Message-ID: <1180739455.034381.166190@i13g2000prf.googlegroups.com> Bummer you can't look into the registry. By convention the ProgID is named ... Also, usually there is a version independent ProgID that goes .. The version independent ProgID usually points to the newest version. It looks like that is what you are using. Many programs get away with not using those conventions, but I'm willing to bet that there is an 'AutoCAD.Application.14' and an 'AutoCAD.Application.??'. I don't know what will be there for 2004. Chances are that it is not '2004', but '15' (or something similar). So, you should be able to use those instead of the version independent one. Matt From listserver at tdw.net Mon Jun 18 09:41:30 2007 From: listserver at tdw.net (Tim Williams) Date: Mon, 18 Jun 2007 14:41:30 +0100 Subject: smtp server simulation using Python In-Reply-To: References: Message-ID: <9afea2ac0706180641u4c343485if1426f8454a69ea4@mail.gmail.com> On 17/06/07, William Gill wrote: > I have a (web) development computer w/o an SMTP server and want to test > form generated e-mail using a dummy SMTP server that delivers the mail > message to a file, or better yet, to a text editor instead of actually > sending it. Is it possible to extend the DebuggingServer class,and > override the process_message() method to accomplish this? If so, any > suggestions are appreciated. > Search the list archives for SMTPRIG.py :) Tim From showell30 at yahoo.com Tue Jun 12 19:35:31 2007 From: showell30 at yahoo.com (Steve Howell) Date: Tue, 12 Jun 2007 16:35:31 -0700 (PDT) Subject: SimplePrograms challenge In-Reply-To: Message-ID: <645504.94273.qm@web33511.mail.mud.yahoo.com> --- Steven Bethard wrote: > On 6/12/07, Steve Howell > wrote: > > --- Steven Bethard > wrote: > > > import itertools > > > > > > def iter_primes(): > > > # an iterator of all numbers between 2 and > > > +infinity > > > numbers = itertools.count(2) > > > > > > # generate primes forever > > > while True > > > > > > # generate the first number from the > > > iterator, > > > # which should always be a prime > > > prime = numbers.next() > > > yield prime > > > > > > # lazily remove all numbers from the > > > iterator that > > > # are divisible by prime we just > selected > > > numbers = > itertools.ifilter(prime.__rmod__, > > > numbers) > > > > > > I think that's 17-ish, though you could shrink > it > > > down by removing some > > > of the spaces. > > > > No, that's perfect. Do you want me to post it, or > do > > you want the honors? > > Go for it. > Done: http://wiki.python.org/moin/SimplePrograms (example 20) Thanks, George and Steve! ____________________________________________________________________________________ Need Mail bonding? Go to the Yahoo! Mail Q&A for great tips from Yahoo! Answers users. http://answers.yahoo.com/dir/?link=list&sid=396546091 From steven.bethard at gmail.com Wed Jun 13 16:07:35 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 13 Jun 2007 14:07:35 -0600 Subject: SimplePrograms challenge In-Reply-To: <87odjjfy75.fsf@merkury.smsnet.pl> References: <466F9329.2020306@gmail.com> <1181735763.199492.164760@q19g2000prn.googlegroups.com> <87odjjfy75.fsf@merkury.smsnet.pl> Message-ID: <46704E87.2090004@gmail.com> Rob Wolfe wrote: > Steven Bethard writes: > >>> I vote for example with ElementTree (without xpath) >>> with a mention of using ElementSoup for invalid HTML. >> Sounds good to me. Maybe something like:: >> >> import xml.etree.ElementTree as etree >> dinner_recipe = ''' >> >> 24slicesbaguette >> 2+tbspolive_oil > ^^^^^^^^^ > Is that a typo here? Just trying to make Thunderbird line-wrap correctly. ;-) It's better with a space instead of an underscore. >> 1cuptomatoes >> 1-2tbspgarlic >> 1/2cupParmesan >> 1jarpesto >> ''' >> pantry = set(['olive oil', 'pesto']) >> tree = etree.fromstring(dinner_recipe) >> for item_elem in tree.getiterator('item'): >> if item_elem.text not in pantry: >> print item_elem.text > > That's nice example. :) > >> Though I wouldn't know where to put the ElementSoup link in this one... > > I had a regular HTML in mind, something like: > > > # HTML page > dinner_recipe = ''' > Recipe > > > > > > > > >
        amtunititem
        24slicesbaguette
        2+tbspolive_oil
        1cuptomatoes
        1-2tbspgarlic
        1/2cupParmesan
        1jarpesto
        > ''' > > # program > import xml.etree.ElementTree as etree > tree = etree.fromstring(dinner_recipe) > > #import ElementSoup as etree # for invalid HTML > #from cStringIO import StringIO # use this > #tree = etree.parse(StringIO(dinner_recipe)) # wrapper for BeautifulSoup > > pantry = set(['olive oil', 'pesto']) > > for ingredient in tree.getiterator('tr'): > amt, unit, item = ingredient.getchildren() > if item.tag == "td" and item.text not in pantry: > print "%s: %s %s" % (item.text, amt.text, unit.text) >
        > > But if that's too complicated I will not insist on this. :) > Your example is good enough. Sure, that looks fine to me. =) Steve From lobais at gmail.com Tue Jun 5 16:59:18 2007 From: lobais at gmail.com (Thomas Dybdahl Ahle) Date: Tue, 05 Jun 2007 22:59:18 +0200 Subject: Strange errors on exit Message-ID: When I close my (gtk) program, I get errors like the below. It seams that when the interpreter shuts down, it sets every variable to None, but continues running the threads, (seems only in cases where they've just been asleep) I don't think this would be intended behavior? Exception in thread Thread-4 (most likely raised during interpreter shutdown): Traceback (most recent call last): File "/usr/lib/python2.4/threading.py", line 442, in __bootstrap File "/home/thomas/Programmering/python/skak/0.7/lib/pychess/System/ ThreadPool.py", line 49, in run File "/usr/lib/python2.4/Queue.py", line 89, in put File "/usr/lib/python2.4/threading.py", line 237, in notify exceptions.TypeError: exceptions must be classes, instances, or strings (deprecated), not NoneType Unhandled exception in thread started by Error in sys.excepthook: Original exception was: From Eric_Dexter at msn.com Mon Jun 4 19:36:33 2007 From: Eric_Dexter at msn.com (Eric_Dexter at msn.com) Date: Mon, 04 Jun 2007 16:36:33 -0700 Subject: Who uses Python? In-Reply-To: <1180985830.288414.208850@q69g2000hsb.googlegroups.com> References: <1180985830.288414.208850@q69g2000hsb.googlegroups.com> Message-ID: <1181000193.893781.242800@o5g2000hsb.googlegroups.com> On Jun 4, 2:37 pm, walterbyrd wrote: I am using python for csound.. You can use it inside of csound as well as using it on csound files... python makes text files very easy... I have to say that the price was very good and that is very important because I don't get funding from anywhere. You can also get programmers at a good cost for simple problems when you get stuck... through getacoder.com I was offered a $10 bid to solve one (I fixed it befour the bid was finished though) http://www.stormpages.com/edexter/csound.html > I mean other than sysadmins, programmers, and web-site developers? > > I have heard of some DBAs who use a lot of python. > > I suppose some scientists. I think python is used in bioinformatics. I > think some math and physics people use python. > > I suppose some people use python to learn "programming" in general. > Python would do well as a teaching language. > > I would think that python would be a good language for data analysis. > > Anything else? Finance? Web-analytics? SEO? Digital art? From __peter__ at web.de Thu Jun 21 09:59:12 2007 From: __peter__ at web.de (Peter Otten) Date: Thu, 21 Jun 2007 15:59:12 +0200 Subject: strip() 2.4.4 References: <1182432181.050589.5800@n2g2000hse.googlegroups.com> Message-ID: Nick wrote: > strip() isn't working as i expect, am i doing something wrong - > > Sample data in file in.txt: > > 'AF':'AFG':'004':'AFGHANISTAN':'Afghanistan' > 'AL':'ALB':'008':'ALBANIA':'Albania' > 'DZ':'DZA':'012':'ALGERIA':'Algeria' > 'AS':'ASM':'016':'AMERICAN SAMOA':'American Samoa' > > > Code: > > f1 = open('in.txt', 'r') > > for line in f1: > print line.rsplit(':')[4].strip("'"), > > Output: > > Afghanistan' > Albania' > Algeria' > American Samoa' > > Why is there a apostrophe still at the end? As others have already guessed, the problem is trailing whitespace, namely the newline that you should have stripped for line in f1: line = line.rstrip("\n") print line.rsplit(":", 1)[-1].strip("'") instead of suppressing it with the trailing comma in the print statement. Here is another approach that might work: import csv for row in csv.reader(f1, delimiter=":", quotechar="'"): print row[-1] that should work, too. Peter From aahz at pythoncraft.com Thu Jun 14 23:48:33 2007 From: aahz at pythoncraft.com (Aahz) Date: 14 Jun 2007 20:48:33 -0700 Subject: Python rocks References: <4661700a$0$19261$da0feed9@news.zen.co.uk> <1180807432.351720.123860@p47g2000hsd.googlegroups.com> <1180887490.024955.61380@p47g2000hsd.googlegroups.com> Message-ID: In article <1180887490.024955.61380 at p47g2000hsd.googlegroups.com>, George Sakkis wrote: >On Jun 2, 4:58 pm, a... at pythoncraft.com (Aahz) wrote: >> In article <1180807432.351720.123... at p47g2000hsd.googlegroups.com>, >> George Sakkis wrote: >>> >>>- Strings being iterable; unfortunately this will stay in Py3K. >> >> I'll repeat the comment I made on python-3000: >> >> "...string iteration isn't about treating strings as sequences of >> strings, it's about treating strings as sequences of characters. The >> fact that characters are also strings is the reason we have problems, >> but characters are strings for other good reasons." > >No, the reason we have problems is that far more often than not >strings are treated as atomic values, not sequences of smaller strings >or characters. A classic example is flatten(), where most people are >surprised if flatten([1, (3.14, 'hello')]) returns [1, 3.14, 'h', 'e', >'l', 'l', 'o']. Enh. That's not my experience -- the ability to slice, dice, and concatenate strings is intrinsic to their usefulness. >> Thing is, the fact that you can e.g. slice strings just like other >> sequence types creates the consequence that you can also iterate over >> strings -- moreover, some of us actually do iterate over strings (though >> of course we could if necessary create lists/tuples of characters). In >> the grand scheme of things, I rarely see people running into problems >> with iterating over strings. > >One class of problems is functions such as flatten() that expect "a >collection or an atom", with strings being typically considered >atomic. A second common pitfall are functions that expect file-like >objects but are given file names instead: > >def process_file(input_file): > for line in input_file: > do_stuff(line) > >process_file('/home/george/.bashrc') # oops That's a problem, yes, and it has oddly enough gotten worse since iterators were introduced into Python. Nevertheless, I have yet to see anyone suggest a mechanism for fixing this particular gotcha without creating more problems. Strings are just too useful as sequences. Moreover, my experience is that these kinds of problems don't show up all that frequently in practice. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "as long as we like the same operating system, things are cool." --piranha From len-l at telus.net Mon Jun 4 18:19:35 2007 From: len-l at telus.net (Lenard Lindstrom) Date: Mon, 04 Jun 2007 22:19:35 GMT Subject: magic names in python In-Reply-To: <1180939436.862957.127810@p77g2000hsh.googlegroups.com> References: <1180939436.862957.127810@p77g2000hsh.googlegroups.com> Message-ID: per9000 wrote: > Hi, > > I recently started working a lot more in python than I have done in > the past. And I discovered something that totally removed the pretty > pink clouds of beautifulness that had surrounded my previous python > experiences: magic names (I felt almost as sad as when I discovered > the strange pink worms that eat you in nethack, not to mention the > mind flayers - I really hate them). > > I guess all programming languages have magic names to some extent > (f.x. classes in the "C-family" have constructors that must have the > same name as the class (foo::foo) instead of foo.__init__). > > I just used a search engine a little on this topic and I found no > comprehensive list of magic names in python. > > So my questions: > * is there a comprehensive list of magic names in python (so far i > know of __init__ and __repr__)? > * are these lists complete or can magic names be added over time (to > the python "core")? > * are magic names the same in different python versions? > > I also tried (selected parts of(?)) the unittest package for use in > Zope and it seemed functions that I created for my test with the magic > prefix "test" were magic, other functions were not. > > So another question emerges: > * is the use of magic names encouraged and/or part of good coding > practice. > What is "magic" about __init__ and __repr__? They are identifiers just like "foo" or "JustAnotherClass". They have no special meaning to the Python compiler. The leading and trailing double underscores represent no special incantation. It is just a naming convention. So a number of method names like __init__ and __repr__ have a pre-defined usage. In every other respect they are just normal methods. They can be called directly. When dir() is called on a class they show up along with other method names. They can appear in a class declaration or added later after the class is created, just like other methods. They differ in that sometimes they will be called implicitly, such as when creating a new object or by the print statement. As to whether to use them: absolutely. __init__ is the preferred way to initialize a new object. Providing a __repr__ or __str__ method lets objects display descriptive and meaningful information about themselves in print statements and exception messages. And various other "special methods" allow for user defined versions of Python's built-in types. In fact most built-in types can be extended by subclassing and overriding their special methods. Back to "magic names". Python is a consistent language. What may be special cased - "magic" - in another language is handled normally with Python's general purpose dynamic type system. In fact I can think of only one name I would call "magic": __future__. from __future__ import does have special meaning to the Python compiler. It does more than import a module. -- Lenard Lindstrom From steve at REMOVE.THIS.cybersource.com.au Sat Jun 16 08:44:47 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sat, 16 Jun 2007 22:44:47 +1000 Subject: Python's "only one way to do it" philosophy isn't good? References: <1181368143.874341.273140@r19g2000prf.googlegroups.com> <1hzrsp4.7vjuav1aegg0tN%aleax@mac.com> Message-ID: On Fri, 15 Jun 2007 22:25:38 -0700, Alex Martelli wrote: > The "Spirit of C" section in the preface of the ISO Standard for C > phrases this principle as "Provide only one way to do an operation". Taken seriously, that rapidly goes to absurdity -- it would mean, for example, replacing all for loops with while loops. That's why I get mad at people who misquote (and often misunderstand) the Zen of Python's OOWTDI, misquoting it as Only One Way To Do It instead of One Obvious Way To Do It. There can be a hundred unobvious ways to do it, and it doesn't matter, so long as there is one obvious way. Needlessly restricting what a language includes leads to a language that does things badly. After all, all you really need is a virtual Turing Machine, and you can do anything Python or Lisp or Perl or C can do. Badly. I'm probably preaching to the converted, because I'm pretty sure Alex doesn't believe Python should be a minimalist language with _literally_ only one way to do anything. > Despite the phrasing variations, this commonality goes well with my > perception that, at their roots, Scheme, C and Python share one > philosophical underpinning (one that's extremely rare among programming > languages as a whole) -- an appreciation of SIMPLICITY AND UNIFORMITY as > language characteristics. Out of curiosity, what do you consider some of the worst offenders as far as overly complex and inconsistent languages go, and why? -- Steven. From evan at yelp.com Thu Jun 14 13:23:14 2007 From: evan at yelp.com (Evan Klitzke) Date: Thu, 14 Jun 2007 10:23:14 -0700 Subject: Moving items from list to list In-Reply-To: <1181838605.080038.162390@x35g2000prf.googlegroups.com> References: <1181838605.080038.162390@x35g2000prf.googlegroups.com> Message-ID: On 6/14/07, HMS Surprise wrote: > > Just wondered if there was some python idiom for moving a few items > from one list to another. I often need to delete 2 or 3 items from one > list and put them in another. Delete doesn't seem to have a return > value. I don't care which items I get so now I just use a couple of > pops or a for loop for more than two. I'm not sure if this is what you're asking, but if the elements in the list are contiguous you can just use list slicing/addition, like this: a = [1, 2, 3, 4, 5] b = [6, 7, 8, 9, 10] b = a[2:] + b a = a[:2] Now the contents of a and b respectively are a = [1, 2] and b = [3, 4, 5, 6, 7, 8, 9, 10]. -- Evan Klitzke From lukefrancomusic at gmail.com Sat Jun 2 14:12:13 2007 From: lukefrancomusic at gmail.com (lukefrancomusic at gmail.com) Date: Sat, 02 Jun 2007 18:12:13 -0000 Subject: Error message if there is a space in the source directory Message-ID: <1180807933.269404.208750@m36g2000hse.googlegroups.com> I am trying to learn Python. I am working on a simple backup program (code listed below). When using a source directory (the files to be backed up) without spaces in the title, my program works fine [see line 5]. If I try to access a directory with a space in the name the program fails with this error message: zip error:Nothing to do! (try: zip -qr C:\Backup\ \06.02.2007\BackUp at _10.03.57.zip . -i C:\test\test2\\) Backup FAILED I've been trying to find the answer for a while now but am stumped and don't know exactly what to look for. Any help would be greatly appreciated! 1. # C:\python25\programs\ 2. # File name: backup3debug.py 3. import os, time 4. # 1. The files and directories to be backed up are specified in a list. 5. source = [r'C:\test\test2\\'] 6. # 2. The backup must be stored in a main backup directory. 7. target_directory = r'C:\Backup\\' 8. # 3. The files are backed up into a zip file. 9. # 4. The name of the directory is the current date. 10. today = target_directory + time.strftime('%m.%d.%Y') 11. # The current time is the name of the zip archive. 12. now = time.strftime('BackUp at _%H.%M.%S') 13. # Create the subdirectory if it does not exist already. 14. if not os.path.exists(today): 15. os.mkdir(today) 16. print 'Successfully created directory', today 17. # The name of the zip file. 18. target = os.path.join(today, now + '.zip') 19. # 5. We use the standard ''zip'' command to put the files in a zip archive. 20. zip_command = "zip -qr %s %s" % (target, ' '.join(source)) 21. print zip_command 22. # Run the backup 23. if os.system(zip_command) == 0: 24. print 'sucessful backup to', target 25. else: 26. print 'Backup FAILED' When using a source like this on line 5: source = [r'C:\test\test 2\\'] which has a space in the title, the program will not work. ==================================================== Windows XP sp2 Dell Latitude D600 From grante at visi.com Fri Jun 1 10:32:08 2007 From: grante at visi.com (Grant Edwards) Date: Fri, 01 Jun 2007 14:32:08 -0000 Subject: c[:]() References: <1180504190.055427.173610@h2g2000hsg.googlegroups.com> <1180554872.3356.30.camel@dot.uniqsys.com> <465DF3DE.40404@cc.umanitoba.ca> <1180566831.239580.199300@m36g2000hse.googlegroups.com> <005401c7a31a$136f7fe0$240110ac@Muse> <135tobve86qj808@corp.supernews.com> <135tru124pie2b3@corp.supernews.com> <135tv1bjqgbmsc9@corp.supernews.com> <9qudnbFRU9QHJsLbnZ2dnUVZ_rKvnZ2d@speakeasy.net> <002f01c7a42d$f94f5d00$240110ac@Muse> Message-ID: <1360bf8jd7depad@corp.supernews.com> On 2007-06-01, Carsten Haese wrote: > On Fri, 2007-06-01 at 02:19 -0700, Warren Stringer wrote: >> There is code that you type which persists and code that you type from a >> command line. Two completely different idioms. A credo inside the cell phone >> game industry is that you lose half your audience with each menu keystroke. >> That's how precious keystrokes are. > > Then why do have your users typing code into a cell phone? I've decided the guy is trolling. Most of what he says is just nonsense. -- Grant Edwards grante Yow! Xerox your lunch at and file it under "sex visi.com offenders"! From sla29970 at gmail.com Tue Jun 26 01:39:48 2007 From: sla29970 at gmail.com (sla29970 at gmail.com) Date: Mon, 25 Jun 2007 22:39:48 -0700 Subject: Portable general timestamp format, not 2038-limited In-Reply-To: <7xbqf3lc7i.fsf@ruckus.brouhaha.com> References: <1182544384.709759.235300@o11g2000prd.googlegroups.com> <20070625133843.9e25d0ab.steveo@eircom.net> <82b5l4-tvh.ln1@zoogz.gregorie.org> <7xbqf3lc7i.fsf@ruckus.brouhaha.com> Message-ID: <1182836388.204373.231220@g37g2000prf.googlegroups.com> On Jun 25, 6:46 pm, Paul Rubin wrote: > TAI really does seem like the most absolute--if you are a user in > orbit or on Mars, then UTC timestamps will seem pretty meaningless and > artificial. TAI makes sense for clocks on the surface of the earth (at least until ion trap clocks and picosecond intercomparison become routine, at which point not even TAI tells what time it is for you), but clocks off the surface of the earth tick at rates which already differ nonlinearly from TAI by measurable amounts. From arkanes at gmail.com Sun Jun 10 10:43:21 2007 From: arkanes at gmail.com (Chris Mellon) Date: Sun, 10 Jun 2007 09:43:21 -0500 Subject: Python editors again (it's not the same old request) In-Reply-To: References: Message-ID: <4866bea60706100743n39d4165fwd591ee6f2573aa61@mail.gmail.com> On 6/10/07, Eric S. Johansson wrote: > I upgraded to version 9.5 and all of my tools which enabled me to program by > voice in Emacs are broken. it's one of those dagnabbit a moment's of life. > > What I am looking for is a Windows based Python Smart editor that uses specific > rich text edit controls as specified here: > > http://knowledgebase.nuance.com/view.asp?tnID=5104&sQuery=4247 > > Quoting from the article: > """ > A window is considered standard if its window class name is one of the following: > > Edit > > RichEdit > > RichEdit20A > > RichEdit20W > > RichEdit50W > > If the name is not one of those, then an edit control is still considered > standard if its window class name and window styles are similar to those of > standard edit controls. > > """ > > There is some other stuff in there about other classes that may be able to work > in so far, they haven't yield anything useful to me. Doesn't mean I won't keep > trying but it's more than a tad frustrating trying to root out some of these > magic numbers. Any help would be most appreciated. Actually, it would be > really nice if wxwindows and gtk used the standard classes underneath so > accessibility would be there semiautomatically on Windows but that's a different > conversation. > wx does (in large part), but most likely the problem is that the "rich text" control used in most editors is not the win32 rich text control, but instead Scintilla, which is designed for source editing and is much easier to use. Very few editors, of any kind, use the native win32 text control for source highlighting. wx does have (some) support for the accessibility features in win32, you might post a feature request on the wx bug tracker to add them to the wx platform bindings for Scintilla. The main reason editors don't use the standard control is for syntax highlighting and perhaps folding and margins, though, which I'm not sure are especially valuable to you. What kind of features makes a Python editor 'smart' for someone who's coding with a screen reader? From stuart.tett at gmail.com Mon Jun 18 00:39:44 2007 From: stuart.tett at gmail.com (stuart.tett at gmail.com) Date: Mon, 18 Jun 2007 04:39:44 -0000 Subject: PyRun_String with Py_single_input to stdout? Message-ID: <1182141584.410228.176350@c77g2000hse.googlegroups.com> I'm using PyRun_String with Py_single_input for a python interpreter embedded in my application. I'm using Py_single_input. Py_single input is what I want, but it seems to output to stdout. Before when I was using Py_eval_input I was able to grab the result so I could print it in a text box: PyObject *resultObject = PyObject_Str( rstring ); if( resultObject != NULL ) { //char *string = PyString_AsString( resultObject ); } But Py_eval_input is only for From doug at alum.mit.edu Thu Jun 21 15:25:37 2007 From: doug at alum.mit.edu (Douglas Alan) Date: Thu, 21 Jun 2007 15:25:37 -0400 Subject: Python's "only one way to do it" philosophy isn't good? References: <1181368143.874341.273140@r19g2000prf.googlegroups.com> <7x3b0nmkk6.fsf@ruckus.brouhaha.com> Message-ID: Steven D'Aprano writes: > On Wed, 20 Jun 2007 17:23:42 -0400, Douglas Alan wrote: >> Macros are a way to abstract syntax the way that objects are used to >> abstract data types and that iterators and generators abstract control, >> etc. > But why is the ability to abstract syntax good? It allows the community to develop language features in a modular way without having to sully the code base for the language itself. A prime example of this is how CLOS, the Common Lisp Object System was implemented completely as a loadable library (with the help of many macros) into Common Lisp, which was not an OO language prior to the adoption of CLOS. The fact that CLOS could be developed in a modular way allowed for a number of different groups to work on competing object systems. After some experience with the pros and cons of the various object systems, the developers of CLOS were able to incorporate most of the best ideas from the entire field and then get it adopted as a defacto standard. This allowed, for instance, the inclusion of multimethods, which are an extremely nice feature for modular code development. In prior Lisp dialects I had used, the object systems were more like the single-object dispatching OO system in Python, which is substantially inferior. The fact that the entire OO system in Common Lisp could be loaded as a module that is coded entirely within Common Lisp allowed for a large jump in the quality of its OO subsystem. > One criticism of operator overloading is that when you see X + Y you > have no real idea of whether it is adding X and Y together, or doing > something bizarre. Yes, and despite this, operator overloading is an essential feature for a modern language. (Java's lack of it notwithstanding.) > Now allow syntax to be over-ridden as well, and not only can't you tell > what X + Y does, but you can't even tell what it *means*. Maybe its a for- > loop, calling the function Y X times. (1) With operator overloading you have no idea what X + Y *means*. It could be feeding the cat, for all you know. If that turns out to be the case, you fire the programmer in question. Just because a language feature *can* be abused is no reason to leave it out of a language. Power always comes with responsibility, but we still need powerful programming languages. (2) In Lisp, you cannot redefine existing syntax (without modifying the standard library, which would be considered very rude), so the problem that you are talking about is moot. You can only add *new* syntactic constructs. I would suggest that any proposed syntax extension mechanisms for other languages behave like Lisp in this regard. > Sometimes, more freedom is not better. If you had a language that > let you redefine the literal 1 to mean the integer zero, wouldn't > that make it much harder to understand what even basic arithmetic > meant? But we're not talking about anything like this. E.g., in some dialects of Lisp it used to be possible to set the variable that contained the value for *true* to the value for *false*. If you actually did this, however, just imagine the havoc that it would wreak. So ultimately, this capability was removed. Alas, in Python, you can still do such a crazy thing! > But that doesn't mean I want a language where anything goes You are imagining something very different from what is proposed. Lisp-like macros don't allow "anything goes". |>oug From bbrown at speakeasy.net Fri Jun 22 00:57:34 2007 From: bbrown at speakeasy.net (Robert Brown) Date: Fri, 22 Jun 2007 00:57:34 -0400 Subject: PEP 3107 and stronger typing (note: probably a newbie question) References: <1182369568.941307.316260@p77g2000hsh.googlegroups.com> Message-ID: Stephen R Laniel writes: > Granted, in a dynamic language we won't always (maybe "won't > often") have a situation where the types are known this well > at compile time. But sometimes we will. And it would be nice > to catch these before the program even runs. > > So my question is: would bolting on "static type checking > when we can, no type checking when we can't" be too much > to ask? Common Lisp allows the programmer to optionally provide type declarations to improve readability or performance. Certain implementations of Common Lisp, such as cmucl and sbcl, check type declarations at compile time, employ type interence to generate efficient machine code, and insert run time checks when the compiler can't prove at compile time that variables have their declared types. From len-l at telus.net Wed Jun 6 01:52:07 2007 From: len-l at telus.net (Lenard Lindstrom) Date: Wed, 06 Jun 2007 05:52:07 GMT Subject: magic names in python In-Reply-To: References: <1180939436.862957.127810@p77g2000hsh.googlegroups.com> Message-ID: Steven D'Aprano wrote: > On Tue, 05 Jun 2007 18:08:31 +0000, Lenard Lindstrom wrote: > >> Steven D'Aprano wrote: >>> On Mon, 04 Jun 2007 22:19:35 +0000, Lenard Lindstrom wrote: >>> >>>> What is "magic" about __init__ and __repr__? They are identifiers just >>>> like "foo" or "JustAnotherClass". They have no special meaning to the >>>> Python compiler. The leading and trailing double underscores represent >>>> no special incantation. It is just a naming convention. >>> That's not quite true, as you point out: >> Disassemble the code object of a class statement. "__init__" is just an >> identifier, a Python name. So there is no "magic" here. > > It is not JUST an identifier, it is an identifier with a special, dare I > say *magic*, meaning. > > I suspect we have different ideas of what a "magic name" is. You seem to > be under the impression that magic names are a bad thing, and that > therefore one has to minimize their number. Hence you are glossing over > the differences and emphasizing the similarities between methods (say) foo > and __init__. > No, I don't consider magic in a programming language a bad thing. Overloaded operators is one feature I like in a language. Using special, or magic, methods to do this is elegant. And it would appear we are working with the same definition as regarding methods: a magic name method is an identifier recognized by the compiler as a special case. So a C++ constructor is a magic name. But by the same definition Python lacks magic methods. They have nothing to do with the compiler. They are a run-time feature. > I don't consider "magic name" in this content to be anything to be ashamed > of, so I'm not concerned about downplaying the differences. Yes, there are > significant similarities between __init__ and random methods you write > yourself, but the differences are equally, if not more, significant. > I'm not contesting that some identifiers have special meaning or are treated differently under certain conditions. Nor am I trying to hide the fact. But in the context of Python I don't find it remarkable. The Python type system is quite abstract, and class behavior is kept separate from the byte code interpreter. It is in the built-in types that special methods are given significance. And through these special methods one has access to the inner workings of Python's type system and modify the special behavior. So if that's magic, then it is a very approachable magic. > > >>>> So a number of method names like __init__ and __repr__ have a >>>> pre-defined usage. >>> That makes them magic, in the best possible way. >> I was careful to use the word "usage". Maybe I should have used >> "protocol" or "specification" here. A method named "write" is understood >> to have a particular definition and purpose. Is it "magic"? > > It could be, depending on the context. > > If we're discussing file objects compared to str objects, then file > objects have a method "write" and str objects don't, and the method is > just another method. > > But in the context of some third function, which takes a file-like object > with a "write" method, then yes it is magic, because any type of object > will work so long as it has a method "write" with the right semantics. Not > very much magic, but a little. > Okay. > >> These >> methods are simply callbacks. And yes, these callbacks make Python flexible. >> >>> >>>> In every other respect they are just normal methods. >>> That is *almost* true. Or, to put it another way, that is wrong. Some of >>> the double-underscore magic methods are automatically called on the class >>> instead of the instance, bypassing normal inheritance. >>> >> They exist as Python functions in the class dictionary. They have no >> hidden flags that distinguish them from other class level function >> attributes. > > They don't need special flags, because the Python compiler itself already > knows about the existence of them and takes special actions with them. By compiler I mean the parser and byte code generator, not the interpreter or built-in objects. And the compiler knows nothing about special Python methods. Neither does the byte code interpreter. By defining ones own meta-meta class one can make __init__ and __new__ unremarkable. > > [snip] > > >> >> [snip] >> In CPython an extension type can be written from >> scratch that treats special methods exactly as a new-style class does. >> Or an extension type can implement a completely novel approach. The >> point is, at some level, the machinery which defines special method >> "magic" is accessible to the programmer. So is it really "magic" or >> advanced technology? > > Does it matter? As Clarke said, any sufficiently advanced technology is > indistinguishable from magic... or to put it another way, as Larry Niven > did, any sufficiently advanced magic is indistinguishable from technology. > > Since I don't actually believe in magic, as in "wishing makes it so", of > course it is technology. But most Python programmers aren't capable of, or > have any interest in, writing extension types in C or hacking the compiler. > If certain magic behaviors depend on the compiler then that magic may be unavailable to the programmer. In Python assignment to None is now a syntax error. I would consider this real magic since Python has no way to declare compile time constants. But I can turn __build__ into a special method that is called at class creation. Special methods are not strictly limited to the ones already defined. And yes, in the sense that magic means using obscure language features to define new behavior, this is magic. Finally, nothing I have mentioned so far requires "hacking the compiler". > >> This comes down to the original posting not defining a "magic name". It >> does not mention what is so objectionable about __init__ and __repr__. I >> am claiming they are not as "magical" as they may first appear. > > I don't believe the Original Poster considers there is anything > objectionable about magic names like __init__ and __repr__, and even if he > does, I certainly don't. > I am not claiming that __init__ or __repr__ are objectionable. I am suggesting that calling them "magic names" in the context of Python is an exaggeration and overlooks the true power of the language. > Magic names in this context are those methods which have pre-defined > meanings to the compiler. That is mostly double-underscore methods like > __init__, but also methods like iterator.next(). If you ask yourself "What > methods do I have to over-ride to make a customized sub-class of a > built-in type?", the answer will include mostly magic names. If you ask > "What methods do I have to write for my class to work with Python > operators?", the answer will also include magic names like __add__, > __mul__, and __xor__. > I assumed you considered magic names as any pre-defined identifiers that have a special meaning within the language. I am guessing that's how others use the term. In this respect I agree that special methods are magic names. But in a programming language labeling a special case as "magic" is not descriptive. It says nothing about what makes the special case unusual or noteworthy. Is the quality unique to certain pre-defined identifiers? Does it make use of obscure language features? Is it a glaring inconsistency in an otherwise uniform language? So I would say to anyone encountering Python magic for the first time to reserve judgment until you understanding it. Then it may not seem so peculiar after all. Don't make assumptions based on other languages. -- Lenard Lindstrom From doug at alum.mit.edu Wed Jun 20 18:10:26 2007 From: doug at alum.mit.edu (Douglas Alan) Date: Wed, 20 Jun 2007 18:10:26 -0400 Subject: Python's "only one way to do it" philosophy isn't good? References: <1181368143.874341.273140@r19g2000prf.googlegroups.com> Message-ID: Robert Kern writes: >> The problem with Python's model is that you >> have to wait for a rather centralized process to agree on and >> implement such a feature. > No, you don't. Philip Eby has been working on various incarnations > of generic functions for some time now. The only thing new with 3.0 > is that they may be included in the standard library and parts of > the rest of the standard library may use them to implement their > features. Implementing generic functions themselves don't require > anyone to convince python-dev of anything. > http://python.org/pypi/simplegeneric/0.6 > http://peak.telecommunity.com/DevCenter/RulesReadme The first one doesn't do multiple dispatch. I'll have to have a look at the second one. It looks interesting. This link http://www.ibm.com/developerworks/library/l-cppeak2/ shows PEAK being used to do multiple dispatch based on predicates, but the code to implement the predicates is in strings! Sure, if you don't have macros, you can always use eval instead if you have it, but (1) doing so is ugly and dangerous, and (2) it's inefficient. Lisp implementations these days do fancy stuff (multiple dispatch, etc.) implemented as macros and yet typically end up generating code that runs within a factor of 2 of the speed of C code. In addition to having to code predicates in strings, using PEAK seems syntactically rather cumbersome. Macros would help solve this problem. Decorators seem to help to a large extent, but they don't help as much as macros would. Thanks for the pointers. |>oug From adam at volition-inc.com Thu Jun 28 17:46:55 2007 From: adam at volition-inc.com (Adam Pletcher) Date: Thu, 28 Jun 2007 16:46:55 -0500 Subject: Writing TGA image files? In-Reply-To: <1183066741.069248.25070@i13g2000prf.googlegroups.com> References: <7xir9cbm0g.fsf@ruckus.brouhaha.com> <7xejjzmk7u.fsf@ruckus.brouhaha.com> <7xy7i7xjl5.fsf@ruckus.brouhaha.com><1183044721.683930.131920@x35g2000prf.googlegroups.com> <1183066741.069248.25070@i13g2000prf.googlegroups.com> Message-ID: <893A44FF792E904A97B7515CE34191460102D730@volimxs01.thqinc.com> Does anyone have Python code for writing Targa (TGA) image files? Ideally, with options for bit-depth/alpha channel, and RLE compression, but I'm probably reaching there. PIL is read-only for TGAs, unfortunately, and so far I'm striking out on Google. Thanks. -- Adam Pletcher Technical Art Director www.volition-inc.com From horpner at yahoo.com Fri Jun 8 11:50:26 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Fri, 08 Jun 2007 15:50:26 GMT Subject: Working with fixed format text db's Message-ID: Many of the file formats I have to work with are so-called fixed-format records, where every line in the file is a record, and every field in a record takes up a specific amount of space. For example, one of my older Python programs contains the following to create a fixed-format text record for a batch of new students: new = file("new.dat", "w") if not new: print "Error. Could not open file new.dat for writing." raw_input("Press Return To Exit.") sys.exit(1) for s in freshmen: new.write(s.ssn.ljust(9)) new.write(s.id.ljust(10)) new.write(s.last[:16].ljust(16)) new.write(s.first[:11].ljust(11)) new.write(' '.ljust(10)) # Phone Number new.write(' '.ljust(1254)) # Empty 'filler' space. new.write('2813 ') new.write(s.major.ljust(5)) # Etc... Luckily, the output format has not changed yet, so issues with maintaining the above haven't arisen. However, I'd like something better. Is there already a good module for working with fixed format records available? I couldn't find one. If not, please suggest how I might improve the above code. -- Neil Cerutti When "yearn" was sung, the performers ounded like they were in a state of yearning. --Music Lit Essay From jmtulloss at gmail.com Tue Jun 19 19:33:14 2007 From: jmtulloss at gmail.com (Justin T.) Date: Tue, 19 Jun 2007 16:33:14 -0700 Subject: ARM cross compile - one last problem In-Reply-To: <1182275375.513700.46290@g4g2000hsf.googlegroups.com> References: <1182275375.513700.46290@g4g2000hsf.googlegroups.com> Message-ID: <1182295994.875288.85550@q75g2000hsh.googlegroups.com> On Jun 19, 10:49 am, jmtull... at gmail.com wrote: > Hello all, > > I've been trying to get Python to cross compile to linux running on an > ARM. I've been fiddling with the cross compile patches here:http://sourceforge.net/tracker/index.php?func=detail&aid=1597850&grou... > > and I've had some success. Python compiles and now all of the > extensions do too, but when I try to import some of them (time, > socket, etc.), they have trouble finding certain symbols. > Py_Exc_IOError and _Py_NoneStruct are the two I remember seeing. It > would appear that they are exported by libpython, which I believe is > statically linked into the python executable? That's where I start to > get confused. What part of python is breaking? Where should I be > looking for problems? > > Thanks a lot! > > Justin Alright, I looked into this a little more, and those symbols definitely exist in my compiled python executable. How are extensions linked to the python interpreter? Justin From mail at timgolden.me.uk Wed Jun 6 11:00:48 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Wed, 06 Jun 2007 16:00:48 +0100 Subject: Can os.remove followed by os.path.isfile disagree? In-Reply-To: <1181140547.279974.83550@q66g2000hsg.googlegroups.com> References: <1181140547.279974.83550@q66g2000hsg.googlegroups.com> Message-ID: <4666CC20.9020705@timgolden.me.uk> ppaterson at gmail.com wrote: > Can os.path.isfile(x) ever return True after os.remove(x) has > successfully completed? (Windows 2003, Python 2.3) As an afterthought, have you tried NTFS auditing, or directory monitoring, such as: http://timgolden.me.uk/python/win32_how_do_i/watch_directory_for_changes.html#use_readdirectorychanges to see the sequence of events on the directory? At least that might confirm whether you are seeing delete-create-delete or some other pattern. TJG From casevh at gmail.com Fri Jun 29 02:27:16 2007 From: casevh at gmail.com (casevh at gmail.com) Date: Thu, 28 Jun 2007 23:27:16 -0700 Subject: Looking for an interpreter that does not request internet access In-Reply-To: References: Message-ID: <1183098436.389332.45720@i13g2000prf.googlegroups.com> On Jun 25, 6:07 pm, James Alan Farrell wrote: > Hello, > I recently installed new anti-virus software and was surprised the > next time I brought up IDLE, that it was accessing the internet. > > I dislike software accessing the internet without telling me about it, > especially because of my slow dial up connection (there is no option > where I live), but also because I feel it unsafe. > > Can anyone recommend an interpreter that does not access the internet > when it starts (or when it is running, unless I specifically write a > program that causes it to do so, so as a browser)? > > James Alan Farrell It is a false alarm. The IP address 127.0.0.1 is a reserved address that means "this computer". It is more commonly known as "localhost". A server application can bind to 127.0.0.1 and it can be accessed by a client application running on the same computer. This is what IDLE is doing. It is not accessing the Internet. It is only using the IP protocol to communicate between different parts of the application. The anti-virus application should be configured to allow use of 127.0.0.1. But coming from a corporate IT world, I'm not surprised that it is not reasonably configured.... casevh From george.sakkis at gmail.com Sun Jun 3 19:00:10 2007 From: george.sakkis at gmail.com (George Sakkis) Date: Sun, 03 Jun 2007 23:00:10 -0000 Subject: Dict naming, global vs local imports, etc. [was Re: *Naming Conventions*] In-Reply-To: References: Message-ID: <1180911610.702985.215970@q75g2000hsh.googlegroups.com> On Jun 3, 4:32 pm, Steve Howell wrote: > I also still waste brain cycles on naming > dictionaries. Sometimes I name the dictionary after > the values it stores, sometimes after the keys it > uses, and sometimes after both. I was in the same boat but now I've pretty much settled to the convention `key2value`, e.g.: name2func = { 'sum' : sum, 'avg' : lambda values: sum(values) / float(len(values)) 'product' : lambda values: reduce(operator.mul,values,1), } word2positions = { 'dog' : [3, 45, 79, 840], 'cat' : [56, 97, 810], } At some point I was torn between this and the plural form, i.e. `keys2values`, but that's ambiguous in cases where each key or value is a collection, such as the 'positions' above. While we're at it, although it's not strictly a naming convention issue I still waste brain cycles on where to put the import statements that are used only once or twice in a module. Should (1) all imports be at the global scope at the top of the module, or (2) be imported in the function or method they are actually used ? Reasons for (1) --------------- - PEP-8 compatible. - Easy to see all external dependencies in one place. Reasons for (2) --------------- - Point of import closer to point of use; easy to notice if a given import is not used any more after refactoring. - Less name pollution. - Faster name lookup in locals (might make a difference for tight loops). I usually go for (1), at least until the number of global imports in the top remains in single digits. After some point though I often localize the standard library imports that are used only once or twice (the third-party and local application imports are almost always global). Any others that are not strictly PEP-8 compliant on this ? George From malaclypse2 at gmail.com Tue Jun 26 17:00:22 2007 From: malaclypse2 at gmail.com (Jerry Hill) Date: Tue, 26 Jun 2007 17:00:22 -0400 Subject: subprocess.Popen() problem In-Reply-To: <1182890310.087603.273390@n60g2000hse.googlegroups.com> References: <1182890310.087603.273390@n60g2000hse.googlegroups.com> Message-ID: <16651e80706261400o34178b22x7091cdf8e91888fc@mail.gmail.com> On 6/26/07, 7stud wrote: > p.stdin.write("hello") You need to add the linefeed, otherwise your mytest.py process is still waiting for you to finish typing. So, use this instead: p.stdin.write("hello\n") -- Jerry From deets at nospam.web.de Tue Jun 12 11:26:15 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 12 Jun 2007 17:26:15 +0200 Subject: Pattern Classification Frameworks? References: Message-ID: <5d7s8nF33dk4sU1@mid.uni-berlin.de> Evan Klitzke wrote: > Hi all, > > What frameworks are there available for doing pattern classification? > I'm generally interested in the problem of mapping some sort of input > to one or more categories. For example, I want to be able to solve > problems like taking text and applying one or more tags to it like > "romance", "horror", "poetry", etc. This isn't really my research > specialty, but my understanding is that Bayesian classifiers are > generally used for problems like this. I've had CRM114 recommended to > me, but as far as I can tell there aren't any python bindings for > this. I've utilized the CRM114 classifier from python. It wasn't too hard to come up with a simple wrapping that only needs the crm114 binary somewhere. The rest was dealt with in python. So if CRM114 fits you needs functionalitywise, you should go for it. Diez From martin at v.loewis.de Mon Jun 25 16:59:28 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Mon, 25 Jun 2007 22:59:28 +0200 Subject: Python SVN down? In-Reply-To: <5ealfjF37mjlvU1@mid.individual.net> References: <1182799060.612115.75490@n60g2000hse.googlegroups.com> <5ealfjF37mjlvU1@mid.individual.net> Message-ID: <46802CB0.3060309@v.loewis.de> > It _is_ down. Probably server maintenance. No, it's a bug. For some reason, the server restart after log rotation failed. I'm uncertain why - the manual restart right now worked without problems. Regards, Martin From steve at REMOVE.THIS.cybersource.com.au Sat Jun 23 13:56:51 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sun, 24 Jun 2007 03:56:51 +1000 Subject: Adding method to a class on the fly References: <1182538969.522044.209560@q19g2000prn.googlegroups.com> <1182543862.369337.36880@z28g2000prd.googlegroups.com> <1182547065.295969.258820@g37g2000prf.googlegroups.com> <1182547724.690874.279230@g37g2000prf.googlegroups.com> <1182548694.545515.81060@e9g2000prf.googlegroups.com> <1182582129.462036.84560@m37g2000prh.googlegroups.com> <1182614796.146337.290300@x35g2000prf.googlegroups.com> Message-ID: On Sat, 23 Jun 2007 09:06:36 -0700, John Henry wrote: >> >> > But then how do I create the on_Button1_mouseClick function? >> >> That depends on what it is supposed to do, but in general you want a >> factory function -- a function that returns functions. Here's a simple >> example: >> > > > Steven, > > May be I didn't explain it clearly: the PythonCard package expects to > see a function by the name of on_Button1_mouseClick. I don't do > anything to register the callback function. The package assumes that > there is a function by that name whenever I create a button named > Button1. So, if I don't use exec, how can I create a function by that > exact name? def mouseclick_factory(name): def function(self, event): print "You clicked '%s'." % name function.name = "on_%s_mouseClick" % name return function class Parrot: def __init__(self, name): function = mouseclick_factory(name) # as before method = new.instancemethod(function, self, self.__class__) setattr(self, function.name, method) And here it is in action: >>> p = Parrot("Button1") >>> p.on_Button1_mouseClick("event") You clicked 'Button1'. -- Steven. From gagsl-py2 at yahoo.com.ar Wed Jun 20 18:47:19 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 20 Jun 2007 19:47:19 -0300 Subject: need help with re module References: <46795CBA.9040807@gmail.com> <46798620$0$30507$c3e8da3@news.astraweb.com> Message-ID: En Wed, 20 Jun 2007 17:24:27 -0300, John Salerno escribi?: > Gabriel Genellina wrote: > >> py> from BeautifulSoup import BeautifulSoup >> py> chaine = """helloworldok""" >> py> soup = BeautifulSoup(chaine) >> py> soup.findAll(text=True) >> [u'hello', u'world', u'ok'] > > Wow. That *is* beautiful. :) Thanks to Leonard Richardson, the main author. -- Gabriel Genellina From Dave.Baum at motorola.com Fri Jun 22 12:41:21 2007 From: Dave.Baum at motorola.com (Dave Baum) Date: Fri, 22 Jun 2007 11:41:21 -0500 Subject: "assert" annoyance References: <7xmyys368j.fsf_-_@ruckus.brouhaha.com> Message-ID: In article <7xmyys368j.fsf_-_ at ruckus.brouhaha.com>, Paul Rubin wrote: > > What I really want is for any assertion failure, anywhere in the > program, to trap to the debugger WITHOUT blowing out of the scope > where the failure happened, so I can examine the local frame. That > just seems natural, but I don't see an obvious way to do it. Am I > missing something? I guess I could replace all the assertions with > function calls that launch pdb, but why bother having an assert > statement? I tend to run my programs with a -i option: python -i foo.py Then if an exception occurs, I can do: import pdb pdm.pm() and have a debug session at the point where the exception was raised. The "-i" shouldn't interfere with sys.argv since it is before the python file. Another option would be for your program to do something like: try: # put your code here except: import sys import pdb pdb.post_mortem(sys.exc_info()[2]) If an exception is raised, the debugger will be started using the appropriate traceback. (You don't need to import sys and pdb in the except block if they have already been imported.) Dave From tburdick at gmail.com Sun Jun 17 12:36:12 2007 From: tburdick at gmail.com (Thomas F. Burdick) Date: Sun, 17 Jun 2007 16:36:12 -0000 Subject: The Modernization of Emacs In-Reply-To: <1182093200.598418.218620@e9g2000prf.googlegroups.com> References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> Message-ID: <1182098172.305305.142180@n2g2000hse.googlegroups.com> For the love of dogs, Xah, try to keep up. Aquamacs is an Emacs distribution that, which not there yet, is at least half way between "classic" Emacs and a modern Mac UI. You sound ridiculous, like if you were complaining about Windows not being really graphical, based on experience with Windows-386 in the era when 95 was already around. On Jun 17, 5:13?pm, Xah Lee wrote: > [this post is a excerpt from > The Modernization of Emacs, Xah Lee, 2006-04 athttp://xahlee.org/emacs/modernization.html > ] > > The Modernization of Emacs > > ---------------------------------------- > THE PROBLEM > > Emacs is a great editor. It is perhaps the most powerful and most > versatile text editor. And, besides text editing, it also serves as a > email application, newsgroup application, ftp application, irc > application, web browser, shell interface, file management > application, programable calculator, calendar and personal info > management application, lisp language system, among other things. > These seemingly wild functionalities are employed in production daily > by a significant number of programers around the world. Some calls > emacs as a Operating System as a joke. (Technically it does not > qualify because a OS implies management of hardware.). > > If emacs is such a great and powerful text editor why almost nobody > knows about it? Vast majority of people who need to write will be more > than happy to use editors other than emacs. Ask a Microsoft Windows > user. She'll be more than happy to use Microsoft Word?. If he doesn't > have MS Word, he'll use NotePad? or WordPad?. If he is a programer, > most will be more than happy to use any of other graphical editors on > the Windows platform or any of the Integrated development > environment?. Same is true on other operating systems, and new editors > spring up here and there even though they don't have as much power or > flexibility as emacs. For example, there are NEdit, JEdit, Eclipse, > Xcode? , or the various associated with languages or third party > language software, such as Visual Basic or Borland C++. > > Many reasons can be made out of this. For example, emacs is not > bundled on popular operating systems such as Windows or Mac, which are > used by some 99% of computer users worldwide. Windows and Mac both > have simple text editors bundled that will satisfy majority of > computer users, which are non-professional computer users. (NotePad > and WordPad on Windows, TextEdit? on Mac) For the few professional > computer users, a majority will need a easy to use, yet powerful > editor that also does styled text, formatting, and sundry light > publishing needs such as table layout, simple line graphics drawing, > embedded images, math formulas. They will choose and adopt Microsoft > Word for their needs. The tiny percentage that might be interested in > emacs, are programers. Even among professional programers, a majority > shy away from emacs. > > A major difficulty among programers who do not use or like emacs, is > that emacs's user interface is rather esoteric, involving arcane > terminologies and keystrokes. This is in sharp contrast to the > thousands of software applications used today, where their User > Interface are similar and familiar to today's computer users. > > ---------------------------------------- > THE COMMON USER INTERFACE > > The following is a excerpt from the Wikipedia article on Common User > Access?: > > CUA was a detailed specification and set strict rules about how > applications should look and function. Its aim was in part to bring > about harmony between MS-DOS applications, which until then had > implemented totally different user interfaces. > > Examples: > > ? ? * In WordPerfect, the command to open a file was [F7], [3]. > > ? ? * In Lotus 1-2-3, a file was opened with [/] (to open the menus), > [W] (for Workspace), [R] (for Retrieve). > > ? ? * In Microsoft Word, a file was opened with [Esc] (to open the > menus), [T] (for Transfer), [L] (for Load). > > ? ? * In WordStar, it was [Ctrl]+[K]+[O]. > > ? ? * In Emacs, a file was opened with [Ctrl]+[x] followed by [Ctrl]+ > [f] (for find-file). > > Some programs used [Esc] to cancel an action, some used it to complete > one; WordPerfect used it to repeat a character. Some programs used > [End] to go to the end of a line, some used it to complete filling in > a form. [F1] was often help but in WordPerfect that was [F3]. [Ins] > sometimes toggled between overtype and inserting characters, but some > programs used it for ?paste?. > > Thus, every program had to be learned individually and its complete > user interface memorized. It was a sign of expertise to have learned > the UIs of dozens of applications, since a novice user facing a new > program would find their existing knowledge of a similar application > absolutely no use whatsoever. > > ---------------------------------------- > SIMPLE CHANGES > > In the following, i describe some critical changes that are also very > easy to fix in emacs. If emacs officially adopt these changes, i think > it will make a lot people, at least programers, like emacs and choose > emacs as their text editor. > > ? ? * Change the keyboard shortcut of Copy & Paste to ctrl-c and ctrl- > v as to be the same with all modern applications. > > ? ? * Change the undo behavior so that there is a Undo and Redo, as > the same with all modern applications. > > ? ? * Get rid of the *scratch* buffer. > > ? ? * Change the terminology of ?kill? to ?cut?, and ?yank? to > ?paste?. > > ? ? * Change the terminology of Meta key to Alt. > > ? ? * Make longlines-mode the default editor behavior for any file. > > Things emacs should do now, even though it eventually will do. > > ? ? * When opening a HTML document, automatically provide highlighting > of HTML, CSS, and Javascript codes. Similarly for other multi-language > files such as PHP, JSP, et al. This behavior must be automatic without > requiring user to customize emacs. > > Possible Documentation Change Proposals > > ? ? * Reduce the use of the word ?buffer? in the emacs documentation. > Call it ?opened file? or ?unsaved document?. > > ? ? * Switch the terminology of Window and Frame so it is more > standard. That is, Emacs's ?Window? should be called Panes or Frames. > While Emacs's ?Frame? should be termed Window. > > ? ? * Change the terminology of keybinding to ?keyboard shortcut? in > emacs documentation. Use the term keybinding or binding only in a > technical context, such as in elisp documentation. > > ? Xah > ? x... at xahlee.org > ?http://xahlee.org/ From NunezD at gmail.com Fri Jun 22 13:40:10 2007 From: NunezD at gmail.com (hiro) Date: Fri, 22 Jun 2007 17:40:10 -0000 Subject: comparing two lists and returning "position" In-Reply-To: <1182493019.795629.108860@w5g2000hsg.googlegroups.com> References: <1182481876.028589.71710@x35g2000prf.googlegroups.com> <7xvedg4n2d.fsf@ruckus.brouhaha.com> <467b624e$0$16271$c30e37c6@lon-reader.news.telstra.net> <1182493019.795629.108860@w5g2000hsg.googlegroups.com> Message-ID: <1182534010.884992.119690@u2g2000hsc.googlegroups.com> On Jun 22, 2:16 am, hiro wrote: > On Jun 22, 1:46 am, Charles Sanders > wrote: > > > Paul Rubin wrote: > > > > from itertools import izip > > > pos = map(dict(izip(l2, count())).__getitem__, l1) > > > or probably less efficiently ... > > > >>> l1 = [ 'abc', 'ghi', 'mno' ] > > >>> l2 = [ 'abc', 'def', 'ghi', 'jkl', 'mno', 'pqr'] > > >>> pos = [ l2.index(i) for i in l1 ] > > >>> print pos > > [0, 2, 4] > > > Charles > > Hey Guys thanks for the feedback and the suggestions. > Charles I got your implementation to work so many thanks for this. > > this is what I had so far > > for spam in l1: > for eggs in l2: > if spam == eggs: > print "kaka", spam, eggs > > so its almost working just need the index, I'll > continue playing with the nested loop approach for a bit more. > > Thanks once again guys Hi once again, Charles.. I have tried your approach in my data set l2 and it keeps crashing on me, bare in mind that I have a little over 10 million objects in my list (l2) and l1 contains around 4 thousand objects.. (i have enough ram in my computer so memory is not a problem) python 2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit (Intel)] on win32 error is : ValueError: list.index(x): x not in list when using Charles's pos = [ l2.index(i) for i in l1 ] print pos does anybody know of if I have to many data points ? the nested for loop approach seems to be working(still have get the index "position" returned though) Charles's approach works fine with less data. Cheers, -d From john at datavoiceint.com Fri Jun 15 11:21:24 2007 From: john at datavoiceint.com (HMS Surprise) Date: Fri, 15 Jun 2007 08:21:24 -0700 Subject: Html parser In-Reply-To: References: <1181916716.258484.74070@p77g2000hsh.googlegroups.com> Message-ID: <1181920884.791883.143310@m36g2000hse.googlegroups.com> Thanks, jh From bj_666 at gmx.net Mon Jun 18 14:49:10 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Mon, 18 Jun 2007 20:49:10 +0200 Subject: BeautifulSoup - extract the Message-ID: In <1182192028.173189.168910 at u2g2000hsc.googlegroups.com>, gcmartijn wrote: > I'm trying to extract something like this: > > codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/ > swflash.cab#version=7,0,19,0" width=640 height=400> > > > getflashplayer type=application/x-shockwave-flash width=640 height=400 > bgcolor=#000000 scale= showall> > > > > ==== > I don't know how I can get the param > > # below don't work > for test in soup.fetch('object'): > print test # nothing There's no `fetch()`. In [15]: soup.fetch('object') --------------------------------------------------------------------------- exceptions.TypeError Traceback (most recent call last) /home/new/ TypeError: 'NoneType' object is not callable > # nothing > print soup.findAll('param',{'name':'movie'}) Works for me: In [16]: soup.findAll('param', {'name': 'movie'}) Out[16]: [ ] > # nothing > print soup.findAll('object') This too: In [17]: soup.findAll('object') Out[17]: [ ] Ciao, Marc 'BlackJack' Rintsch From kyosohma at gmail.com Sat Jun 9 11:30:49 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Sat, 09 Jun 2007 15:30:49 -0000 Subject: Repository - file scanner In-Reply-To: <1181331239.609059.320740@g4g2000hsf.googlegroups.com> References: <1181331239.609059.320740@g4g2000hsf.googlegroups.com> Message-ID: <1181403049.098884.115770@q66g2000hsg.googlegroups.com> On Jun 8, 2:33 pm, HMS Surprise wrote: > Greetings, > > Could someone point my muddled head at a/the python repository. I know > that one exists but cannot find it again. In particular I am looking > for a standalone search tool that given a path searches files for a > text string. > > Thanks, > > jvh Are you looking for A.) a Python script to search for file names that match a given text string? B.) a script to search for a given text string within a text file? C.) a Python repository, as in the SVN/CVS area? Here's a couple scripts for finding files given a path: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52224 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/189973 And here's an interesting article on creating a Python "Find" utility: http://www.python.org/search/hypermail/python-1994q2/0116.html This link has a chapter from "Learning Python" by O'Reilly that talks about looking for words within files: http://www.oreilly.com/catalog/lpython/chapter/ch09.html The "repository" is here: http://svn.python.org/ Enjoy! Mike From http Sun Jun 24 21:19:11 2007 From: http (Paul Rubin) Date: 24 Jun 2007 18:19:11 -0700 Subject: how to sorted by summed itemgetter(x) References: <1182733105.118722.86390@e16g2000pri.googlegroups.com> Message-ID: <7xwsxs96gg.fsf@ruckus.brouhaha.com> Aldarion writes: > how to sorted by summed itemgetter(1)? > maybe sorted(items,key = lambda x:sum(x[1])) > can't itemgetter be used here? You really want function composition, e.g. sorted(items, key=sum*itemgetter(1)) where * is a composition operator (doesn't exist in Python). You could write: def compose(f,g): return lambda *a,**k: f(g(*a,**k)) and then use sorted(items, key=compose(sum,itemgetter(1))) or spell it out inline: sorted(items, key=lambda x: sum(itemgetter(1)(x))) I'd probably do something like: snd = itemgetter(1) # I use this all the time sorted(items, key=lambda x: sum(snd(x))) From danb_83 at yahoo.com Wed Jun 6 22:01:50 2007 From: danb_83 at yahoo.com (Dan Bishop) Date: Wed, 06 Jun 2007 19:01:50 -0700 Subject: lists - append - unique and sorted In-Reply-To: <1181143597.563633.241640@o5g2000hsb.googlegroups.com> References: <1181143597.563633.241640@o5g2000hsb.googlegroups.com> Message-ID: <1181181710.879767.234090@m36g2000hse.googlegroups.com> On Jun 6, 10:26 am, rhXX wrote: > hi, > > can i append a item to a list using criterias: > > - UNIQUE - if there already exist don't append > > and/or > > - SORTED - INSERT in the correct place using some criteria? > > tks in advance If you don't need the list to be sorted until you're done building it, you can just use: lst = sorted(set(lst)) From kj7ny at nakore.com Fri Jun 29 17:31:51 2007 From: kj7ny at nakore.com (kj7ny) Date: Fri, 29 Jun 2007 14:31:51 -0700 Subject: How do I remotely access Scheduled Tasks from Windows XP to Windows Server 2003? Message-ID: <1183152711.161151.285960@i13g2000prf.googlegroups.com> How can I access and manipulate Scheduled Tasks in Windows using Python? I have a Windows XP workstation running Python 2.4.4 using the win32all modules to control the windows services on multiple Windows 2003 servers. It works great. However, I also need to remotely collect the settings for the scheduled tasks (on those same Windows 2003 servers) and then manipulate those task settings. At the very least, I need to find out which ones are enabled and then be able to disable and re-enable those tasks at will. It would be better to be able to also detect the account each task runs as so that I could only disable selected tasks, but I'll any help I can get. Thanks, From deets at nospam.web.de Fri Jun 15 02:00:16 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 15 Jun 2007 08:00:16 +0200 Subject: using Mac OS X CoreGraphics via ctypes In-Reply-To: <1181876264.097017.283110@n15g2000prd.googlegroups.com> References: <1181876264.097017.283110@n15g2000prd.googlegroups.com> Message-ID: <5deo7iF34h5s2U1@mid.uni-berlin.de> Daniel schrieb: > I'm trying to implement a routine that converts a PDF document to > image files using ctypes and the Apple CoreGraphics library as per the > 'Splitting a PDF File' example on Apple's web site [0]. Unfortunately > I cannot use the CoreGraphics module used in that example because I'm > using Python 2.5 (AFAIK that module is only available in the system > default Python 2.3.5). There are three questions in the code snippet > below. Each problem area has been commented out in the example so it > runs through to the end. The code is obviously not complete, but it's > enough do demonstrate my problems so far. > > BTW, this is the only way I have found to convert a PDF (generated by > ReportLab) to an image that can be fed into a PyQt (v3) QPrinter > object. If anyone knows another way to gain access to the system print > services on Mac OS X using Python please do tell. Oh yes, I'd rather > not include PyObjC because I'm already packaging PyQt, and that would > make the resulting app a lot bigger. > # BEGIN CODE > from ctypes import cdll, c_void_p > from ctypes.util import find_library > > cglib = cdll.LoadLibrary(find_library('ApplicationServices')) > > # the next line causes a segfault - what's the right way to do this? > #GCS_RGB = cglib.kCGColorSpaceGenericRGB() Usually, things in the OSX lib that start with k* are a constant - not a function. As is this. Diez From kyosohma at gmail.com Wed Jun 6 17:00:19 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Wed, 06 Jun 2007 14:00:19 -0700 Subject: generating a wm5 executable In-Reply-To: <1181153971.483189.183610@x35g2000prf.googlegroups.com> References: <1181153971.483189.183610@x35g2000prf.googlegroups.com> Message-ID: <1181163619.661841.287260@z28g2000prd.googlegroups.com> On Jun 6, 1:19 pm, Marco wrote: > Hi, > I'm quite a newbee on Python and have started developing apps on > PythonCE. > > My .pyc files are running fine under windows mobile 5 but I'm a bit > stuck on how to generate single file executable packages under such > platform, nor I've found a lot of reference about it - seems to be > quite a niche. > > Can I run py2exe runs under wm5? > > Any other suggestion? > > Thanks in advance > > Marco I know some Python people use Inno Setup for packaging an executable and I think that would work with Windows Mobile. They seem to be using a mix of py2exe and Inno in some cases. Here's some links I found on the topic: http://mail.python.org/pipermail/patches/2003-October/013672.html http://www.thescripts.com/forum/thread30814.html http://www.thescripts.com/forum/thread26910.html http://innoconda.berlios.de/ Something to ponder and/or glean ideas from. Mike From hal at thresholddigital.com Mon Jun 18 14:13:42 2007 From: hal at thresholddigital.com (Hal Vaughan) Date: Mon, 18 Jun 2007 14:13:42 -0400 Subject: The Modernization of Emacs References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <873b0p9vpm.fsf@W0053328.mgh.harvard.edu> Message-ID: <5rWdnfcDQ4PLVuvbnZ2dnUVZ_qGjnZ2d@comcast.com> Joel J. Adamson wrote: > Xah Lee writes: > >> ---------------------------------------- >> SIMPLE CHANGES >> >> In the following, i describe some critical changes that are also very >> easy to fix in emacs. If emacs officially adopt these changes, i think >> it will make a lot people, at least programers, like emacs and choose >> emacs as their text editor. > > The problem with this line of thinking is that it aims to make Emacs > appeal to people -- I think it is rather the other way around. > Certain people appeal to Emacs: certain kinds of people like Emacs > and the way it is set up, and they change it to suit their needs. I worked for years as a special ed teacher and I learned that people have different learning styles. It's not just learning, but it's perceiving and working as well. Some people will always do better with a command line and some will always do better with a GUI with point-and-click. That doesn't mean one is smarter than the other or one is a true geek and one isn't. It's just the way our brains are wired. Emacs appeals to the type of personality that is often a hard core programmer. It works for those that want to customize everything and have full control over their environment AND do well with a command line rather than a more visual and graphic environment. For those, emacs is probably the best program for them. Some people prefer to drive a Miata and some prefer a Dodge Ram. One isn't better than the other, they're just different. Trying to make a Dodge Ram look like a convertible so Miata lovers will want to use it is a waste. It'll never be a Miata and the more people try to make it adaptable so it can be one, the more they ruin what's special about it. The more emacs is adapted for the non-technical, the more it'll lose what makes it special and a good fit for programmers. > Among your changes, I found none that made sense to me, a person who > used Unix before Windows became widely used. For people like me, who > always preferred Unix, changes like changing "buffer" to "opened file" > seem inefficient and unnecessary. It seems to me that is the kind of person emacs is written for. What will it gain if a large number of non-technical people start using it in a "non-emacs" mode? > Sorry -- this totally falls flat. It won't make Emacs more widely > used. The only thing that will make Emacs more widely used is making > people aware of it; as soon as I became aware of Emacs (from reading > Wikipedia, ironically), I began using it and I knew I was stuck with > it. It's not even important for the survival of Emacs that it be more > widely used -- it was never important in the last thirty years of its > history, why should it be important now that Microsoft Word is so > widely used? Let those who need Word use it. To try to change emacs into something it isn't is ignoring what makes it special. Hal From Stebanoid at gmail.com Fri Jun 8 03:37:13 2007 From: Stebanoid at gmail.com (Stebanoid) Date: Fri, 08 Jun 2007 00:37:13 -0700 Subject: howto obtain directory where current (running) py-file is placed? In-Reply-To: <1181198387.952428.163120@q75g2000hsh.googlegroups.com> References: <1181198387.952428.163120@q75g2000hsh.googlegroups.com> Message-ID: <1181288233.458341.5480@p47g2000hsd.googlegroups.com> On 7 , 10:39, dmitrey wrote: > Hi all, > I guess this question was asked many times before, but I don't know > keywords for web search. > > Thank you in advance, D. import sys file_name = sys.argv[0] ???????????? this? From jadamson at partners.org Thu Jun 21 13:14:54 2007 From: jadamson at partners.org (Joel J. Adamson) Date: Thu, 21 Jun 2007 13:14:54 -0400 Subject: The Modernization of Emacs: terminology buffer and keybinding References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182272495.990807.99110@a26g2000pre.googlegroups.com> <87tzt3ihev.fsf@kobe.laptop> <1182370216.961241.6960@n60g2000hse.googlegroups.com> <85zm2ufjpb.fsf@lola.goethe.zz> <1182372592.803332.288260@u2g2000hsc.googlegroups.com> <1182373419.522607.14500@g4g2000hsf.googlegroups.com> <1182374902.920671.171900@k79g2000hse.googlegroups.com> <87fy4l73qc.fsf@W0053328.mgh.harvard.edu> <868xadl59a.fsf@lola.quinscape.zz> Message-ID: <87sl8l9qlt.fsf@W0053328.mgh.harvard.edu> David Kastrup writes: > jadamson at partners.org (Joel J. Adamson) writes: >> Or, since Emacs is customizable, for me it would be >> >> t >> i >> ? > > Huh? The latter are available by default on Emacs 22.1. Interesting, maybe I have a telepathetic connection with the developers; either that or I just kept using the same .emacs when I upgraded ;) (I had to change this when I was using Emacs 21.4, since I started using C-h for backspace) Joel -- Joel J. Adamson Biostatistician Pediatric Psychopharmacology Research Unit Massachusetts General Hospital Boston, MA 02114 (617) 643-1432 (303) 880-3109 A webpage of interest: http://www.gnu.org/philosophy/sylvester-response.html From C.delete_this.Sanders at BoM.GOv.AU Fri Jun 22 01:46:52 2007 From: C.delete_this.Sanders at BoM.GOv.AU (Charles Sanders) Date: Fri, 22 Jun 2007 15:46:52 +1000 Subject: comparing two lists and returning "position" In-Reply-To: <7xvedg4n2d.fsf@ruckus.brouhaha.com> References: <1182481876.028589.71710@x35g2000prf.googlegroups.com> <7xvedg4n2d.fsf@ruckus.brouhaha.com> Message-ID: <467b624e$0$16271$c30e37c6@lon-reader.news.telstra.net> Paul Rubin wrote: > > from itertools import izip > pos = map(dict(izip(l2, count())).__getitem__, l1) or probably less efficiently ... >>> l1 = [ 'abc', 'ghi', 'mno' ] >>> l2 = [ 'abc', 'def', 'ghi', 'jkl', 'mno', 'pqr'] >>> pos = [ l2.index(i) for i in l1 ] >>> print pos [0, 2, 4] Charles From sturlamolden at yahoo.no Sun Jun 17 18:19:08 2007 From: sturlamolden at yahoo.no (sturlamolden) Date: Sun, 17 Jun 2007 15:19:08 -0700 Subject: Matrix Multiplication In-Reply-To: <1182113543.957069.135240@k79g2000hse.googlegroups.com> References: <1182113543.957069.135240@k79g2000hse.googlegroups.com> Message-ID: <1182118748.755871.267780@u2g2000hsc.googlegroups.com> On Jun 17, 10:52 pm, "amitsoni.1... at gmail.com" wrote: > Hi, > > Is there any direct function for matrix multiplication in Python or > any of its packages? or do we have to multiply element by element? Use numpy: www.scipy.org NumPy has a matrix type that overloads the * operator. From laurent.pointal at limsi.fr Thu Jun 14 08:43:08 2007 From: laurent.pointal at limsi.fr (Laurent Pointal) Date: Thu, 14 Jun 2007 14:43:08 +0200 Subject: for web application development In-Reply-To: <1181812584.392929.232670@o11g2000prd.googlegroups.com> References: <1181812584.392929.232670@o11g2000prd.googlegroups.com> Message-ID: james_027 a ?crit : > hi everyone, > > I am very new to python, I am almost done learning the python language > enough that I can start learning developing web app in python. I have > gone thru many research and I still say that I will want to develop > web app in python. Although some says php should be better since the > language is made for the web compare to python. In the point of view > of rails, they say that their framework is really easy and best for > web app. > > My problem is looking for a web framework for python, that could > provide a natural way of developing web app. I am avoiding to learn > template language as much as possible. Near the big ones (Django, TurboGears, Pylons), you may take a look at Karrigell: http://karrigell.sourceforge.net/en/front.htm (se examples) > > Any advice will be greatly appreciated. > > THanks > james > From pinkfloydhomer at gmail.com Mon Jun 18 19:58:53 2007 From: pinkfloydhomer at gmail.com (pinkfloydhomer at gmail.com) Date: Mon, 18 Jun 2007 23:58:53 -0000 Subject: Python and (n)curses Message-ID: <1182211133.956524.160020@g4g2000hsf.googlegroups.com> I need to develop a cross-platform text-mode application. I would like to do it in Python and I would like to use a mature text-mode library for the UI stuff. The obvious choice, I thought, was ncurses. But as far as I can tell, it is not available for Python on Windows? Is there a workaround? Or are there alternative libraries that might be used instead of (n)curses? I know I can use (n)curses on *nix and console on Windows etc., but that is of course suboptimal. /David From larry.bates at websafe.com Tue Jun 12 13:12:18 2007 From: larry.bates at websafe.com (Larry Bates) Date: Tue, 12 Jun 2007 12:12:18 -0500 Subject: Forgetting an import In-Reply-To: <1181666164.640868.225130@i38g2000prf.googlegroups.com> References: <1181666164.640868.225130@i38g2000prf.googlegroups.com> Message-ID: HMS Surprise wrote: > I imported a set of functions from a file I wrote to interpreter > shell: > > from myFile import * > > Now if I change functions in this file how can I make python forget it > so I can force a fresh import? > > thanx, > > jh > While there may be ways of doing this, I have found that you are much better off opening another window and run your script from the bare OS. It will help you catch problems that you may miss in the interpreter shell. It also solves this problem completely. -Larry From compiledmonkey at gmail.com Tue Jun 5 23:10:51 2007 From: compiledmonkey at gmail.com (Chris Stewart) Date: Tue, 5 Jun 2007 23:10:51 -0400 Subject: web development without using frameworks In-Reply-To: <1181073336.850423.120500@q69g2000hsb.googlegroups.com> References: <20d6f8950706051201mba83194hcbc4d17cd2439cd@mail.gmail.com> <1181073336.850423.120500@q69g2000hsb.googlegroups.com> Message-ID: <20d6f8950706052010s39b44737u56ae57d8a4c3a5a6@mail.gmail.com> Interesting. So I guess to accomplish my goals, I'll have to explore one of these frameworks. On 6/5/07, bruno.desthuilliers at gmail.com wrote: > > On Jun 5, 9:24 pm, Christoph Haas wrote: > > On Tue, Jun 05, 2007 at 03:01:01PM -0400, Chris Stewart wrote: > > > I'm interested in learning web based python without the use of fancy > frameworks > > > that are out there. I'm having a hard time coming up with resources > and > > > examples for this. Does anyone have anything that could be helpful? > > > > I'd say the only decent ways are either using a full-featured framework > > (I favor Pylons) or write plain CGIs. Even for the later a look > intohttp://wiki.python.org/moin/WebFrameworksmight be useful (I wouldn't > > say that "web.py" is really a framework - and it's listed there). Or you > > write plain-old CGIs with Python's "cgi" module. I have also started > > like that but currently only use frameworks because the "cgi" module is > > pretty limited (compared to what Perl offers) and for serious > > applications not really the way to go. > > > > > I can only second Christoph's answer. Using bare CGI, you'll rapidly > find you have to set up some common things like sessions, templating, > url to actions dispatch etc - IOW, reinventing the (square) wheel. So > unless your goal is to learn the "low-level" parts of web programming > (which is a very legitimate goal - as far as I'm concerned, I'd like > to see more 'web developpers' doing so), my advice is also to look for > a simple, flexible, non-intrusive framework (web.py and Pylons come to > mind). > > My 2 (euro) cents. > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Chris Stewart compiledmonkey at gmail.com http://www.compiledmonkey.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From kyosohma at gmail.com Wed Jun 20 10:05:00 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Wed, 20 Jun 2007 07:05:00 -0700 Subject: Controlling Firefox with Python In-Reply-To: <46784c34$0$5104$ba4acef3@news.orange.fr> References: <1182286371.974090.80760@q75g2000hsh.googlegroups.com> <46784c34$0$5104$ba4acef3@news.orange.fr> Message-ID: <1182348300.106377.111100@u2g2000hsc.googlegroups.com> On Jun 19, 4:35 pm, "M?ta-MCI" wrote: > Hi! > > See Mozlab: http://dev.hyperstruct.net/mozlab > > and give a report, please. > Thank you in advance. > > Michel Claveau There seems to be some kind of weird bug with the current version of MozLab. When I use telnet on my Windows XP box, it tries to evaluate every character I type, which only results in lots of syntax errors. I tried Putty in raw mode, and it works, but not well. Each line doesn't get output to the far left. Instead, each line is dropped down one line and tabbed over so it's one character ahead of the previous line. I assume you think I can use Python to telnet to a running MozLab to execute my commands? I will need to be able to do this to all the users on a network and installing extensions on everyone's PC will be somewhat difficult. Mike From showell30 at yahoo.com Wed Jun 20 12:58:46 2007 From: showell30 at yahoo.com (Steve Howell) Date: Wed, 20 Jun 2007 09:58:46 -0700 (PDT) Subject: SimplePrograms challenge In-Reply-To: Message-ID: <477094.68243.qm@web33509.mail.mud.yahoo.com> --- Pete Forman wrote: > > An empty list raises an IndexError, a non-iterable > raises TypeError. > This is correct behavior IMHO, there is nothing to > fix. Median should > return an element (or average of two) from its input > and if that is > not meaningful returning None or other special value > is neither > appropriate nor Pythonic. Only the caller knows how > to handle such > exceptional circumstances. > > Actually there are some other issues. Should the > median of an even > number of integers allow halves? Should median > insist that its input > has an odd number of elements? But it's tough > squeezing all that > discourse into 13 or 14 lines ;-) BankAccount > allows arbitrarily > large withdrawals, is that to be fixed too? Agreed on all points. I prefer the simplicity of the current examples, and I think any reasonable reader will know their limitations. The BankAccount example is about as small of a "complete" class example that I could come up with, even though it's "complete" only a basic level. It would be good to have a larger class example that fleshes out the concept a bit more, even if it's just BankAccount revisited. I have some free time next time, I'll try my hand at it. ____________________________________________________________________________________ Yahoo! oneSearch: Finally, mobile search that gives answers, not web links. http://mobile.yahoo.com/mobileweb/onesearch?refer=1ONXIC From josiah.carlson at sbcglobal.net Thu Jun 14 01:04:48 2007 From: josiah.carlson at sbcglobal.net (Josiah Carlson) Date: Wed, 13 Jun 2007 22:04:48 -0700 Subject: save class In-Reply-To: References: <1181784016.454693.42340@o11g2000prd.googlegroups.com> <1181787082.712869.72770@z28g2000prd.googlegroups.com> Message-ID: Gabriel Genellina wrote: > En Wed, 13 Jun 2007 23:11:22 -0300, nik escribi?: >> It would seem that I want to actually save the source code for the >> class. I know that I could of course open up an editor and just make >> it, but my ideal would be to have the base class, Map, be able to make >> the sub-classes. I don't want the class definition. What I want is an >> actual class that I could later import and use somewhere else. I am >> planning to have each one of these map objects contain a different >> dictionary and then be able to import the map into the application, >> but have certain methods defined in the Map super-class to draw data >> out of the specific map's specific dictionary. I hope that makes >> sense. >> >> Something like, >> class Map: >> dict = {} >> def DoSomething(self): >> pass >> >> def MakeNewMapSubClass(self, newclassname): >> """ make a new file, newclassname.py that contains a new >> class >> newclassname(Map) that inherits from base-class Map. > > And are you sure you actually need different subclasses? Will you > construct them several instances of each subclass? From the above > description I feel you want just different Map *instances*, each with > its own dict, not different *subclasses*. What you said, and that his solution sounds like a Java approach to the problem (subclass an abstract base class that calls specific methods on the subclass to "do the right thing"). To offer the OP source he can use... class Map: def __init__(self): self.dict = {} def DoSomething(self): #do something with self.dict Every instance gets a new dictionary. Now, if he actually wants to change the behavior of the DoSomething method, of course then it would make sense to subclass Map. - Josiah From kylotan at gmail.com Wed Jun 13 12:57:54 2007 From: kylotan at gmail.com (Ben Sizer) Date: Wed, 13 Jun 2007 09:57:54 -0700 Subject: Windows build of PostgreSQL library for 2.5 In-Reply-To: <1180538458.993024.173510@g4g2000hsf.googlegroups.com> References: <1180534505.421166.83700@q66g2000hsg.googlegroups.com> <1180536164.370773.183140@q69g2000hsb.googlegroups.com> <1180538458.993024.173510@g4g2000hsf.googlegroups.com> Message-ID: <1181753874.015973.193030@g37g2000prf.googlegroups.com> On 30 May, 16:20, Ben Sizer wrote: > On 30 May, 15:42, Frank Millman wrote: > > > On May 30, 4:15 pm,BenSizer wrote: > > > > I've been looking for a Windows version of a library to interface to > > > PostgreSQL, but can only find ones compiled under Python version 2.4. > > > Is there a 2.5 build out there? > > > Is this what you are looking for? > > >http://stickpeople.com/projects/python/win-psycopg/ > > It may well be, thanks. On second thoughts, is there one anywhere without an extra multi- megabyte dependency? This seems to rely on the eGenix 'mx' library. -- Ben Sizer From max at alcyone.com Sun Jun 10 01:54:47 2007 From: max at alcyone.com (Erik Max Francis) Date: Sat, 09 Jun 2007 22:54:47 -0700 Subject: urllib2 - iteration over non-sequence In-Reply-To: References: <1181427526.996101.75230@m36g2000hse.googlegroups.com> <466B2AA7.3040704@websafe.com> <1181429903.533207.105730@p77g2000hsh.googlegroups.com> <7x3b10pnwq.fsf@ruckus.brouhaha.com> Message-ID: Gary Herron wrote: > Certainly there's are cases where xreadlines or read(bytecount) are > reasonable, but only if the total pages size is *very* large. But for > most web pages, you guys are just nit-picking (or showing off) to > suggest that the full read implemented by readlines is wasteful. > Moreover, the original problem was with sockets -- which don't have > xreadlines. That seems to be a method on regular file objects. > > For simplicity, I'd still suggest my original use of readlines. If > and when you find you are downloading web pages with sizes that are > putting a serious strain on your memory footprint, then one of the other > suggestions might be indicated. It isn't nitpicking to point out that you're making something that will consume vastly more amounts of memory than it could possibly need. And insisting that pages aren't _always_ huge is just a silly cop-out; of course pages get very large. There is absolutely no reason to read the entire file into memory (which is what you're doing) before processing it. This is a good example of the principle of there is one obvious right way to do it -- and it isn't to read the whole thing in first for no reason whatsoever other than to avoid an `x`. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM, Y!M erikmaxfrancis The more violent the love, the more violent the anger. -- _Burmese Proverbs_ (tr. Hla Pe) From Afro.Systems at gmail.com Sun Jun 17 04:48:44 2007 From: Afro.Systems at gmail.com (Tzury) Date: Sun, 17 Jun 2007 08:48:44 -0000 Subject: Comparing UTF-8 into USC-2 and vice versa (newbie :-) ) In-Reply-To: <4674E74E.1080406@v.loewis.de> References: <1182064058.292960.319970@p77g2000hsh.googlegroups.com> <4674E74E.1080406@v.loewis.de> Message-ID: <1182070124.121858.97140@q69g2000hsb.googlegroups.com> On Jun 17, 10:48 am, "Martin v. L?wis" wrote: > > I recently rewrote a .net application in python. > > The application is basically gets streams via TCP socket and handle > > operations against an existing database. > > The Database is SQLite3 (Encoded as UTF-8). > > The Networks streams are encoded as UCS-2. > > > Since in UCS-2, 'A' = '0041' and when I check with the built-in > > functions I get for unicode("A", "utf-8") = u'A' = u'\u0041'. I > > wonder what is the difference, and how can I safely encode/decode > > UCS-2 streams and match them with the UTF-8 representation > > In unicode("A", "utf-8"), the "utf-8" parameter does *not* mean > that the output is in UTF-8, but the *input*. > So "A" = '41' != '0041'. In UCS-2, the A consumes two bytes; in > UTF-8, it consumes only one byte. > > For different letters, that's different: For example, for u'\xf6', > the UCS-2 representation (big-endian) is '00F6', for UTF-8, it is > 'C3B6'. For u'\u20AC', the UCS-2 is '20AC', the UTF-8 is 'E282AC' > (i.e. three bytes). > > You should use Unicode objects in your program always, and encode > to or from UCS-2 or UTF-8 only when interfacing with the > network/database. > > HTH, > Martin Thanks Martin for this guideline. But in fact say I get a USC-2 string and need to compare it with UTF-8 value in the database. How can I do it given the Python built-in libraries? From vdicarlo at gmail.com Thu Jun 7 21:28:33 2007 From: vdicarlo at gmail.com (vdicarlo) Date: Thu, 07 Jun 2007 18:28:33 -0700 Subject: How Can I Increase the Speed of a Large Number of Date Conversions Message-ID: <1181266113.100863.174410@q19g2000prn.googlegroups.com> I am a programming amateur and a Python newbie who needs to convert about 100,000,000 strings of the form "1999-12-30" into ordinal dates for sorting, comparison, and calculations. Though my script does a ton of heavy calculational lifting (for which numpy and psyco are a blessing) besides converting dates, it still seems to like to linger in the datetime and time libraries. (Maybe there's a hot module in there with a cute little function and an impressive set of attributes.) Anyway, others in this group have said that the date and time libraries are a little on the slow side but, even if that's true, I'm thinking that the best code I could come up with to do the conversion looks so clunky that I'm probably running around the block three times just to go next door. Maybe someone can suggest a faster, and perhaps simpler, way. Here's my code, in which I've used a sample date string instead of its variable name for the sake of clarity. Please don't laugh loud enough for me to hear you in Davis, California. dateTuple = time.strptime("2005-12-19", '%Y-%m-%d') dateTuple = dateTuple[:3] date = datetime.date(dateTuple[0], dateTuple[1], dateTuple[2]) ratingDateOrd = date.toordinal() P.S. Why is an amateur newbie trying to convert 100,000,000 date strings into ordinal dates? To win try to win a million dollars, of course! In case you haven't seen it, the contest is at www.netflixprize.com. There are currently only about 23,648 contestants on 19,164 teams from 151 different countries competing, so I figure my chances are pretty good. ;-) From gagsl-py2 at yahoo.com.ar Thu Jun 21 20:43:20 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 21 Jun 2007 21:43:20 -0300 Subject: unable to execute to a python script References: Message-ID: En Thu, 21 Jun 2007 12:47:30 -0300, Bala Subramanyam vemu escribi?: > It executes fine in the python shell, but the problem is in when i > execute > as a python script i get the following error > > DCA-TestMachine:~/python_scripts # python2.5 -v rpmqa.py > # /root/python_scripts/rpm.pyc matches /root/python_scripts/rpm.py > import rpm # precompiled from /root/python_scripts/rpm.pyc > Traceback (most recent call last): > File "rpmqa.py", line 1, in > import rpm > File "/root/python_scripts/rpm.py", line 10, in > main() > File "/root/python_scripts/rpm.py", line 3, in main > tss= rpm.TransactionSet() > AttributeError: 'module' object has no attribute 'TransactionSet' You have a rpm.py in your python_scripts directory, and it shadows the right one. Rename or delete your rpm.py > I dont know what path I should set the PYTHONHOME PYTHONPATH .etc.. > variables Usually, nothing. -- Gabriel Genellina From bruno.42.desthuilliers at wtf.websiteburo.oops.com Thu Jun 21 02:59:01 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Thu, 21 Jun 2007 08:59:01 +0200 Subject: PEP 3107 and stronger typing (note: probably a newbie question) In-Reply-To: References: <1182369568.941307.316260@p77g2000hsh.googlegroups.com> Message-ID: <467a21a3$0$7053$426a74cc@news.free.fr> Stephen R Laniel a ?crit : > On Wed, Jun 20, 2007 at 12:59:28PM -0700, bruno.desthuilliers at gmail.com wrote: >> Then you should use another language. > > This is what I meant about knowing how Internet discussions > go. > Please let not forget the context. You said: "I'm new to Python", and then : "if I *want* strong static type-checking, why shouldn't I be able to get it?" You obviously don't know Python enough to understand why static typechecking doesn't belong to Python. Trying to explain would be a waste of time, because you have to experiment it in real-life situation to fully understand. So to put things briefly, Python with static typechecking would not be Python anymore - it would be another language. Which implies that if you want static typechecking, you'll have to use another language one way or another. From jura.grozni at gmail.com Wed Jun 6 07:49:28 2007 From: jura.grozni at gmail.com (azrael) Date: Wed, 06 Jun 2007 04:49:28 -0700 Subject: otsu threshold in python In-Reply-To: <1181059357.248682.38980@p77g2000hsh.googlegroups.com> References: <1181053148.203548.199630@w5g2000hsg.googlegroups.com> <1181059357.248682.38980@p77g2000hsh.googlegroups.com> Message-ID: <1181130568.840780.74850@p47g2000hsd.googlegroups.com> the otsu filter is a filter that takes a image and from its histogram calculates the values at which the image should be thresholded to acomplish an optimal seperation of a foregtround and background object. I didn't hear about, but I used it through the ImageJ tool. It gave me optimal results. I'm working on a project for my clases, and the last thing I need to accomplish my goal is this filter. Is there anyone who implemented it. Thanks Hyuga On Jun 5, 6:02 pm, Hyuga wrote: > On Jun 5, 10:19 am, azrael wrote: > > > > > Hy guys. > > I'd like to ask you for a favour. > > I tried several times to implement the otsu threshold filter in > > python. but I failed every time. I found the soucre code i n Java from > > the ImageJ project but I never worked in Java and there have been used > > some built in Java functions which I don't know how they behave. I > > also found the otsu threshold in the ia636 python module and would > > like only this filter and don't want to import this library. > > Is there anyone who wold like to help me. I need a function that takes > > a list of 256 elements as an argument and returns the threshold values > > for the threshold according to Otsu. > > > In addvance, I don't expect someone to do my homework. I really tried > > it, I have been googling and didn't find a standalone function. I > > wasn't able write a standalone function because I don't understand the > > Otsu method. I just know that it works well and that I need it. > > > If there is no one that wants to help me with this problem, can > > someone at least explain me in a detailed way how to implement it. > > > Thanks > > What is the whole assignment meant to accomplish? Is the assignment > to implement the Otsu method? If so, you shouldn't be trying to find > library functions. Or is it just something you need for some larger > task? > > I would ask exactly what problems you're running into, but: > > > it, I have been googling and didn't find a standalone function. I > > wasn't able write a standalone function because I don't understand the > > Otsu method. I just know that it works well and that I need it. > > How do you know you need it? Did you learn about this in class? And > if so, are you expected to understand it? > I've never even heard of it, but I googled it, and found the fourth > hit pretty good:http://homepages.inf.ed.ac.uk/rbf/CVonline/LOCAL_COPIES/MORSE/thresho... > This gives a reasonable explanation. I couldn't tell you *exactly* > why it works, but it's understandable enough from that that I can see > that it should work, and to see how to implement it. > > Not to mention that the above PDF basically *gives* you the > implementation for free (just make sure not to miss the recurrence > relations at the end of the section on the Otsu method, or else you'll > be screwing yourself). > > So give that a look and see if it helps. > > Hyuga From adam at atlas.st Mon Jun 4 09:57:56 2007 From: adam at atlas.st (Adam Atlas) Date: Mon, 04 Jun 2007 06:57:56 -0700 Subject: `yield` in a `try/finally` block, pre-Python 2.5 In-Reply-To: <1180936147.621280.33080@o5g2000hsb.googlegroups.com> References: <1180934605.412073.138120@q75g2000hsh.googlegroups.com> <1180936147.621280.33080@o5g2000hsb.googlegroups.com> Message-ID: <1180965476.759771.72680@m36g2000hse.googlegroups.com> On Jun 4, 1:49 am, yuce wrote: > I had the same problem, you can see:http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/130004 > for a solution. > > Happy hacking, > > Yuce Thanks. I thought of doing something like that, but in my program, it's important that the order follow the actual nesting order. That is, I have a few nested generator each of which has its own 'finally', and I need the innermost ones to run first. How can I deal with that? From chowroc.z+l at gmail.com Thu Jun 21 23:37:21 2007 From: chowroc.z+l at gmail.com (Roc Zhou) Date: Fri, 22 Jun 2007 11:37:21 +0800 Subject: why __repr__ affected after __getattr__ overloaded? Message-ID: <7847e5160706212037n6136c901qeea2450c0168b478@mail.gmail.com> Now I have to design a class that overload __getattr__, but after that, I found the __repr__ have been affected. This is a simple example model: #!/usr/bin/env python class test: def __init__(self): self.x = 1 def __getattr__(self, attr_name): try: return self.__dict__[attr_name] except KeyError: self.__dict__[attr_name] = 'inexistent' return self.__dict__[attr_name] t = test() print t.x print t.y print type(t) T = t print T.x print t So far, I want the operation "print t" still return "", but the reuslt is: sh$ python test.py 1 inexistent 1 Traceback (most recent call last): File "testtree.py", line 23, in ? print t TypeError: 'str' object is not callable I also tried to overload __repr__ itself: #!/usr/bin/env python class test: def __init__(self): self.x = 1 def __getattr__(self, attr_name): try: return self.__dict__[attr_name] except KeyError: self.__dict__[attr_name] = 'inexistent' return self.__dict__[attr_name] def __repr__(self): return 'test.__repr__' t = test() print t.x print t.y print type(t) T = t print T.x print t But the result remains: Traceback (most recent call last): File "testtree.py", line 23, in ? print t TypeError: 'str' object is not callable So why? What is the principles? -------------- next part -------------- An HTML attachment was scrubbed... URL: From hyugaricdeau at gmail.com Mon Jun 18 11:01:26 2007 From: hyugaricdeau at gmail.com (Hyuga) Date: Mon, 18 Jun 2007 15:01:26 -0000 Subject: sqlite3 bug?? In-Reply-To: <46753426$0$30325$fa0fcedb@news.zen.co.uk> References: <46752230$0$31685$db0fefd9@news.zen.co.uk> <46753426$0$30325$fa0fcedb@news.zen.co.uk> Message-ID: <1182178886.470101.139340@n2g2000hse.googlegroups.com> On Jun 17, 9:16 am, mark carter wrote: > Should I also explicitly close the cursor and connection, or is that > taken care of "automagically"? > Somebody correct me if I'm wrong, but I'm pretty sure that the Cursor and Connection objects properly clean themselves up when deallocated (when their reference count reaches 0), so not explicitly closing them isn't a terrible thing. In fact, I have code in which references to a db connection are passed around, so I have to be careful about explicitly closing the connection, lest it be in use by some other method somewhere. Maybe people will frown on this, but it's not uncommon. Hyuga From martin at v.loewis.de Sun Jun 17 13:56:08 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 17 Jun 2007 19:56:08 +0200 Subject: Comparing UTF-8 into USC-2 and vice versa (newbie :-) ) In-Reply-To: <1182101582.573171.213190@q75g2000hsh.googlegroups.com> References: <1182064058.292960.319970@p77g2000hsh.googlegroups.com> <4674E74E.1080406@v.loewis.de> <1182070124.121858.97140@q69g2000hsb.googlegroups.com> <1182070999.570999.311690@e9g2000prf.googlegroups.com> <1182101582.573171.213190@q75g2000hsh.googlegroups.com> Message-ID: <467575b8$0$24878$9b622d9e@news.freenet.de> Tzury schrieb: > Yet, > 'utf_16_be' is not 'ucs-2'. That's not true. They are virtually identical. > How would I get ucs-2 encoding and decoding functionality with python? Use the UTF-16 codec. Regards, Martin From deets at nospam.web.de Fri Jun 1 06:50:13 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 01 Jun 2007 12:50:13 +0200 Subject: How to clean a module? References: <1180622824.836459.222090@q19g2000prn.googlegroups.com> <5c87f5F2mg4c1U1@mid.uni-berlin.de> <1180664579.182455.26170@g37g2000prf.googlegroups.com> Message-ID: <5cabv5F30c36fU1@mid.uni-berlin.de> ai wrote: > Yes, you are right. > But from this problem, could I infer that the statement "del xxx" > doesn't release the memory which xxx used? It just removes the name xxx from the current scope - which will result in a reference counter decrease. If that was the last reference, the object will be destroyed. Most times. There are some special cases involving the usage of __del__-methods on objects. Diez From tutufan at gmail.com Mon Jun 18 12:41:58 2007 From: tutufan at gmail.com (tutufan at gmail.com) Date: Mon, 18 Jun 2007 16:41:58 -0000 Subject: suggestion: recursive collections.defaultdict Message-ID: <1182184918.766497.315040@k79g2000hse.googlegroups.com> It seems like x = defaultdict(defaultdict(list)) should do the obvious, but it doesn't. This seems to work y = defaultdict(lambda: defaultdict(list)) though is a bit uglier. From deliberatus at verizon.net Thu Jun 28 23:23:33 2007 From: deliberatus at verizon.net (Kirk Bailey) Date: Fri, 29 Jun 2007 00:23:33 -0300 Subject: Python & cgi on win98--tinyweb problems, etc Message-ID: <46847B35.6020405@verizon.net> RE: TinyWeb running python in windows PROBLEM: getting python scripts to execute. SOLUTION: Insure the script ends in the name extension .py. Windows associates all such files with the pythonw.exe interpreter program, and will use it to interpret them. IT IGNORES THE SHEBANG (the first line in a script which in the lovely world of un*x points to the interpreter program). Some servers have config files to tell the server what to use. TinyWeb does not, and relies on windows file associations to direct it to the proper interpreter. Also note that it is possible for windows to conceal name extensions in some configurations, and also to create name extensions it does not display, resulting in some interesting hair pulling evenings chasing bugs. Also note that tinyweb checks for the existence of a default page to use if none is specified in an incoming request. IF YOU CHANGE THE FILE NAME AFTER TINY LOADS IT WILL BARK LIKE A DOG. For instance, index.htm or index.html are equally acceptable. You had .htm. then you decided to change it to .html- and the server started woofing. It thinks the file index.htm still is there someplace and is looking for it! If you change the file name, restart the server. I used tinyweb in supporting the development of windows wiki, and in all that crazy alpha stage flakiness, it NOT ONCE blew out. It is BULLETPROOF. But it is it's own strange beast, and has it's own peculiarities. -- Salute! -Kirk Bailey Think +-----+ | BOX | +-----+ knihT Fnord. From basilisk96 at gmail.com Wed Jun 6 18:49:27 2007 From: basilisk96 at gmail.com (Basilisk96) Date: Wed, 06 Jun 2007 22:49:27 -0000 Subject: creating lists based on parsed items In-Reply-To: References: <0138071BF1642F49BD9826823E668663DCA87A@ex2.casl.umd.edu> Message-ID: <1181170167.160965.126760@g37g2000prf.googlegroups.com> > If you are using Python 2.5, use a defaultdict instead, the very first > example looks like what you want. > > > -- > Gabriel Genellina Uh-oh.. I am using Python 2.5 on WinXP, but when I tried the examples in the manual, I got a "NameError: name 'defaultdict' is not defined". What am I missing in my Python installation? -Basilisk96 From __peter__ at web.de Thu Jun 21 18:27:34 2007 From: __peter__ at web.de (Peter Otten) Date: Fri, 22 Jun 2007 00:27:34 +0200 Subject: import mysteries References: Message-ID: David Abrahams wrote: > I'm pretty comfortable with Python, but recently I'm constantly > finding mysterious issues with import. For example, looking at > > http://genshi.edgewall.org/browser/trunk/genshi/filters/transform.py > > the examples use the symbol 'HTML' but it's not defined locally, it's > not explicitly imported, and there's no import *. Yet doctest will > test this module and it passes with flying colors. It turns out HTML > is defined in genshi.input. How do I know that? I grepped for it. > How does it become available to this module? Explicitly passed, see http://genshi.edgewall.org/browser/trunk/genshi/filters/tests/transform.py > Another example: I was recently working on some code that did an > import from inside a class method. That import was failing. I moved > the import to the top of the file (at module scope) and it succeeded. > I'm fairly sure that nobody was monkeying around with sys.path in that > case. Can anyone think of a likely explanation? Too vague, sorry. Peter From bj_666 at gmx.net Mon Jun 25 16:05:27 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Mon, 25 Jun 2007 22:05:27 +0200 Subject: Collections of non-arbitrary objects ? References: <1182449993.223262.229500@z28g2000prd.googlegroups.com> <87k5twx4hf.fsf@benfinney.id.au> <1182559502.069773.321620@i38g2000prf.googlegroups.com> <87wsxvrzsj.fsf@benfinney.id.au> <1182620734.940718.196520@e16g2000pri.googlegroups.com> <467ed491$0$27132$426a34cc@news.free.fr> <1182780863.067601.89320@d30g2000prg.googlegroups.com> <46801791$0$32172$426a34cc@news.free.fr> Message-ID: In <46801791$0$32172$426a34cc at news.free.fr>, Bruno Desthuilliers wrote: > walterbyrd a ?crit : >> For example, I don't think you can divide a string by another string. > > No, because this operation is not implemented for strings - IOW, strings > doesn't understand this message. What would be the meaning of dividing > strings anyway ? (while concatening string is a well-known operation). As someone else already mentioned dividing strings is splitting. The Pike language does this: http://pike.ida.liu.se/generated/manual/ref/chapter_4.html Scroll down to ``string / string``. The definition of ``string / float`` is neat too. Something I really miss in everyday programming in Python, not. ;-) Ciao, Marc 'BlackJack' Rintsch From keramida at ceid.upatras.gr Fri Jun 22 15:43:52 2007 From: keramida at ceid.upatras.gr (Giorgos Keramidas) Date: Fri, 22 Jun 2007 22:43:52 +0300 Subject: The Modernization of Emacs References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182370894.001918.36590@k79g2000hse.googlegroups.com> <1182372821.298343.316860@g4g2000hsf.googlegroups.com> <1182375321.067664.190780@o61g2000hsh.googlegroups.com> <86hcp1l6hb.fsf@lola.quinscape.zz> <871wg56y1x.fsf@W0053328.mgh.harvard.edu> Message-ID: <87ejk3rczr.fsf@kobe.laptop> On Thu, 21 Jun 2007 13:02:18 -0400, jadamson at partners.org (Joel J. Adamson) wrote: >David Kastrup writes: >> You know you can use something like >> C-x C-f /su::/etc/fstab RET >> (or /sudo::/etc/fstab) in order to edit files as root in a normal >> Emacs session? > > I did not know that. That will save me huge amounts of time. You're > my hero. If you like `C-x C-f /sudo::...', then it may also please you to know that Tramp supports other remote access methods too, i.e.: C-x C-f /ftp: C-x C-f /ssh: and it lets Emacs edit files in remote locations, as long as you have a valid set of username/password credentials for the remote host :-) From kerny404 at gmail.com Wed Jun 27 06:41:22 2007 From: kerny404 at gmail.com (andrea) Date: Wed, 27 Jun 2007 03:41:22 -0700 Subject: textmate and execute line In-Reply-To: <1182255615.005437.146660@k79g2000hse.googlegroups.com> References: <1182255615.005437.146660@k79g2000hse.googlegroups.com> Message-ID: <1182940882.658076.213410@c77g2000hse.googlegroups.com> On 19 Giu, 14:20, andrea wrote: > Hi, > I have the latest bundle for python (upgraded from svn) but I don't > understand how execute line works.. > > It only works if I play with arithmetic operations, something like > this works: > 2*2 > 4 > > but for example trying to execute this line gives me this error, any > help? > x = 1; x + 1 > > Traceback (most recent call last): > File "/tmp/temp_textmate.31Kc2h", line 19, in ? > stdout.write(exc) > TypeError: argument 1 must be string or read-only character buffer, > not list > > Thanks a lot Noone using textmate for python? From vedrandekovic at v-programs.com Sat Jun 23 08:28:21 2007 From: vedrandekovic at v-programs.com (...:::JA:::...) Date: Sat, 23 Jun 2007 14:28:21 +0200 Subject: Changing the names of python keywords Message-ID: Hello, I on working on windows and Python 2.4. Where can I find and CHANGE python grammar. ( I just want to change the keywords ) PLEASE HELP ME SOMEBODY!!!!!! THANKS!!!!!!!!!!!!!!!!! __________________________________________________________________ Vedran veki ICQ#: 264412055 Current ICQ status: + More ways to contact me Get ICQ! __________________________________________________________________ From broek at cc.umanitoba.ca Thu Jun 7 12:40:31 2007 From: broek at cc.umanitoba.ca (Brian van den Broek) Date: Thu, 07 Jun 2007 12:40:31 -0400 Subject: running a random function In-Reply-To: <1654405.LVbK4P6cM3@teancum> References: <1654405.LVbK4P6cM3@teancum> Message-ID: <466834FF.9060402@cc.umanitoba.ca> David Bear said unto the world upon 06/07/2007 11:56 AM: > I would like to write some code that would randomly select a function from a > list of functions and call it. I was looking in the globals names space and > randomly selecting items that were of type function.. but I didn't see a > way of actually running the function. > > Any pointers? > Unless I've missed your meaning: >>> import random >>> def f(): print 42 ... >>> def g(): print 24 ... >>> funcs = [f,g] >>> random.choice(funcs)() 24 Best, Brian vdB From markybob at gmail.com Thu Jun 28 11:06:53 2007 From: markybob at gmail.com (markybob) Date: Thu, 28 Jun 2007 15:06:53 -0000 Subject: compiling extension using distutils and visual studio 2003 Message-ID: <1183043213.540419.152580@w5g2000hsg.googlegroups.com> I'm trying to get Deluge ported to work on Windows, but unfortunately I can't seem to figure how to fix this error. Any help would be *greatly* appreciated. First off, here's the code to the setup.py file (http://dev.deluge-torrent.org/browser/trunk/setup.py? rev=809&format=txt) And here is the error: C:\Documents and Settings\James\Desktop\deluge>python setup.py build Attempting to detect your system information Couldn't detect CPU architecture Windows system detected Libraries mt running build running build_py creating build creating build\lib.win32-2.5 creating build\lib.win32-2.5\deluge copying src\common.py -> build\lib.win32-2.5\deluge copying src\core.py -> build\lib.win32-2.5\deluge copying src\deluge_stats.py -> build\lib.win32-2.5\deluge copying src\dgtk.py -> build\lib.win32-2.5\deluge copying src\dialogs.py -> build\lib.win32-2.5\deluge copying src\interface.py -> build\lib.win32-2.5\deluge copying src\ipc_manager.py -> build\lib.win32-2.5\deluge copying src\plugins.py -> build\lib.win32-2.5\deluge copying src\pref.py -> build\lib.win32-2.5\deluge copying src\__init__.py -> build\lib.win32-2.5\deluge running build_ext building '_deluge_core' extension creating build\temp.win32-2.5 creating build\temp.win32-2.5\Release creating build\temp.win32-2.5\Release\src creating build\temp.win32-2.5\Release\libtorrent creating build\temp.win32-2.5\Release\libtorrent\src creating build\temp.win32-2.5\Release\libtorrent\src\kademlia Traceback (most recent call last): File "setup.py", line 335, in cmdclass=cmdclass File "c:\python25\lib\distutils\core.py", line 151, in setup dist.run_commands() File "c:\python25\lib\distutils\dist.py", line 974, in run_commands self.run_command(cmd) File "c:\python25\lib\distutils\dist.py", line 994, in run_command cmd_obj.run() File "setup.py", line 293, in run _build.run(self) File "c:\python25\lib\distutils\command\build.py", line 112, in run self.run_command(cmd_name) File "c:\python25\lib\distutils\cmd.py", line 333, in run_command self.distribution.run_command(command) File "c:\python25\lib\distutils\dist.py", line 994, in run_command cmd_obj.run() File "c:\python25\lib\distutils\command\build_ext.py", line 290, in run self.build_extensions() File "c:\python25\lib\distutils\command\build_ext.py", line 416, in build_exte nsions self.build_extension(ext) File "c:\python25\lib\distutils\command\build_ext.py", line 481, in build_exte nsion depends=ext.depends) File "c:\python25\lib\distutils\ccompiler.py", line 697, in compile self._compile(obj, src, ext, cc_args, extra_postargs, pp_opts) File "c:\python25\lib\distutils\cygwinccompiler.py", line 150, in _compile extra_postargs) TypeError: can only concatenate list (not "str") to list C:\Documents and Settings\James\Desktop\deluge> From gagsl-py2 at yahoo.com.ar Mon Jun 11 00:17:09 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 11 Jun 2007 01:17:09 -0300 Subject: read 9 bytes References: <1181533948.427220.14650@j4g2000prf.googlegroups.com> Message-ID: En Mon, 11 Jun 2007 00:52:28 -0300, nik escribi?: > I need to read a 9 byte response from a device on the serial port. >> From reading the pySerial documentation it appears that I can only > read in characters at a time. > > If I do: serialport.read(4) > I would get 8 bytes, Why do you think so? read(4) will read up to 4 bytes, or less if the specified timeout elapses. > Is there a trick to read 9 bytes off of a serial port? read(9) (don't forget to set the timeout) -- Gabriel Genellina From venner at gmail.com Thu Jun 21 14:43:34 2007 From: venner at gmail.com (Eric) Date: Thu, 21 Jun 2007 11:43:34 -0700 Subject: newbie question: parsing street name from address In-Reply-To: <1182433644.485185.197690@w5g2000hsg.googlegroups.com> References: <1182433644.485185.197690@w5g2000hsg.googlegroups.com> Message-ID: <1182451414.139267.7910@w5g2000hsg.googlegroups.com> On Jun 21, 9:47 am, cjl wrote: > P: > > I am working on a project that requires geocoding, and have written a > very simple geocoder that uses the Google service. > > I would like to be able to extract the name of the street from the > addresses in my data, however they vary significantly. Here a some > examples: > > 25 Main St > 2500 14th St > 12 Bennet Pkwy > Pearl St > Bennet Rd and Main st > 19th St > > As you can see, sometimes I have the house number, and sometimes I do > not. Sometimes the street name is a number. Sometimes I simply have > the names of intersecting streets. > > I would like to be able to parse the above into the following: > > Main St > 14th St > Bennet Pkwy > Pearl St > Bennet Rd > Main St > 19th St > > How might I approach this complex parsing problem? > > -CJL You might be able to use consistencies in your data to make this simpler. If the examples you have there are representative, it looks like what you should do is look for a word like 'St' or 'Rd' and then return that word and the previous word. From horpner at yahoo.com Fri Jun 1 11:33:54 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Fri, 01 Jun 2007 15:33:54 GMT Subject: file reading by record separator (not line by line) References: <465ff8d3$0$79139$e4fe514c@news.xs4all.nl> Message-ID: On 2007-06-01, Tijs wrote: > Steve Howell wrote: >>> >>> from blockread import BlockReader >>> >>> b = BlockReader(f, boundary='>') >>> for block in b: >>> # whatever >> >> Yep, I like this idea. You might have a few >> variations: > > Yes, or a single one that takes a wide range of construction > possibilities, like strings, lambdas or regexes in various > keyword parameters. > > BlockReader(f, start='>') > BlockReader(f, start=re.compile('>|<'), end='---') > BlockReader(f, start=lambda x: x.startswith('>')) > > Maybe make variations for character-based readers and > line-based readers. I would prefer, "f.readlines(delim='>')" etc., a la C++ str::getline. -- Neil Cerutti From gagsl-py2 at yahoo.com.ar Sat Jun 23 02:46:53 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 23 Jun 2007 03:46:53 -0300 Subject: need help with re module References: <46795CBA.9040807@gmail.com> Message-ID: En Sat, 23 Jun 2007 01:12:17 -0300, samwyse escribi?: > Speak for yourself. If I'm writing an HTML syntax checker, I think I'll > skip BeautifulSoup and use something that gives me the results that I > expect, not the results that you expect. Sure! By the way, I'm looking for a different sound. I have an Ibanez but I think the Jackson is far better for thrash metal, the Jackson Kelly Pro series KE3 sounds good, and it's a classic. Maybe as a self-gift for my birthday next month. -- Gabriel Genellina From cam.ac.uk at mh391.invalid Tue Jun 5 10:44:04 2007 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Tue, 05 Jun 2007 15:44:04 +0100 Subject: *Naming Conventions* In-Reply-To: References: <1180909218.939713.112010@q69g2000hsb.googlegroups.com> <1180990280.960271.235550@h2g2000hsg.googlegroups.com> Message-ID: Neil Cerutti wrote: > I find i and j preferable to overly generic terms like "item." Well, I probably wouldn't use "item" in a real example, unless it were for a truly generic function designed to act on all sequences. -- Michael Hoffman From saint.infidel at gmail.com Mon Jun 11 14:59:36 2007 From: saint.infidel at gmail.com (infidel) Date: Mon, 11 Jun 2007 11:59:36 -0700 Subject: REALLY need help with iterating a list. In-Reply-To: <1181586648.614514.228900@m36g2000hse.googlegroups.com> References: <1181586648.614514.228900@m36g2000hse.googlegroups.com> Message-ID: <1181588376.426556.46530@j4g2000prf.googlegroups.com> On Jun 11, 11:30 am, Radamand wrote: > This has been driving me buggy for 2 days, i need to be able to > iterate a list of items until none are left, without regard to which > items are removed. I'll put the relevant portions of code below, > please forgive my attrocious naming conventions. > Basically i'm trying to spin up some subprocesses that will ping a > group of servers and then wait until all of them have completed (good > or bad), store the ping result and the return code, and move on. > The problem comes in the second block, when i try to iterate the > list of servers and remove the ones that are finished, for some reason > Python appears to re-index the list when I remove an item and the next > step through the loop it cant find the item its expecting because the > indexes have changed. > Any assistance would be appreciated... > > ============================================================================= > for server in serverlist: > ping[server] = subprocess.Popen("ping -c 1 " + str(server) + " 5", > shell=True, stdout=subprocess.PIPE) > > while len(serverlist) > 0: > for server in serverlist: > if ping[server].returncode==None: > ping[server].poll() > else: > pingresult[server] = ping[server].stdout.read() > pingreturncode[server] = ping[server].returncode > serverlist.remove(server) How about something like this? while serverlist: server = serverlist.pop(0) pinger = ping[server] if pinger.returncode==None: pinger.poll() serverlist.append(server) else: pingresult[server] = pinger.stdout.read() pingreturncode[server] = pinger.returncode Basic idea: as long as there are servers in the list, pop the first one out of the list, see if it's done, and if it isn't, put it back on the end of the list. From http Sat Jun 23 11:16:38 2007 From: http (Paul Rubin) Date: 23 Jun 2007 08:16:38 -0700 Subject: Python's "only one way to do it" philosophy isn't good? References: <1181368143.874341.273140@r19g2000prf.googlegroups.com> <7x3b0nmkk6.fsf@ruckus.brouhaha.com> <1182608015.004758.49060@w5g2000hsg.googlegroups.com> Message-ID: <7xk5tur99l.fsf@ruckus.brouhaha.com> Michele Simionato writes: > BTW, there are already Python-like languages with macros > (i.e. logix) and still nobody use them, including people with a > Scheme/Lisp background. That should be telling you something. What about Dylan? From warren at muse.com Sat Jun 9 20:51:18 2007 From: warren at muse.com (Warren Stringer) Date: Sat, 9 Jun 2007 17:51:18 -0700 Subject: Hooking exceptions outside of call stack In-Reply-To: References: <001f01c7aab4$71153940$240110ac@Muse> Message-ID: <003c01c7aaf9$753b55f0$240110ac@Muse> Josiah Carlson wrote: > >>> foo = type(foo)(foo.func_code, d, foo.func_name, foo.func_defaults, > foo.func_closure) Wow! I've never seen that, before. Is there documentation for `type(n)(...)` somewhere? I did find a very useful "Decorator for Binding Constants, by Raymond Hettinger", that uses this technique. The calls are made from embedded classes that are constructed on the fly: class a(object): ... class b(object): ... class c(object): ... for `a.b[c]=1`, a.__getattr__('b') is called but 'c' need to be resolved as an object before a.b.__getitem__(c) is called. Could a.b.__init__ set globals so that 'c' gets resolved? Is this global namespace the same as the `globals()` namespace? Cheers, \~/ From gagsl-py2 at yahoo.com.ar Sat Jun 23 02:06:06 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 23 Jun 2007 03:06:06 -0300 Subject: newbie question about unicode References: <1182571819.128093.18980@i13g2000prf.googlegroups.com> Message-ID: En Sat, 23 Jun 2007 01:10:19 -0300, Genie T escribi?: > can anybody tell me whether these two expressions have the same > meanings? > > s = u'' > s1 = s.encode('utf-8') > > AND > > s1 = unicode(s,'utf-8') No - but consider this (assuming your terminal uses utf-8): py> u1 = u'' py> s1 = u1.encode('utf-8') py> py> s2 = '' py> u2 = s2.decode('utf-8') py> py> type(u1), type(u2) (, ) py> u1==u2 True py> type(s1), type(s2) (, ) py> s1==s2 True -- Gabriel Genellina From msj at infoserv.dk Tue Jun 26 10:03:53 2007 From: msj at infoserv.dk (Martin Skou) Date: Tue, 26 Jun 2007 16:03:53 +0200 Subject: text-mode tree viewer? In-Reply-To: <87y7i6j294.fsf@wilson.homeunix.com> References: <873b0fj9n5.fsf@wilson.homeunix.com> <46810112$0$6273$edfadb0f@dread14.news.tele.dk> <87y7i6j294.fsf@wilson.homeunix.com> Message-ID: <46811c92$0$6746$edfadb0f@dread14.news.tele.dk> Torsten Bronger wrote: > > It doesn't show Paul and Mary on the same level. I (think I) solved > the problem with this: > I could do so if Poul was in a list of his own, like "Arthur" and "Clara". /Martin From kyosohma at gmail.com Tue Jun 26 17:03:38 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Tue, 26 Jun 2007 14:03:38 -0700 Subject: subprocess.Popen() problem In-Reply-To: <1182890310.087603.273390@n60g2000hse.googlegroups.com> References: <1182890310.087603.273390@n60g2000hse.googlegroups.com> Message-ID: <1182891818.301472.33210@q69g2000hsb.googlegroups.com> On Jun 26, 3:38 pm, 7stud wrote: > I have this program: > > mytest.py > -------------- > myinput = raw_input("Enter input: ") > > if myinput == "hello": > print "goodbye" > -------------- > > and I want to execute it using subprocess.Popen(). I tried the > following but it just hangs: > > ----------- > import subprocess > > f = open("/Users/me/2testing/dir1/aaa.txt", "w") > my_path = "/Users/me/2testing/" > my_file = "mytest.py" > > p = subprocess.Popen(["python", "mytest.py"], stdin=subprocess.PIPE, > stdout = f, > stderr = f, > cwd = my_path > ) > > f.close() > > p.stdin.write("hello") > p.wait() > > f.open("/Users/me/2testing/dir1/aaa.txt") > print f.read() > ------------ Never tried this, but I think you need to use the communicate method detailed here: http://docs.python.org/dev/lib/node537.html If that doesn't work, you might look into using the threading module and its methods. Or there could be a flush command that I can't find... Mike From gnewsg at gmail.com Tue Jun 19 16:30:24 2007 From: gnewsg at gmail.com (billiejoex) Date: Tue, 19 Jun 2007 13:30:24 -0700 Subject: How can I know the name of "caller" Message-ID: <1182285024.048003.310120@n2g2000hse.googlegroups.com> Hi there, unfortunately, I'm compelled to apply a sort of monkey patching at the code of an existing libreary that I can't modify directly. Here's my question Having such code: class test: def caller(self): self.b() def called(self): pass ...(if it is possible) how can I get, from method "called", the name of function/method that called it (in this case "caller")? Thanks in advance From facundo at taniquetil.com.ar Fri Jun 1 09:16:46 2007 From: facundo at taniquetil.com.ar (Facundo Batista) Date: Fri, 01 Jun 2007 10:16:46 -0300 Subject: ImageMagick Issue In-Reply-To: <2adc542f0705311808g61b1ababob62ad7c7f58b2bbb@mail.gmail.com> References: <2adc542f0705302100g3135fd0fn1e6c3decd210bd5f@mail.gmail.com> <2adc542f0705311808g61b1ababob62ad7c7f58b2bbb@mail.gmail.com> Message-ID: <46601C3E.2050200@taniquetil.com.ar> Sick Monkey escribi?: > I ran into another slight problem. And I attempted to fix it, but have > not been able to do so yet. If a filename does not contain a space, > then this method works like a charm. But if there is a space then the > code throws a nasty error. Ok, the issue is that subprocess.Popen needs a list of the arguments. So, for simplicity, I made an string and then splitted it: >>> s = "ls -l /etc" >>> s.split() ['ls', '-l', '/etc'] >>> This does not work if you have spaces, even if you escape them: >>> s = "ls -l '/etc/mi file'" >>> s.split() ['ls', '-l', "'/etc/mi", "file'"] >>> But you can always build the list by hand: >>> subprocess.Popen(["ls", "-l", "'/etc/mi file'"], ... Regards, -- . Facundo . Blog: http://www.taniquetil.com.ar/plog/ PyAr: http://www.python.org/ar/ From steve at laniels.org Wed Jun 20 16:05:55 2007 From: steve at laniels.org (Stephen R Laniel) Date: Wed, 20 Jun 2007 16:05:55 -0400 Subject: PEP 3107 and stronger typing (note: probably a newbie question) In-Reply-To: <1182369568.941307.316260@p77g2000hsh.googlegroups.com> References: <1182369568.941307.316260@p77g2000hsh.googlegroups.com> Message-ID: <20070620200555.GC27969@slaniel-laptop.itasoftware.com> On Wed, Jun 20, 2007 at 12:59:28PM -0700, bruno.desthuilliers at gmail.com wrote: > Then you should use another language. This is what I meant about knowing how Internet discussions go. -- Stephen R. Laniel steve at laniels.org Cell: +(617) 308-5571 http://laniels.org/ PGP key: http://laniels.org/slaniel.key From S.Mientki-nospam at mailbox.kun.nl Sun Jun 10 16:03:58 2007 From: S.Mientki-nospam at mailbox.kun.nl (Stef Mientki) Date: Sun, 10 Jun 2007 22:03:58 +0200 Subject: Select one of 2 functions with the same name ? In-Reply-To: References: Message-ID: <99c4b$466c582c$d443bb3a$28936@news.speedlinq.nl> thanks Francesco and "7stud", The solution with objects is too difficult, because I want to stay very close to the orginal language, ( so the users can understand the Python code, and the automatic translation becomes as simple as possible). But after some tests, it seems to be quit simple: simulation_level = 0 def f1(): print 'f1' if simulation_level == 2: def f1(): print 'f2' f1() cheers, Stef Mientki Francesco Guerrieri wrote: > If the functions are > f1, f2, f3 you could go this way: > > def SimulationRun(): > if simulation_level = 1: SimulationFunction = f1 > else if simulation_level = 2: SimulationFunction = f2 > else .... > > > and in the rest of the code you can refer to SimulationFunction > instead of explicitly calling f1, f2 or f3. > > I'm sure that there are many smarter methods :-) > > > > On 6/10/07, Stef Mientki wrote: >> hello, >> >> For a simulation at different levels, >> I need different functions with the same name. >> Is that possible ? >> >> I can realize it with a simple switch within each function, >> but that makes the code much less readable: >> >> def Some_Function(): >> if simulation_level == 1: >> ... do things in a way >> elif simulation_level == 2: >> ... do things in another way >> elif simulation_level == 3: >> ... do things in yet another way >> >> >> thanks, >> Stef Mientki >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > > From john106henry at hotmail.com Sun Jun 24 15:40:00 2007 From: john106henry at hotmail.com (John Henry) Date: Sun, 24 Jun 2007 12:40:00 -0700 Subject: Adding method to a class on the fly In-Reply-To: <1182673146.373172.112750@g37g2000prf.googlegroups.com> References: <1182538969.522044.209560@q19g2000prn.googlegroups.com> <1182543862.369337.36880@z28g2000prd.googlegroups.com> <1182547065.295969.258820@g37g2000prf.googlegroups.com> <1182547724.690874.279230@g37g2000prf.googlegroups.com> <1182548694.545515.81060@e9g2000prf.googlegroups.com> <1182582129.462036.84560@m37g2000prh.googlegroups.com> <1182614796.146337.290300@x35g2000prf.googlegroups.com> <1182627099.634025.37430@m37g2000prh.googlegroups.com> <1182673146.373172.112750@g37g2000prf.googlegroups.com> Message-ID: <1182714000.259031.112070@o11g2000prd.googlegroups.com> On Jun 24, 1:19 am, John Henry wrote: > On Jun 23, 6:24 pm, Steven D'Aprano > > wrote: > > On Sat, 23 Jun 2007 12:31:39 -0700, John Henry wrote: > > > it works fine but PythonCard isn't calling this function when I > > > clicked on the button. > > > I think you need to take this question onto a PythonCard list. I have no > > idea how PythonCard decides which method to call. > > > -- > > Steven. > > I did. I am not sure I'll get an answer though. > > Thanks for the help. Upon further investigation, I found the problem. Pythoncard is relying on the __name__ attribute and that's why it didn't know about the newly careated function. I can not set that attribute directly, of course, since it's a readonly attribute. Need other workaround. The author of Pythoncard has responded and so I am shifting this thread over to the Pythoncard list. Thanks again for all the help. I learned a few things about Python through this exercise. From needpassion at gmail.com Mon Jun 4 20:03:02 2007 From: needpassion at gmail.com (mike) Date: Mon, 04 Jun 2007 17:03:02 -0700 Subject: how to print out each single char from a string in HEX format? In-Reply-To: References: <1180998219.005688.323200@r19g2000prf.googlegroups.com> Message-ID: <1181001782.216372.78410@r19g2000prf.googlegroups.com> Great! It works. Thanks a lot. From eadmund42 at NOSPAMgmail.com Sun Jun 24 21:51:00 2007 From: eadmund42 at NOSPAMgmail.com (Robert Uhl) Date: Sun, 24 Jun 2007 19:51:00 -0600 Subject: The Modernization of Emacs: terminology buffer and keybinding References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182272495.990807.99110@a26g2000pre.googlegroups.com> <87tzt3ihev.fsf@kobe.laptop> <1182370216.961241.6960@n60g2000hse.googlegroups.com> <85zm2ufjpb.fsf@lola.goethe.zz> <1182372592.803332.288260@u2g2000hsc.googlegroups.com> <1182373919.262388.100740@c77g2000hse.googlegroups.com> <85r6o6fhkb.fsf@lola.goethe.zz> <1182375045.626510.188170@m36g2000hse.googlegroups.com> <85myyufgwj.fsf@lola.goethe.zz> <1182375528.985142.293900@q69g2000hsb.googlegroups.com> <1182545268.055596.228700@i38g2000prf.googlegroups.com> <1182661040.286559.150880@q75g2000hsh.googlegroups.com> <1182731526.329068.101540@c77g2000hse.googlegroups.com> Message-ID: Twisted writes: > >> I have two frames open right now: one 80x70, the other around 180x70 >> (characters, not pixels). One isn't split at all; the other is split >> into four windows, horizontally and vertically. > > Then you're obviously not using the One True Emacs I am criticizing, > which is a console app. No, the One True Emacs supports GUIs. It has since 1991. Take a look at . >> emacs has continued doing its own thing, mostly because that thing is >> better. The CUA standards (there exists an emacs package if you >> really want them) are broken and lame--I and most other don't wish to >> cripple our text editor of choice. > > "CUA standards"? I'm sorry, I don't speak Botswanan. If you mean > Windows standards like for cut, copy, and paste, "broken and lame" is > obviously in the eye in the beholder, and something 97% of computer > users are used to is the defacto standard, so it's the other 3% that > are "broken and lame". ;) Popularity is no measure of goofness. > No, we're discussing ... oh, nevermind. It looks like there are > several utterly different pieces of software that have one thing in > common - the name "emacs". That is actually true. There's GNU emacs (the original and still the best). There's XEmacs (a fork of the same). Then there are a myriad of ancient emacsen, most particularly Gosling emacs. However, the only two which matter are GNU emacs and XEmacs. Both have supported a GUI for 16 years now. I don't have XEmacs installed, so I cannot tell you if it has the tutorial. I would be truly surprised if it didn't. >> Neither is right nor wrong; you're just used to one. The emacs keys are >> certainly more flexible and powerful, though. Some might consider them >> right for that reason. [snip] > This is also a change from your earlier position that they were, and I > quote, "broken and lame", assuming you mean the same stock Windoze > keybindings you meant with the cryptic term "CUA standards". Not really--they're broken and lame because they are less flexible and powerful. How 'bout you actually try using a modern emacs? It'll even support your chosen operating system. -- Robert Uhl Better to teach a man to fish than to give him a fish. And if he can't be bothered to learn to fish and starves to death, that's a good enough outcome for me. --Steve VanDevender, 1 May 2000 From kyosohma at gmail.com Thu Jun 28 13:43:19 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Thu, 28 Jun 2007 10:43:19 -0700 Subject: noob question How do I run a Python script. In-Reply-To: <1183051059.795931.299900@q75g2000hsh.googlegroups.com> References: <1183051059.795931.299900@q75g2000hsh.googlegroups.com> Message-ID: <1183052599.902628.89210@c77g2000hse.googlegroups.com> On Jun 28, 12:17 pm, CarlP wrote: > How do I run a Python script. I have one that gmail loader needs to > run on my email box. Here's the script > > http://www.marklyon.org/gmail/cleanmbox.py > > I can't seem to find what I need to run it. I installed python, run > the interpreter and the script , but all it will do is say invalid > syntax. > > Thanks Please post the traceback too. That will aid in helping you. Mike From borud-news at borud.no Wed Jun 20 08:30:08 2007 From: borud-news at borud.no (Bjorn Borud) Date: 20 Jun 2007 14:30:08 +0200 Subject: The Modernization of Emacs: terminology buffer and keybinding References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182272495.990807.99110@a26g2000pre.googlegroups.com> Message-ID: [Xah Lee ] to be quite honest, your proposal seems to largely be based on ignorance. | A: The terminology ?buffer? or ?keybinding?, are technical terms | having to do with software programing. The term ?keybinding? refers to | the association of a keystroke with a command in a technical, software | application programing context. That is to say, a programer ?bind? a | keystroke to a command in a software application. The term ?buffer? | refers to a abstract, temporary area for storing data, in the context | of programing or computer science. the term "buffer" is used extensively outside the computer science domain, so it is not a CS only term. in an editor it is actually a quite sensible name since it abstracts things a bit. for instance a buffer need not be associated with a file. nor does it make any assumptions about the way it is displayed (as opposed to "window" or "tab"). | These terms are irrelevant to the users of a software application. they are very relevant to me, and I am very much a user of Emacs. and again, they provide good abstractions. | As a user of a text editor, he works with files. learn Emacs before you criticize it. your assumption is wrong. in emacs you work on _buffers_. buffers often do not have files associated with them. | The terms ?opened file? or ?untitled file? are more appropriate than | ?buffer?. Since emacs is also used for many things beside reading | files or writing to files, for example, file management, ftp/sftp, | shell, email, irc etc., the proper term can be ?panel?, ?window?, or | ?work area?. "panel" and "window" refer to UI-elements. the buffer concept does not map 1:1 to any of these. substituting "work area" for "buffer" doesn't seem like a better abstraction. especially not if you see it in the context of how Emacs relates to buffer contents. | And, the term ?keyboard shortcut? refers to typing of a key- | combination to activate a command. It is also more appropriate than | ?binding? or ?keybinding?. why? if anything the term "shortcut" seems to imply that there is a primary route to executing the function in question -- which more often than not isn't the case. "keybinding" is a more precise term. | Although concepts like ?buffer? and ?keybinding? are seemingly | interchangeable with ?panel? or ?keyboard shortcut?, but their | contexts set them apart. they are interchangeable only if you have no idea what you are talking about. you obviously have not bothered to have a proper look at Emacs and think these things through properly. | This is why in all modern software application's user | documentations, terms like ?buffer? or ?keybinding? are not to be | seen but ?windows, panes, and keyboard shortcuts?. most "modern" editors are built on different premises than Emacs and many have a far simpler view of the world. extremely few of them even come close to Emacs in defining what is in practice an operating environment for applications. it makes sense to refer to "windows" when in fact you are referring to windows. it doesn't make sense to call buffers "windows" in Emacs; because they are not. | The reason emacs uses the technical terminologies throughout is | because when emacs started in the 1970s, there really isn't any other | text editors or even software applications. the abstractions you mention are sensible ones independently of when they were concieved. just because other people came along later and used different abstractions, doesn't mean that the ones used in Emacs are wrong, inferior or inappropriate. if you had bothered to understand Emacs properly, you would have found that some of the abstractions used make a lot of sense in an editor. | Changes in society are always resisted by old timers, but it is also a | main element behind progress. I've been in the computer industry long enough to have seen quite a few cycles of re-invention. each cycle you learn something about which inventions were good and which were bad. a common thread if you look at the survival rate of products and ideas is that it isn't always the best product or idea that wins. often something new comes along to replace something old. sometimes it is better than what you had before, but often it is not really better, just different. a good example is the web and the applications we implement in terms of the web. take forums for instance. in a strict technical sense, web-based forums are inferior to NNTP-based forums. (I am sure you can make the comparison yourself). yet NNTP-based discussion is not growing at the same rate as web forums. the net has chosen its preferred technology, and it wasn't because the web-based discussion forums were so much more technically refined that the majority chose them. for my uses, web forums are a huge step back from NNTP. | This terminology issue may seem trivial, but its importance lies in | making emacs palpable to the vast number of people who ever need to | use a computer to write. why? Emacs is a tool. if you don't like it: use something else. it is that simple. -Bj?rn From gagsl-py2 at yahoo.com.ar Fri Jun 29 00:14:53 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 29 Jun 2007 01:14:53 -0300 Subject: win32event.WaitForInputIdle() returns too soon References: <4684330c$0$742$3a628fcd@textreader.nntp.hccnet.nl> Message-ID: En Thu, 28 Jun 2007 19:15:40 -0300, Hans escribi?: > I'm sending keyboard and mouse events to a seperate windows application. > I use win32event.WaitForInputIdle() before calling e.g. > win32api.keybd_event() > However it seems that WaitForInputIdle() returns too soon because some > of my > events get lost. Now I'v created my own WaitForInputIdle() which calls From the Microsoft docs for WaitForInputIdle: "The WaitForInputIdle function only works with GUI applications. If a console application calls the function, it returns immediately, with no wait." A typical Python script is a console application. -- Gabriel Genellina From michele.simionato at gmail.com Mon Jun 25 08:09:47 2007 From: michele.simionato at gmail.com (Michele Simionato) Date: Mon, 25 Jun 2007 12:09:47 -0000 Subject: is this a valid import sequence ? In-Reply-To: References: <4f97$467c254d$d443bb3a$9522@news.speedlinq.nl> <137qo1egg4v1k04@corp.supernews.com> <1i0694u.1n6evsntoei0wN%aleax@mac.com> <1i06hm3.1ii0h87p707f2N%aleax@mac.com> <1182748080.330171.324800@g4g2000hsf.googlegroups.com> Message-ID: <1182773387.774151.249520@c77g2000hse.googlegroups.com> On Jun 25, 1:46 pm, Steven D'Aprano wrote: > To me, this code is redundant but not wrong: > > def sin(x): > return math.sin(x) > > It's not wrong, because it does everything that it is supposed to do, and > nothing that it isn't supposed to do. I told you, redundant/useless/misleading/poor code is worse than wrong: wrong code speaks (you see the bug, you have no choice but to fix it) whereas redundant code is silent: you see how damaging it is only when doing maintenance, i.e. too late, so it tends to perpetuate itself forever (whereas a bug *has* to be fixed, otherwise the application does not work). Michele Simionato From sjdevnull at yahoo.com Mon Jun 4 16:00:57 2007 From: sjdevnull at yahoo.com (sjdevnull at yahoo.com) Date: Mon, 04 Jun 2007 13:00:57 -0700 Subject: Who uses Python? In-Reply-To: <1180985830.288414.208850@q69g2000hsb.googlegroups.com> References: <1180985830.288414.208850@q69g2000hsb.googlegroups.com> Message-ID: <1180987257.435519.92770@q66g2000hsg.googlegroups.com> On Jun 4, 3:37 pm, walterbyrd wrote: > I mean other than sysadmins, programmers, and web-site developers? > > I have heard of some DBAs who use a lot of python. > > I suppose some scientists. I think python is used in bioinformatics. I > think some math and physics people use python. > > I suppose some people use python to learn "programming" in general. > Python would do well as a teaching language. > > I would think that python would be a good language for data analysis. > > Anything else? Finance? Web-analytics? SEO? Digital art? Presumably most of the above are "programmers" when they're writing programs in Python, right? It's a general purpose language that can be used for a very wide range of domains. FWIW, I do use it for digital art (music visualization). It's excellent for data analysis (I've done everything from stats on lines in an SQL database to mining flat text files of data for statistical projections of MLB baseball player performance). I know a couple of people who sell a double-entry accounting system written in Python, which is presumably "finance". Web analytics is very common (I've seen several such projects). I know at least one group using python as a control language in embedded systems (at least at one point a few years back they had opted for Stackless, but Python nonetheless); they're doing some cool home-automation style stuff. I've also written my window manager, various text editor extensions, numerous web applications, one-off data analysis scripts, several GUI applications, etc in Python (or mostly Python). The apps I've worked on range from one-offs at the command line to midrange scripts to multiple-hundreds-of-thousands of lines of code projects worked on by many developers. From steve at REMOVE.THIS.cybersource.com.au Wed Jun 6 20:34:55 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Thu, 07 Jun 2007 10:34:55 +1000 Subject: creating lists based on parsed items References: <0138071BF1642F49BD9826823E668663DCA87A@ex2.casl.umd.edu> <1181170167.160965.126760@g37g2000prf.googlegroups.com> Message-ID: On Wed, 06 Jun 2007 22:49:27 +0000, Basilisk96 wrote: >> If you are using Python 2.5, use a defaultdict instead, the very first >> example looks like what you want. >> >> >> -- >> Gabriel Genellina > > Uh-oh.. > I am using Python 2.5 on WinXP, but when I tried the examples in the > manual, I got a "NameError: name 'defaultdict' is not defined". What > am I missing in my Python installation? This would be a RTFM moment :) defaultdict is not a built-in, it is part of the collections module. You have to import collections first. >>> defaultdict Traceback (most recent call last): File "", line 1, in NameError: name 'defaultdict' is not defined >>> import collections >>> collections.defaultdict -- Steven. From sean.farrow at seanfarrow.co.uk Sat Jun 2 04:35:14 2007 From: sean.farrow at seanfarrow.co.uk (Sean Farrow) Date: Sat, 2 Jun 2007 09:35:14 +0100 Subject: Accessing the IRichEditOle interface Message-ID: Hi: Can anyone tell me how to access the IRichEditOle interface from python. I realise I have to send a M_GETOLEINTERFACE message to the window concerned but from then on I am stuck. I carn't seem to find a type library. Any help apreciated. I am using either com types or the win32 extensions it doesn't really matter. Regards Sean. From rw at smsnet.pl Mon Jun 18 10:14:22 2007 From: rw at smsnet.pl (Rob Wolfe) Date: Mon, 18 Jun 2007 07:14:22 -0700 Subject: Parsing HTML, extracting text and changing attributes. In-Reply-To: <1182175239.122827.4150@g4g2000hsf.googlegroups.com> References: <1182175239.122827.4150@g4g2000hsf.googlegroups.com> Message-ID: <1182176062.621465.14340@o61g2000hsh.googlegroups.com> seb... at gmail.com wrote: > So, I'm writing this to have your opinion on what tools I should use > to do this and what technique I should use. Take a look at parsing example on this page: http://wiki.python.org/moin/SimplePrograms -- HTH, Rob From survivedsushi at yahoo.com Mon Jun 25 21:27:29 2007 From: survivedsushi at yahoo.com (Matthew Peter) Date: Mon, 25 Jun 2007 18:27:29 -0700 (PDT) Subject: Return name of caller function? Message-ID: <652382.50464.qm@web35214.mail.mud.yahoo.com> For example, how do I get this to work? def func(): print "This is", __?__ return __caller__ def echo(): print "This is ", __?__ return func() >>> print echo() This is echo This is func echo ____________________________________________________________________________________ Yahoo! oneSearch: Finally, mobile search that gives answers, not web links. http://mobile.yahoo.com/mobileweb/onesearch?refer=1ONXIC From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Fri Jun 15 11:45:22 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Fri, 15 Jun 2007 17:45:22 +0200 Subject: IndentationError: unexpected indent References: <467134fe$0$66966$dbd49001@news.wanadoo.nl> Message-ID: <5dfqgiF34u6dtU2@mid.individual.net> "Wim Vogelaar" wrote: > You have possibly unvisible tab characters in your file. > Just copy your lines to the simple MS notepad and try again. How is he supposed to run MS notepad on X11? :) Regards, Bj?rn P.S.: YES, I know there is wine. -- BOFH excuse #126: it has Intel Inside From showell30 at yahoo.com Mon Jun 11 17:27:59 2007 From: showell30 at yahoo.com (Steve Howell) Date: Mon, 11 Jun 2007 14:27:59 -0700 (PDT) Subject: Python optimization (was Python's "only one way to do it" philosophy isn't good?) In-Reply-To: Message-ID: <937486.86963.qm@web33508.mail.mud.yahoo.com> --- John Nagle wrote: > > When you have to start buying more servers for > the server farm, > it's a real pain. I'm actually facing that because > Python's HTML > parsing is so slow. > I have been following this thread for a bit, but apologies in advance if I didn't read far back enough. Did you profile the module that you're using to do the HTML parsing? ____________________________________________________________________________________ Get the free Yahoo! toolbar and rest assured with the added security of spyware protection. http://new.toolbar.yahoo.com/toolbar/features/norton/index.php From james.p.turk at gmail.com Thu Jun 14 10:22:36 2007 From: james.p.turk at gmail.com (James Turk) Date: Thu, 14 Jun 2007 14:22:36 -0000 Subject: one-time initialization of class members In-Reply-To: References: <1181772494.803499.266690@o11g2000prd.googlegroups.com> <1181778902.547599.147960@q19g2000prn.googlegroups.com> <1181785384.380731.224550@n15g2000prd.googlegroups.com> Message-ID: <1181830956.214338.175980@o11g2000prd.googlegroups.com> On Jun 13, 11:42 pm, Steven Bethard wrote: > James Turk wrote: > > It actually occured to me that I could use a @classmethod to do the > > loading and take that out of the BaseClass constructor. What I have > > makes more sense and eliminates the unecessary constructors. > > > ie. > > > class BaseClass: > > @classmethod > > def loadData(params): > > #expensive load here > > > class ChildClass1(BaseClass): > > dataset = BaseClass.loadData(params) > > > This is pretty much along the lines of what you suggested, thank you > > for the hint in the right direction. > > > I realized that this still doesn't meet my needs exactly as I only > > want the expensive dataset to be loaded if/when a class is actually > > used (there are potentially many of these and only a few will be > > used). > > Seems like you want a lazy class attribute. How about something like:: > > >>> class LazyClassAttribute(object): > ... def __init__(self, func): > ... self.func = func > ... def __get__(self, obj, cls=None): > ... value = self.func(cls) > ... setattr(cls, self.func.__name__, value) > ... return value > ... > >>> class Base(object): > ... @LazyClassAttribute > ... def dataset(cls): > ... print 'calculating dataset' > ... return 'dataset(%s)' % cls.params > ... > >>> class Child1(Base): > ... params = 'foo' > ... > >>> class Child2(Base): > ... params = 'bar' > ... > >>> Child1.dataset > calculating dataset > 'dataset(foo)' > >>> Child1.dataset > 'dataset(foo)' > >>> Child2.dataset > calculating dataset > 'dataset(bar)' > >>> Child2.dataset > 'dataset(bar)' > > The idea is basically similar to the @classmethod approach except that > instead of @classmethod, we use a custom descriptor that calls the > method the first time it's accessed and then stores that value > afterwards. This means that instead of explicitly calling the > @classmethod, the method will be called whenever the attribute is first > accessed. > > STeVe This is a pretty interesting idea, I hadn't thought of using a decorator to get this behavior. I'm evaluating it and will see if it fits in with the rest of the system well, but it certainly is a unique solution to this problem. From NoSpam at Hccnet.nl Sat Jun 30 15:58:23 2007 From: NoSpam at Hccnet.nl (Hans) Date: Sat, 30 Jun 2007 21:58:23 +0200 Subject: win32event.WaitForInputIdle() returns too soon References: <4684330c$0$742$3a628fcd@textreader.nntp.hccnet.nl> <4685657e$0$734$3a628fcd@textreader.nntp.hccnet.nl> <1183148539.304679.77690@m36g2000hse.googlegroups.com> Message-ID: <4686b5e0$0$737$3a628fcd@textreader.nntp.hccnet.nl> schreef in bericht news:1183148539.304679.77690 at m36g2000hse.googlegroups.com... On Jun 29, 3:03 pm, "Hans" wrote: > "Gabriel Genellina" schreef in > berichtnews:mailman.184.1183090500.22759.python-list at python.org... > > > > > En Thu, 28 Jun 2007 19:15:40 -0300, Hans escribi?: > > >> I'm sending keyboard and mouse events to a seperate windows > >> application. > >> I use win32event.WaitForInputIdle() before calling e.g. > >> win32api.keybd_event() > >> However it seems that WaitForInputIdle() returns too soon because some > >> of my > >> events get lost. Now I'v created my own WaitForInputIdle() which calls > > > From the Microsoft docs for WaitForInputIdle: "The WaitForInputIdle > > function only works with GUI applications. If a console application > > calls > > the function, it returns immediately, with no wait." > > A typical Python script is a console application. > > > -- > > Gabriel Genellina > > It would explain my problem. > Perhaps I could create a small windows application as interface.. > I have to think about it ( and wait, as I currently don't have access to > visual C++, nor the MS documentation) > > Thanks, > Hans : Who says you have to create it with Visual C++? You could use Tkinter : or wxPython. Both are pretty easy to pick up and can look professional : with a little work. : Mike Nobody. However, yesterday I tried wrapping my piece of offending code into a very simple Tkinter application. Alas, the problem wasn't solved. WaitForInputIdle() returns too soon (unless I don't understand WaitForInputIdle(), which is actually a Microsoft call. Therefore using Visual Studio is sometimes handier: doc available and most compatible with Microsoft's quirks) Any other suggestions are welcome. Cheers, Hans From samuraiblog at gmail.com Wed Jun 13 12:23:13 2007 From: samuraiblog at gmail.com (samuraisam) Date: Wed, 13 Jun 2007 09:23:13 -0700 Subject: Bytes/File Size Format Function In-Reply-To: References: <1181706472.008233.80050@a26g2000pre.googlegroups.com> Message-ID: <1181751793.182399.312260@j4g2000prf.googlegroups.com> Haha, you guys. Use it however you want. But trust me, if you put MiB and GiB instead of the more-common mb and gb [MB and GB] in your applications, your users will probably have a harder time understanding what you mean. From streamservenl at gmail.com Thu Jun 21 07:11:39 2007 From: streamservenl at gmail.com (jvdb) Date: Thu, 21 Jun 2007 11:11:39 -0000 Subject: How to hide a program? In-Reply-To: References: <1182347596.414718.117190@w5g2000hsg.googlegroups.com> <5dsq6hF36eulqU1@mid.uni-berlin.de> <1182349569.122969.284950@q19g2000prn.googlegroups.com> Message-ID: <1182424299.887904.4330@p77g2000hsh.googlegroups.com> Hi all, thanks very much! it was indeed how i compiled to .exe After using the windows= , my issue was solved. Thanks to all who took the time on helping me. Jeroen From matiassurdi at gmail.com Fri Jun 1 03:32:47 2007 From: matiassurdi at gmail.com (Matias Surdi) Date: Fri, 01 Jun 2007 09:32:47 +0200 Subject: Delete a file from a CGI Message-ID: HI! I want to delete a file from a CGI, but I always get a Permission denied error. I've tryed this after creating the file (from a normal script): os.chmod(".lock",stat.S_IMODE(stat.S_IRWXU | stat.S_IRWXO | stat.S_IRWXG)) os.chown(".lock",pwd.getpwnam("nobody")[2],pwd.getpwnam("nobody")[3]) but the CGI still can't delete the file. I will appreciate very much your help. Thanks a lot. From tundra at tundraware.com Wed Jun 6 11:11:35 2007 From: tundra at tundraware.com (Tim Daneliuk) Date: Wed, 06 Jun 2007 10:11:35 -0500 Subject: Can os.remove followed by os.path.isfile disagree? In-Reply-To: <1181140547.279974.83550@q66g2000hsg.googlegroups.com> References: <1181140547.279974.83550@q66g2000hsg.googlegroups.com> Message-ID: <4666CEA7.8030301@tundraware.com> ppaterson at gmail.com wrote: > > The application is multithreaded so it is possible that another thread > writes to the file between the "remove" and the "isfile", but at the > end of the failure the file is actually not on the filesystem and I > don't believe there is a way that the file could be removed again in > this scenario. > This sure sounds like a thread race condition. In theory, the os.remove call failing to actually remove the file before returning might also do this, but it seems unlikely that a bug that blatant in a fundamental OS call could survive very long, even in Windoze. I'd take the time to really examine the multiple threads of work you're running to make sure one of them isn't removing the file just as another creates it. Better still, use a locking semaphore around the code the creates/deletes the file to guarantee mutual exclusion. From iansan at gmail.com Tue Jun 12 15:16:45 2007 From: iansan at gmail.com (IamIan) Date: Tue, 12 Jun 2007 19:16:45 -0000 Subject: Splitting SAX results In-Reply-To: References: <1181187340.685296.284850@i38g2000prf.googlegroups.com> <4667A954.8070909@web.de> <1181335953.348151.57540@n15g2000prd.googlegroups.com> Message-ID: <1181675805.996632.311070@r19g2000prf.googlegroups.com> I do know how split works, but thank you for the response. The end result that I want is a dictionary made up of the title results coming through SAX, looking like {'Title1: Description', 'Title2:Description'}. The XML data looks like: Title1:Description Link Desc Author Date Title2:Description Link Desc Author Date I've tried different approaches, a couple of which I've added to the code below (only running one option at a time): from xml.sax import make_parser from xml.sax.handler import ContentHandler tracker = [] # Option 1 tracker = {} # Option 2 class reportHandler(ContentHandler): def __init__(self): self.isReport = 0 def startElement(self, name, attrs): if name == 'title': self.isReport = 1 self.reportText = '' def characters(self, ch): if self.isReport: self.reportText += ch tracker.append(ch) # Option 1 key, value = ch.split (':') # Option 2 tracker[key] = value def endElement(self, name): if name == 'title': self.isReport = 0 print self.reportText parser = make_parser() parser.setContentHandler(reportHandler()) parser.parse('http://www.some.com/rss/') print tracker Option 1 returns a list with the markup included, looking like: [u'Title1:", u'\n', u'Description ', u'\n', u'\t\t\t', u'Title2:', u'\n', u'Description ', u'\n', u'\t\t\t', etc] Option 2 fails with the traceback: File "C:\test.py", line 21, in characters key, value = ch.split(':') ValueError: need more than 1 value to unpack Thank you for the help! From laurent.pointal at limsi.fr Thu Jun 14 08:40:54 2007 From: laurent.pointal at limsi.fr (Laurent Pointal) Date: Thu, 14 Jun 2007 14:40:54 +0200 Subject: IndentationError: unexpected indent In-Reply-To: References: Message-ID: desktop a ?crit : > I have this class: > > class case(blop.case): > def __init__(self, n, a, b): > blop.case.__init__(self) > print 'Monty Python's Flying Circus has a ' within it...' > ... > ... > > But I get an error when I run the .py script from shell saying: > > print 'Monty Python's Flying Circus has a ' within it...' > ^ > IndentationError: unexpected indent > > I have tried to indent the print statement 8 blanks but that does not > help. Any hints? You have also another error: >>> print 'Monty Python's Flying Circus has a ' within it...' File "", line 1 print 'Monty Python's Flying Circus has a ' within it...' ^ SyntaxError: invalid syntax Better: >>> print "Monty Python's Flying Circus has a ' within it..." Monty Python's Flying Circus has a ' within it... Note: for your indentation problem, try to use an editor allowing to display tab and spaces and then identify the problem location, or replace all tabs by 4 spaces and configure the editor to only use spaces. From senwin30 at gmail.com Wed Jun 27 14:02:28 2007 From: senwin30 at gmail.com (senthil arasu) Date: Wed, 27 Jun 2007 13:02:28 -0500 Subject: Tabbed windows Support in Python Message-ID: <1ef9860e0706271102m466cf4a7k1f55f76517d456b3@mail.gmail.com> Hi, Currently iam implementing GUI Framework for supporting Tabbed windows to render different HTML Pages. A row of tabs facilitated for navigation of pages. Iam expecting some classes like "QTabWidget" whick provided by Qt Libarary. After starting my implementation i came to know Tkinter not supports tabbed windows is there anybody to help me how to proceed further. thanks in advance -------------- next part -------------- An HTML attachment was scrubbed... URL: From len-l at telus.net Tue Jun 19 16:38:34 2007 From: len-l at telus.net (Lenard Lindstrom) Date: Tue, 19 Jun 2007 20:38:34 GMT Subject: metaclasses and performance In-Reply-To: References: Message-ID: Mirko Dziadzka wrote: > Hi all > > I'm playing around with metaclasses and noticed, that there is small > but mesurable a performance difference in the code shown below. With a > more complex example I get a 5 percent performance penalty for using a > metaclass. Until today I assumed, that a metaclass has no performance > impact at all after class creation. > Can someone explain me the performance difference between the two classes > test1 and test2 > > Thank's in advance > > Mirko > > ---- cut here ----- > > class meta(type): > pass > > class test1(object): > __metaclass__ = meta # using type via meta here > def __init__(self): > self.foo = 42 > def get_foo(self): > return self.foo > > class test2(object): > __metaclass__ = type # using type directly > def __init__(self): > self.foo = 42 > def get_foo(self): > return self.foo > > # and here the performance test code ... it's only 2% on my machine > import time > for c in [test1, test2] * 10: > t = c() > start = time.time() > for i in xrange(10 * 1000 * 1000): > t.get_foo() > print c.__name__, time.time() - start > > ---- cut here ----- > > I don't know if C asserts are active in release Python, but for new-style classes one thing that happens during attribute lookup is that an object's class is asserted to be an instance of type. Class test2 immediately passes the test since its type is "type". But test1's type is meta, so a function is called to check that meta is a subclass of "type". This may be the cause of the slowdown. Otherwise attribute lookups for test1 and test2 instances are identical. -- Lenard Lindstrom From DustanGroups at gmail.com Thu Jun 7 07:40:21 2007 From: DustanGroups at gmail.com (Dustan) Date: Thu, 07 Jun 2007 11:40:21 -0000 Subject: get a list from a string In-Reply-To: References: <1181213434.814684.236770@q19g2000prn.googlegroups.com> Message-ID: <1181216421.650317.321680@w5g2000hsg.googlegroups.com> On Jun 7, 6:06 am, simon kagwe wrote: > > exec("distances = [[1,1,1,1],[2,2,2,2]]") To be clear, exec is *not* a function; it's a statement. That means it can't be used in lambda functions, for example. > Wow! So simple! but dodgy, as it'll execute any python code. > Thanks a lot. :-) From kyosohma at gmail.com Mon Jun 4 16:36:59 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Mon, 04 Jun 2007 13:36:59 -0700 Subject: wxPython splitwindow with interpreter on bottom In-Reply-To: <1180969036.773130.219700@n4g2000hsb.googlegroups.com> References: <1180969036.773130.219700@n4g2000hsb.googlegroups.com> Message-ID: <1180989419.705079.251540@k79g2000hse.googlegroups.com> On Jun 4, 9:57 am, chewie54 wrote: > Hi all, > > Does anyone know of an example of wxPython source code that shows how > to put a python shell (interpreter) in a bottom window with a > graphical application in the top window? > > Thanks, There's the pyCrust/pyShell examples in the wxPython demo. They are quite similar to what you want, I think. Mike From kw at codebykevin.com Wed Jun 13 18:13:28 2007 From: kw at codebykevin.com (Kevin Walzer) Date: Wed, 13 Jun 2007 18:13:28 -0400 Subject: Build EXE on Mac OsX 10.4 In-Reply-To: References: <1181762699.145088.159500@j4g2000prf.googlegroups.com> Message-ID: <46706C08.8020809@codebykevin.com> Paul McNett wrote: > Tempo wrote: >> Has anyone sucesfully built a *.exe file on a mac operating system >> before from a *.py file? I have been trying to do this with >> pyinstaller, but I keep getting errors and I don't know how to install >> UPX properly. I tried putting the linux UPX folder in my python 2.4 >> directory, but that didn't work. I am just generally confused right >> now. Ha. If anybody can lend me some insight I would really appreciate >> it. Thank you for taking the time to read this post. > > You need to build Mac Apps on Mac, Windows EXE's on Windows, and Linux > ELF's on Linux. You can't build a windows.exe from Mac, just as you > can't build a mac.app from Windows. > Also, use py2app--that's the standard on the Mac. I don't believe pyinstaller works on OS X. -- Kevin Walzer Code by Kevin http://www.codebykevin.com From adam at atlas.st Wed Jun 27 00:48:46 2007 From: adam at atlas.st (Adam Atlas) Date: Tue, 26 Jun 2007 21:48:46 -0700 Subject: PyKQueue Message-ID: <1182919726.121679.292020@g4g2000hsf.googlegroups.com> Does anyone have a copy of PyKQueue 2.0 around? The site it's supposed to be on (http://python-hpio.net/trac/wiki/PyKQueue) is down. From malkarouri at gmail.com Sat Jun 30 11:30:43 2007 From: malkarouri at gmail.com (malkarouri at gmail.com) Date: Sat, 30 Jun 2007 15:30:43 -0000 Subject: Python Memory Usage In-Reply-To: <1182311282.752464.143150@g37g2000prf.googlegroups.com> References: <1182311282.752464.143150@g37g2000prf.googlegroups.com> Message-ID: <1183217443.893850.176880@c77g2000hse.googlegroups.com> On Jun 20, 4:48 am, "greg.no... at gmail.com" wrote: > I am using Python to process particle data from a physics simulation. > There are about 15 MB of data associated with each simulation, but > there are many simulations. I read the data from each simulation into > Numpy arrays and do a simple calculation on them that involves a few > eigenvalues of small matricies and quite a number of temporary > arrays. I had assumed that that generating lots of temporary arrays > would make my program run slowly, but I didn't think that it would > cause the program to consume all of the computer's memory, because I'm > only dealing with 10-20 MB at a time. > > So, I have a function that reliably increases the virtual memory usage > by ~40 MB each time it's run. I'm measuring memory usage by looking > at the VmSize and VmRSS lines in the /proc/[pid]/status file on an > Ubuntu (edgy) system. This seems strange because I only have 15 MB of > data. > > I started looking at the difference between what gc.get_objects() > returns before and after my function. I expected to see zillions of > temporary Numpy arrays that I was somehow unintentionally maintaining > references to. However, I found that only 27 additional objects were > in the list that comes from get_objects(), and all of them look > small. A few strings, a few small tuples, a few small dicts, and a > Frame object. > > I also found a tool called heapy (http://guppy-pe.sourceforge.net/) > which seems to be able to give useful information about memory usage > in Python. This seemed to confirm what I found from manual > inspection: only a few new objects are allocated by my function, and > they're small. > > I found Evan Jones article about the Python 2.4 memory allocator never > freeing memory in certain circumstances: http://evanjones.ca/python-memory.html. > This sounds a lot like what's happening to me. However, his patch was > applied in Python 2.5 and I'm using Python 2.5. Nevertheless, it > looks an awful lot like Python doesn't think it's holding on to the > memory, but doesn't give it back to the operating system, either. Nor > does Python reuse the memory, since each successive call to my > function consumes an additional 40 MB. This continues until finally > the VM usage is gigabytes and I get a MemoryException. > > I'm using Python 2.5 on an Ubuntu edgy box, and numpy 1.0.3. I'm also > using a few routines from scipy 0.5.2, but for this part of the code > it's just the eigenvalue routines. > > It seems that the standard advice when someone has a bit of Python > code that progressively consumes all memory is to fork a process. I > guess that's not the worst thing in the world, but it certainly is > annoying. Given that others seem to have had this problem, is there a > slick package to do this? I envision: > value = call_in_separate_process(my_func, my_args) > > Suggestions about how to proceed are welcome. Ideally I'd like to > know why this is going on and fix it. Short of that workarounds that > are more clever than the "separate process" one are also welcome. > > Thanks, > Greg I had almost the same problem. Will this do? http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/511474 Any comments are welcome (I wrote the recipe with Pythonistas' help). Regards, Muhammad Alkarouri From misiek3d at gmail.com Thu Jun 28 06:07:26 2007 From: misiek3d at gmail.com (misiek3d) Date: Thu, 28 Jun 2007 10:07:26 -0000 Subject: Can IronPython work as Windows Scripting Host (WSH) language? Message-ID: <1183025246.292300.67210@g4g2000hsf.googlegroups.com> Hello I want to use IronPython as Windows Scripting Host language. Is it possible? How can I do it? I know that ActivePython works as WSH language but for specific reasons I need to use IronPython. regards Michal From rplobue at gmail.com Sat Jun 9 18:58:23 2007 From: rplobue at gmail.com (rplobue at gmail.com) Date: Sat, 09 Jun 2007 22:58:23 -0000 Subject: urllib2 - iteration over non-sequence In-Reply-To: <466B2AA7.3040704@websafe.com> References: <1181427526.996101.75230@m36g2000hse.googlegroups.com> <466B2AA7.3040704@websafe.com> Message-ID: <1181429903.533207.105730@p77g2000hsh.googlegroups.com> Thanks for the reply Larry but I am still having trouble. If i understand you correctly, your are just suggesting that i add an http:// in front of the address? However when i run this: >>> import urllib2 >>> site = urllib2.urlopen('http://www.google.com') >>> for line in site: >>> print line I am still getting the message: TypeError: iteration over non-sequence File "", line 1 TypeError: iteration over non-sequence From radamand at gmail.com Mon Jun 11 16:26:34 2007 From: radamand at gmail.com (Radamand) Date: Mon, 11 Jun 2007 20:26:34 -0000 Subject: REALLY need help with iterating a list. In-Reply-To: <1181588376.426556.46530@j4g2000prf.googlegroups.com> References: <1181586648.614514.228900@m36g2000hse.googlegroups.com> <1181588376.426556.46530@j4g2000prf.googlegroups.com> Message-ID: <1181593594.952263.50960@p77g2000hsh.googlegroups.com> On Jun 11, 12:59 pm, infidel wrote: > On Jun 11, 11:30 am, Radamand wrote: > > > > > This has been driving me buggy for 2 days, i need to be able to > > iterate a list of items until none are left, without regard to which > > items are removed. I'll put the relevant portions of code below, > > please forgive my attrocious naming conventions. > > Basically i'm trying to spin up some subprocesses that will ping a > > group of servers and then wait until all of them have completed (good > > or bad), store the ping result and the return code, and move on. > > The problem comes in the second block, when i try to iterate the > > list of servers and remove the ones that are finished, for some reason > > Python appears to re-index the list when I remove an item and the next > > step through the loop it cant find the item its expecting because the > > indexes have changed. > > Any assistance would be appreciated... > > > ============================================================================= > > for server in serverlist: > > ping[server] = subprocess.Popen("ping -c 1 " + str(server) + " 5", > > shell=True, stdout=subprocess.PIPE) > > > while len(serverlist) > 0: > > for server in serverlist: > > if ping[server].returncode==None: > > ping[server].poll() > > else: > > pingresult[server] = ping[server].stdout.read() > > pingreturncode[server] = ping[server].returncode > > serverlist.remove(server) > > How about something like this? > > while serverlist: > server = serverlist.pop(0) > pinger = ping[server] > if pinger.returncode==None: > pinger.poll() > serverlist.append(server) > else: > pingresult[server] = pinger.stdout.read() > pingreturncode[server] = pinger.returncode > > Basic idea: as long as there are servers in the list, pop the first > one out of the list, see if it's done, and if it isn't, put it back on > the end of the list. I like this idea, ill try it out asap. ok, tried it, works perfectly!! It never occurred to me to use pop to pull one off and put it back on if it wasnt done, very nice! Thank You!! From kyosohma at gmail.com Sat Jun 30 19:31:09 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Sat, 30 Jun 2007 23:31:09 -0000 Subject: Python + Google Calendar API issue Message-ID: <1183246269.152344.3510@c77g2000hse.googlegroups.com> Hi, I was trying to hook into Google Calendar today using their gdata module for Python, but I can't seem to get Python to work with it. When I run the setup.py from the command line, I get the following: Traceback (most recent call last): File "J:\Python\Lib\site-packages\gdata\setup.py", line 39, in ? package_dir = {'gdata':'src/gdata', 'atom':'src/atom'} File "J:\Python\lib\distutils\core.py", line 137, in setup raise SystemExit, gen_usage(dist.script_name) + "\nerror: %s" % msg SystemExit: usage: setup.py [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...] or: setup.py --help [cmd1 cmd2 ...] or: setup.py --help-commands or: setup.py cmd --help error: no commands supplied I tried using some different commands, like --verbose, but it would just give me the same traceback. I also tried manually copying all the files into my site-packages directory (as you can see from the traceback) in hopes that it might work without running the setup.py file. Does anyone have any ideas? I don't usually have any problem getting these things to work. I am using Python 2.4.3 on Windows XP Pro SP2. Thanks a lot! Mike From nick at craig-wood.com Sun Jun 10 01:36:25 2007 From: nick at craig-wood.com (Nick Craig-Wood) Date: Sun, 10 Jun 2007 00:36:25 -0500 Subject: Bug/Weak Implementation? popen* routines can't handle simultaneous read/write? References: <1181232071.928835.301710@w5g2000hsg.googlegroups.com> <1181264380.441881.38570@i13g2000prf.googlegroups.com> <1181330055.380987.294550@p47g2000hsd.googlegroups.com> Message-ID: dmoore wrote: > On Jun 8, 12:30 pm, Nick Craig-Wood wrote: > > Windows has a really strange idea of non-blocking IO - it uses > > something called overlapped io. You or in the FILE_FLAG_OVERLAPPED > > flag when you create the file/pipe. You then pass in overlap buffers > > for reading writing. > > > > the wx guys appear to do it differently (unless FILE_FLAG_OVERLAPPED > is implicit in the calls they make) > > take a look at: > http://cvs.wxwidgets.org/viewcvs.cgi/wxWidgets/src/msw/utilsexc.cpp?rev=1.88&content-type=text/vnd.viewcvs-markup > > a reasonably well-documented wxExecute function handles all the messy > win32 api calls and wraps the process in a wxProcess object and the > streams in wxInputStream / wxOutputStream (also see the wxExecuteDDE > function) You are right, named pipes seem to have a non blocking mode. Here is the lowdown from http://msdn2.microsoft.com/en-US/library/aa365605.aspx Both pipe clients and pipe servers can change a pipe handle's wait mode by specifying either PIPE_WAIT or PIPE_NOWAIT in a call to the SetNamedPipeHandleState function. Note The nonblocking-wait mode is supported for compatibility with Microsoft? LAN Manager version 2.0. This mode should not be used to achieve overlapped input and output (I/O) with named pipes. Overlapped I/O should be used instead, because it enables time-consuming operations to run in the background after the function returns. For more information about overlapped I/O, see Synchronous and Overlapped Input and Output. So it has a nonblocking mode but you shouldn't use it! -- Nick Craig-Wood -- http://www.craig-wood.com/nick From jloden at jayloden.com Tue Jun 19 00:52:41 2007 From: jloden at jayloden.com (Jay Loden) Date: Tue, 19 Jun 2007 00:52:41 -0400 Subject: Does altering a private member decouple the property's value? In-Reply-To: <1hzx8yb.t6r2y71wuilpzN%aleax@mac.com> References: <1hzx8yb.t6r2y71wuilpzN%aleax@mac.com> Message-ID: <46776119.20008@jayloden.com> Alex Martelli wrote: > >>>>> class a_class: > > This is ALL of the problem: you're using a legacy (old-style) class, and > properties (particularly setters) don't work right on its instances (and > cannot, for backwards compatibility: legacy classes exist exclusively to > keep backwards compatibility with Python code written many, many years > ago and should be avoided in new code). > > Change that one line to > > class a_class(object): > > and everything else should be fine. If you want, I can try to explain > the why's and wherefore's of the problem, but to understand it requires > deeper knowledge of Python than you'll need for just about any practical > use of it: just retain the tidbit "NEVER use oldstyle classes" and you > won't need to understand WHY you shouldn't use them:-). Can you elaborate (or just point me to a good doc) on what you mean by an "old style" class versus the new style? I learned Python (well, am still learning) from an older book, and I just want to make sure that I'm using the preferred method. Thanks, -Jay From half.italian at gmail.com Mon Jun 4 13:23:00 2007 From: half.italian at gmail.com (half.italian at gmail.com) Date: Mon, 04 Jun 2007 17:23:00 -0000 Subject: get_traceback Message-ID: <1180977780.997361.133320@g37g2000prf.googlegroups.com> Hi, Is there a function or idoim for returning an exception/traceback rather than just printing it to stdout? I'm running a deamon where stdout is going to /dev/null, and I'm not even watching it..until now. All the functions I found in traceback and sys seemed only to print the error rather than just returning it, so I resorted to this: def get_traceback(): import traceback, tempfile stdout = sys.stdout f = tempfile.TemporaryFile(mode='w+') sys.stdout = f traceback.print_tb(sys.exc_info()[2]) error = f.read() f.close() sys.stdout = stdout return error Whats the right function?!? Thanks. ~Sean From gagsl-py2 at yahoo.com.ar Mon Jun 4 00:24:36 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 04 Jun 2007 01:24:36 -0300 Subject: can this be implemented? References: <1180828469.633454.105970@z28g2000prd.googlegroups.com> Message-ID: En Sat, 02 Jun 2007 20:54:29 -0300, greenflame escribi?: > When I first learned about programming, I started with BASIC, QBASIC > to be more accurate. While I was at that stage, I learned about the > INPUT command. I used it abundantly. > > Ok so now for the actual issue. > > I would like to implement something like the INPUT command from BASIC. > I failed to find something on the python website documentation for > beginners. This BASIC program: INPUT "Your name"; z$ PRINT "Hello, "; z$ would be this in Python: name = raw_input("Your name? ") print "Hello,", name raw_input is a built-in function, see http://docs.python.org/lib/built-in-funcs.html#l2h-59 -- Gabriel Genellina From apatheticagnostic at gmail.com Mon Jun 11 04:11:50 2007 From: apatheticagnostic at gmail.com (kaens) Date: Mon, 11 Jun 2007 04:11:50 -0400 Subject: Are there any python jobs worked at home from the internet? In-Reply-To: References: Message-ID: <163f0ce20706110111qc04d95rbc08b14381fd1f81@mail.gmail.com> On 6/9/07, Gabriel Genellina wrote: > En Sat, 09 Jun 2007 22:53:08 -0300, boyeestudio > escribi?: > > > Are there any python jobs worked at home from the internet? > > I want to find a part time job. > > Please give a clue to this for me. > > I know of http://www.rentacoder.com/ but I've never actually used it. > > -- > Gabriel Genellina > > -- I'm on RAC, and I'm doing python work right now, but python stuff is more or less few and far between on RAC. If you know a few different languages, or can pick them up quickly, there is a good amount of employment opportunity on RAC. Most of the "bids" right now seem to be for PHP work or more general web + random.choice(['design', 'app']) stuff. But yeah, python works pops up here and there, and when it does it tends to be pretty interesting stuff. > http://mail.python.org/mailman/listinfo/python-list > From bjourne at gmail.com Tue Jun 19 20:57:30 2007 From: bjourne at gmail.com (=?ISO-8859-1?Q?BJ=F6rn_Lindqvist?=) Date: Wed, 20 Jun 2007 02:57:30 +0200 Subject: Q: listsort and dictsort - official equivalents? In-Reply-To: <1182302544.4202.40.camel@delta.sgr-a.net> References: <1182302544.4202.40.camel@delta.sgr-a.net> Message-ID: <740c3aec0706191757i43204155o89f4b37ed0bc68eb@mail.gmail.com> > In python I must kick off a sort on the line before I start the > iteration. (This does make sense because at the end of the day the sort > has complete BEFORE the for loop can proceed - that is... until the day > when python lists have a secondary index ;-). > > group_list=group_dict.keys() > group_list.sort() > for group in group_list: # do > print group,group_dict[group] > # done > > I am sure python has a more concise way of doing this, any hints? for group in sorted(open("/etc/group")): print group, It's not true that the sort must complete (or that the whole file must be read for that matter), Python has cool generators which makes the above possible. You can even sort by the gid: for group in sorted(open("/etc/group"), key = lambda x: int(x.split(':')[2])): print group, -- mvh Bj?rn From eadmund42 at NOSPAMgmail.com Sat Jun 23 20:49:56 2007 From: eadmund42 at NOSPAMgmail.com (Robert Uhl) Date: Sat, 23 Jun 2007 18:49:56 -0600 Subject: The Modernization of Emacs: terminology buffer and keybinding References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182272495.990807.99110@a26g2000pre.googlegroups.com> <87tzt3ihev.fsf@kobe.laptop> <1182370216.961241.6960@n60g2000hse.googlegroups.com> <85zm2ufjpb.fsf@lola.goethe.zz> <1182372592.803332.288260@u2g2000hsc.googlegroups.com> <1182549094.366282.286740@m37g2000prh.googlegroups.com> <87bqf7fwmg.fsf@telesippa.clsnet.nl> <1182553682.197778.138500@g37g2000prf.googlegroups.com> Message-ID: nebulous99 at gmail.com writes: > > So now we're expected to go on a filesystem fishing expedition instead > of just hit F1? Interestingly enough, f1 _is_ bound to the help system in emacs. So's C-h. So's the 'help' key. -- Robert Uhl That's why I love VoIP. You don't get people phoning up to complain that the network is down. --Peter Corlett From Stebanoid at gmail.com Sun Jun 3 09:41:20 2007 From: Stebanoid at gmail.com (Stebanoid at gmail.com) Date: Sun, 03 Jun 2007 13:41:20 -0000 Subject: c[:]() In-Reply-To: References: <1180504190.055427.173610@h2g2000hsg.googlegroups.com> <1180504773.374529.161740@q66g2000hsg.googlegroups.com> Message-ID: <1180878080.630213.258230@q75g2000hsh.googlegroups.com> On 30 , 22:48, "Warren Stringer" wrote: > I want to call every object in a tupple, like so: > > #------------------------------------------ > def a: print 'a' > def b: print 'b' > c = (a,b) > > >>>c[:]() # i wanna > > TypeError: 'tupple' object is not callable > > >>>c[0]() # expected > a > >>>c[:][0] # huh? > a > >>> [i() for i in c] # too long and ...huh? > > a > b > [None,None] > #------------------------------------------ > > bla-bla-bla...... you can write: >>> map(lambda x: x(), c) I think that it is good idea to use "map()" function for doing somethimg with each element of a sequence, if the order of a actions not important. it is easy to read and understandable. P.S. sorry my bad English From deets at nospam.web.de Fri Jun 1 09:04:23 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 01 Jun 2007 15:04:23 +0200 Subject: subexpressions References: Message-ID: <5cajqnF2viccfU1@mid.uni-berlin.de> > Ok, I stand corrected. > > Duplicate subexpressions are pretty easy to avoid in > Python, so though an optimization would not be > impossible here (checking for immutability of > builtins, etc., which still assumes the idea that > multiplication is more expensive than checking for > immutability even for the common builtin case), it > would not be worthwhile. > > Shortly after I posted, there was an elegant solution > to avoiding having to repeat x*x in the lambda, so the > point's kind of moot now. The elegance of that solution very much depends on the cost of the duplicate operation vs. the additional function call. And for the usecase at hand, that's exactly the point not to do it: droggisch at ganesha:/tmp$ python -m timeit '(lambda x: lambda y: y+y)(10 * 10)' 1000000 loops, best of 3: 1.04 usec per loop droggisch at ganesha:/tmp$ python -m timeit 'lambda: 10 * 10 + 10 * 10' 1000000 loops, best of 3: 0.336 usec per loop Diez From stefan.behnel-n05pAM at web.de Sat Jun 9 13:45:13 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Sat, 09 Jun 2007 19:45:13 +0200 Subject: read xml file from compressed file using gzip In-Reply-To: <1181278784.312152.99910@r19g2000prf.googlegroups.com> References: <1181278784.312152.99910@r19g2000prf.googlegroups.com> Message-ID: <466AE729.8070602@web.de> flebber wrote: > I was working at creating a simple program that would read the content > of a playlist file( in this case *.k3b") and write it out . the > compressed "*.k3b" file has two file and the one I was trying to read > was maindata.xml The k3b format is a ZIP archive. Use the zipfile library: file:///usr/share/doc/python2.5-doc/html/lib/module-zipfile.html Stefan From sjmachin at lexicon.net Mon Jun 11 19:40:26 2007 From: sjmachin at lexicon.net (John Machin) Date: Mon, 11 Jun 2007 16:40:26 -0700 Subject: SimplePrograms challenge In-Reply-To: References: <1181602284.131343.145200@i38g2000prf.googlegroups.com> Message-ID: <1181605226.367359.235860@q19g2000prn.googlegroups.com> On Jun 12, 9:16 am, Steve Howell wrote: > > One more suggestion--maybe it could exercise a little > more of the CVS module, i.e. have something in the > data that would trip up the ','.split() approach? The what approach?? Do you mean blah.split(',') ?? Perhaps like an example I posted a few days ago: "Jack ""The Ripper"" Jones","""Eltsac Ruo"", 123 Smith St",,Paris TX 12345 (name and 3 address fields) [for avoidance of doubt caused by line wrapping, repr(last_field) is 'Paris TX 12345', and the 2nd-last is ''] From gagsl-py2 at yahoo.com.ar Thu Jun 21 02:22:44 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 21 Jun 2007 03:22:44 -0300 Subject: subprocess.popen question References: <1182353267.200998.43900@w5g2000hsg.googlegroups.com> <1182380572.235876.113160@n2g2000hse.googlegroups.com> <1182389286.706352.64780@o61g2000hsh.googlegroups.com> Message-ID: En Wed, 20 Jun 2007 22:28:06 -0300, Eric_Dexter at msn.com escribi?: > On Jun 20, 7:50 pm, "Gabriel Genellina" > wrote: >> En Wed, 20 Jun 2007 20:02:52 -0300, Eric_Dex... at msn.com >> escribi?: >> > On Jun 20, 1:46 pm, "Gabriel Genellina" >> > wrote: >> >> >> cmd = ["gawk", "-f", "altertime.awk", "-v", "time_offset=4", "-v", >> >> "outfile=testdat.sco", "i1.sco"] >> >> Now, what do you want to do with the output? Printing it line by >> line? >> >> output = subprocess.Popen(cmd, >> stdout=subprocess.PIPE).communicate()[0] >> >> lines = output.splitlines() >> >> for line in lines: >> >> print line >> >> > C:\dex_tracker\pipe1.py >> > Traceback (most recent call last): >> > File "C:\dex_tracker\pipe1.py", line 14, in >> > last_line = subprocess.Popen([cmd], >> > stdout=subprocess.PIPE).communicate()[0] >> > File "C:\Python25\lib\subprocess.py", line 593, in __init__ >> > errread, errwrite) >> > File "C:\Python25\lib\subprocess.py", line 793, in _execute_child >> > startupinfo) >> > WindowsError: [Error 2] The system cannot find the file specified >> > Script terminated. >> >> > I can write it out as a batch file and then run it but that is a messy >> > hack.. >> >> If cmd is a list of arguments, like the example above, you should use >> subprocess.Popen(cmd,...) (like the example above, too). > > I had cut and pasted the example in to get that error... could it be > a problem with ms windows??? (I am at a library computer befour work > so that ended my testing) Note the call to subprocess.Popen - is the first argument [cmd] or cmd? What do you get with print repr(cmd)? Do you have gawk installed on that machine too? -- Gabriel Genellina From roy at panix.com Thu Jun 21 09:44:41 2007 From: roy at panix.com (Roy Smith) Date: Thu, 21 Jun 2007 09:44:41 -0400 Subject: strip() 2.4.4 References: <1182432181.050589.5800@n2g2000hse.googlegroups.com> Message-ID: In article <1182432181.050589.5800 at n2g2000hse.googlegroups.com>, Nick wrote: > strip() isn't working as i expect, am i doing something wrong - > > Sample data in file in.txt: > > 'AF':'AFG':'004':'AFGHANISTAN':'Afghanistan' > 'AL':'ALB':'008':'ALBANIA':'Albania' > 'DZ':'DZA':'012':'ALGERIA':'Algeria' > 'AS':'ASM':'016':'AMERICAN SAMOA':'American Samoa' > > > Code: > > f1 = open('in.txt', 'r') > > for line in f1: > print line.rsplit(':')[4].strip("'"), > > Output: > > Afghanistan' > Albania' > Algeria' > American Samoa' > > Why is there a apostrophe still at the end? No clue, I can't reproduce it, but here's some ideas to try. 1) It helps to give more information. Exactly what version of python are you using? Cut-and-paste what python prints out when you start it up interactively, i.e.: Python 2.4 (#1, Jan 17 2005, 14:59:14) [GCC 3.3.3 (NetBSD nb3 20040520)] on netbsd2 More than likely, just saying "2.4" would tell people all they need to know, but it never hurts to give more info. 2) Try to isolate what's happening. Is the trailing quote really in the string, or is print adding it? Do something like: temp = line.rsplit(':')[4].strip("'") print repr (temp[0]) and see what happens. 3) Are you sure the argument you're giving to strip() is the same character that's in the file? Is it possible the file has non-ascii characters, such as "smart quotes"? Try printing ord(temp[0]) and ord(temp("'")) and see if they give you the same value. From andre.roberge at gmail.com Tue Jun 26 15:17:54 2007 From: andre.roberge at gmail.com (=?iso-8859-1?B?QW5kcuk=?=) Date: Tue, 26 Jun 2007 19:17:54 -0000 Subject: problem mixing gettext and properties In-Reply-To: References: <1182880358.100599.139120@j4g2000prf.googlegroups.com> Message-ID: <1182885474.515335.242470@e9g2000prf.googlegroups.com> On Jun 26, 3:56 pm, Peter Otten <__pete... at web.de> wrote: > Andr? wrote: > > I've encountered a problem using gettext with properties while using a > > Python interpreter. > > > Here's a simple program that illustrate the problem. > > ============== > > # i18n_test.py: test of gettext & properties > > > import gettext > > > fr = gettext.translation('i18n_test', './translations', > > languages=['fr']) > > _ = fr.gettext # untested > > > > > help = _("Help me!") > > > class Test_i18n(object): > > def get(self): > > __help = _("HELP!") > > return __help > > help_prop = property(get, None, None, 'help') > > > test = Test_i18n() > > > print help > > print test.help_prop > > #### end of file > > > To run the above program, you need to have the strings translated and > > the proper ".po" and ".mo" files created. (for those interested, I > > can send the whole lot in a zip file) > > > If I run the program as is, the output is: > > Aidez-moi! > > AIDE!!! > > > Ok, let's try with the Python interpreter: > > > ActivePython 2.4.2 Build 248 (ActiveState Corp.) based on > > Python 2.4.2 (#67, Oct 30 2005, 16:11:18) [MSC v.1310 32 bit (Intel)] > > on win32 > > Type "help", "copyright", "credits" or "license" for more information. > >>>> import i18n_test > > Aidez-moi! > > AIDE!!! > > > # No surprise there so far. > > >>>> print i18n_test.help > > Aidez-moi! > >>>> print i18n_test.test.help_prop > > AIDE!!! > >>>> i18n_test.help > > 'Aidez-moi!' > > > # all of the above are as expected; now for the first surprise > > >>>> i18n_test.test.help_prop > > Traceback (most recent call last): > > File "", line 1, in ? > > File "i18n_test.py", line 12, in get > > __help = _("HELP!") > > TypeError: 'str' object is not callable > > > # and a second surprise where we try to repeat something that used to > > work > > >>>> print i18n_test.test.help_prop > > Traceback (most recent call last): > > File "", line 1, in ? > > File "i18n_test.py", line 12, in get > > __help = _("HELP!") > > TypeError: 'str' object is not callable > > > #============= > > > Dare I say: "Help!" I really need to use the above at the > > interpreter prompt. > > > Andr? > > The _ builtin is set to the result of the last expression evaluated by the > interpreter: > > >>> for i in range(3): > > ... i > ... > 0 > 1 > 2>>> _ > 2 > >>> import __builtin__ > >>> __builtin__._ > > 2 > > Therefore you get a name clash with _() as an alias for gettext(). Use > module-global aliases instead, e. g. > > _ = fr.gettext > > in the above code. > > Peter Thanks, that works ... but, it brings many other "complications". I have multiple modules, and I want to be able to switch languages easily. Unless I am mistaken, if I do it with module-global aliases instead, I will need to have something like lang = {} for code in ['en', 'fr', ...]: lang[code] = gettext.translation('i18n_test', './translations', languages=[code]) def switch_language(code): ... import module1 import module2 ... module1._ = lang[code].gettext module2._ = lang[code].gettext ... And I will need to make sure to keep track of all the modules that require translation... Is there an easier, less tedious way to do this? Am I missing something? Andr? From vintermann at gmail.com Mon Jun 25 02:46:10 2007 From: vintermann at gmail.com (Harald Korneliussen) Date: Sun, 24 Jun 2007 23:46:10 -0700 Subject: What was that web interaction library called again? In-Reply-To: <1182535493.241900.166040@m37g2000prh.googlegroups.com> References: <1182521949.813529.75140@w5g2000hsg.googlegroups.com> <1182535493.241900.166040@m37g2000prh.googlegroups.com> Message-ID: <1182753970.955758.249290@q75g2000hsh.googlegroups.com> On Jun 22, 8:04 pm, felciano wrote: > Maybe http://twill.idyll.org/ That was it! Thanks, I'd googled for hours. From 2007 at jmunch.dk Wed Jun 13 12:57:47 2007 From: 2007 at jmunch.dk (Anders J. Munch) Date: Wed, 13 Jun 2007 18:57:47 +0200 Subject: Python's "only one way to do it" philosophy isn't good? In-Reply-To: References: <1181368143.874341.273140@r19g2000prf.googlegroups.com> <7xy7irxjom.fsf@ruckus.brouhaha.com> <466f0c2c$0$4157$ba624c82@nntp02.dk.telia.net> Message-ID: <46702229$0$4158$ba624c82@nntp02.dk.telia.net> Neil Cerutti wrote: > On 2007-06-12, Anders J. Munch <2007 at jmunch.dk> wrote: >> Converting tail-recursion to iteration is trivial, and >> perfectly reasonable for a human to do by hand. > > For simple recursive tail calls, yeah, it can be. Translating a > tail-recursive Factorial function into a while loop is easy. But > tail-call optimization technically works for any tail-call, > including mutual recursion, and non-recursive tail-calls. You > can't reasonably hand-optimize away the stack frame for all > tail-calls. I may have misunderstood, I thought we were talking about tail recursion only. The general tail-call optimisation, where all leaf calls become jumps and the called function usurps the current stack frame, is a different ballgame entirely. There's no pure-Python transformation for that, but that still doesn't mean you need CPS. General tail-call optimisation is of course completely out-of-bounds for Python, because it ruins tracebacks. Unlike tail recursion, which could use recursion counters. - Anders From mail at timgolden.me.uk Fri Jun 8 16:24:35 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Fri, 08 Jun 2007 21:24:35 +0100 Subject: Binary / SOAPpy In-Reply-To: <003901c7a9d3$1a2fc3c0$4e8f4b40$@rawlins@thinkbluemedia.co.uk> References: <003901c7a9d3$1a2fc3c0$4e8f4b40$@rawlins@thinkbluemedia.co.uk> Message-ID: <4669BB03.5080104@timgolden.me.uk> Robert Rawlins - Think Blue wrote: > I have a WebService call which returns an array, the first element in > that array is the binary for a zip file, however I?m having trouble > writing that binary string into an actual file when it arrives, I?ve > tried the following method. > > Result = call to the webservice that returns the array. > file = open("Zips/1.zip", "wb") > file.write(result[0]) > file.close() > > But this throws the error message: > > file.write(result[0]) > > TypeError: argument 1 must be string or read-only buffer, not instance Robert, do the obvious here, and insert: print type (result[0]) print repr (result[0]) after you receive the result and before you open the file. Is result[0] really what you expected? By the way, you can't simply throw a zipped string into a .zip file. The .zip file needs headers and so forth. Maybe that's not quite what you're trying to do, but it looks like it. TJG From steve at laniels.org Thu Jun 21 09:30:06 2007 From: steve at laniels.org (Stephen R Laniel) Date: Thu, 21 Jun 2007 09:30:06 -0400 Subject: strip() 2.4.4 In-Reply-To: <1182432181.050589.5800@n2g2000hse.googlegroups.com> References: <1182432181.050589.5800@n2g2000hse.googlegroups.com> Message-ID: <20070621133006.GQ6145@slaniel-laptop.itasoftware.com> On Thu, Jun 21, 2007 at 06:23:01AM -0700, Nick wrote: > Why is there a apostrophe still at the end? Is it possible that you actually have whitespace at the end of the line? So then strip() is looking for an apostrophe at the end of the line, not finding it, and therefore not stripping it? -- Stephen R. Laniel steve at laniels.org Cell: +(617) 308-5571 http://laniels.org/ PGP key: http://laniels.org/slaniel.key From claird at lairds.us Mon Jun 4 11:18:44 2007 From: claird at lairds.us (Cameron Laird) Date: Mon, 4 Jun 2007 15:18:44 +0000 Subject: Python, Dutch, English, Chinese, Japanese, etc. References: <1180965224.136341.271180@z28g2000prd.googlegroups.com> Message-ID: In article <1180965224.136341.271180 at z28g2000prd.googlegroups.com>, ahlongxp wrote: . . . >I'm a Chinese. >Language/English is really a big problem for Chinese programmers. >If python can be written in Chinese, it may become the most popular >program language in China(though popular alreay). >Considering the potential large amount of users in China, the effort >of internationalization for Chinese will totally worth. . . . Tcl can be (more-or-less) written in Chinese now. How popular is it among Chinese-speaking developers? From pats at acm.org Mon Jun 11 20:57:35 2007 From: pats at acm.org (Patricia Shanahan) Date: Mon, 11 Jun 2007 17:57:35 -0700 Subject: The Concepts and Confusions of Prefix, Infix, Postfix and Fully Functional Notations In-Reply-To: <1181545345.788665.191690@q66g2000hsg.googlegroups.com> References: <1179936917.652372.24780@q69g2000hsb.googlegroups.com> <1180508453.226022.44230@q19g2000prn.googlegroups.com> <1181335574.107472.229370@x35g2000prf.googlegroups.com> <1181358616.792797.97720@k79g2000hse.googlegroups.com> <1181414625.121073.203940@g4g2000hsf.googlegroups.com> <0uHai.176367$nh4.13819@newsfe20.lga> <1181448558.120521.63250@g4g2000hsf.googlegroups.com> <0G_ai.1970$xg4.809@trnddc08> <1181525392.369255.138460@h2g2000hsg.googlegroups.com> <1181545345.788665.191690@q66g2000hsg.googlegroups.com> Message-ID: Twisted wrote: > On Jun 11, 2:42 am, Joachim Durchholz wrote: >> It is possible to write maintainable Perl. > > Interesting (spoken in the tone of someone hearing about a purported > sighting of Bigfoot, or maybe a UFO). > > Still, extraordinary claims require extraordinary evidence. (And no, a > fuzzy picture of something that might be a giant serpent-like thing in > the loch, or equivalent, does not constitute "extraordinary > evidence".) > How about "I caught a very small one, but it belonged to a former employer, so I couldn't keep it for display."? I wrote a Perl script to process logic analyzer traces for some hardware engineers. While I was out of the office, they found they needed to process a new record type. They didn't want to delay their work until I got back, and one of the EEs knew Perl, so he modified my script. The change was done correctly. It not only worked. Except for a couple of comments calling my attention to the changes, it looked as though the new record type had always been there. Patricia From kyosohma at gmail.com Mon Jun 11 10:26:54 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Mon, 11 Jun 2007 07:26:54 -0700 Subject: wx.grid 2.6.1.0 events In-Reply-To: <1181570690.369131.28910@g37g2000prf.googlegroups.com> References: <1181570690.369131.28910@g37g2000prf.googlegroups.com> Message-ID: <1181572014.381851.134180@k79g2000hse.googlegroups.com> On Jun 11, 9:04 am, DarkBlue wrote: > Hello > > pythoncard > wx 2.6.1 > python 2.4.x > kinterbasdb > firebird > > I have a wx.grid filled with data from a database > one of the fields is a blob field with text data, which > I want to display in some adjacent text control when I scroll > through the grid. > > The question is which wx.EVT_XXX do I need > to use and how to 'connect ' the wx.grid to my TextArea > control ,so that the correct data gets displayed after > any row change? > > Thanks for any hints. > > Db Upon skimming the grid controls event types in the wxPython in Action book, it looks like you could catch the wx.grid.EVT_GRID_SELECT_CELL event. Then use the GetCellValue method to grab the selected cell's contents and then write that to your TextCtrl. If that doesn't work, please post the issue to the wxPython user's group here: http://wxpython.org/maillist.php Mike From gagsl-py2 at yahoo.com.ar Tue Jun 12 07:39:56 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 12 Jun 2007 08:39:56 -0300 Subject: for ... else ? References: <1181622331.955264.31610@i38g2000prf.googlegroups.com> <1181640889.439145.60020@g37g2000prf.googlegroups.com> Message-ID: En Tue, 12 Jun 2007 06:34:49 -0300, exhuma.twn escribi?: > On Jun 12, 6:57 am, "Gabriel Genellina" > wrote: >> for number in range(10,100): >> for divisor in range(2,number): >> if number % divisor == 0: >> break >> else: >> print number, >> > > Oh my. Would it not be an idea to rename this "else" into a "finally"? > As Gabriel points out, the else-block gets executed after the for loop > exits *normally*. In that case, is the "else" not semantically > misleading? I would surely misunderstand it if I saw it the first time. No - finally already has a meaning, "do this always, even if an exception occurred before". The "else" clause is fired when a condition is not met: if condition: do something when condition is true else: do something when condition is not true while condition: do something when condition is true else: do something when condition is not met for x in iterable: do something with x else: do something when there are no more x You can think the above as: while there are still values in iterable: do something with the next value else: do something when there are no more items -- Gabriel Genellina From josh at laculine.com Sat Jun 2 04:58:38 2007 From: josh at laculine.com (Josh West) Date: Sat, 02 Jun 2007 09:58:38 +0100 Subject: Create a new class on the fly In-Reply-To: <1hz1s32.1e0j3ee1fmijbnN%aleax@mac.com> References: <1180568447.449581.250500@g37g2000prf.googlegroups.com> <1hyy30j.f4k5tc17kc7ohN%aleax@mac.com> <1180732492.717760.288190@n15g2000prd.googlegroups.com> <1hz1s32.1e0j3ee1fmijbnN%aleax@mac.com> Message-ID: <4661313E.705@laculine.com> Alex Martelli wrote: > > Thanks for snipping all the actual helpful stuff I posted, it makes SO > much easier for me to be snide! > > You can find a few examples of me demonstrating the subject of your > interest by searching for my name e.g. on video.google.com; searching > for my name on Amazon will show some books using similar techniques, and > searching for my name on groups.google.com will find about 50,000 posts > many of which exhibit essentially the same approach. Unfortunately, I > can't currently offer such courses commercially while staying employed > as Uber Tech Lead for Google, Inc, but if the monies on offer make it > worth my while for me to drop million bucks worth of stock options, plus > a vigorish for my other comp package _and_ the incredible amount of > happiness I get every day from my job (where I get to interact with > truly brlliant people, who, if and when they "leave an erroneous snippet > in", are GRATEFUL to me for pointing it out, rather than RESENTFUL and > DEFENSIVE), I'll surely consider that most seriously (as long as the > monies in question are in escrow for my personal reassurance). > > Until such conditions should obtain, I'll just have to keep freely > helping the people who are WORTH helping, and poking sarcastic funs at > those who prove themselves ot be a waste of oxygen instead. > > > May you have the life you deserve, I'm new to all this, but I didn't get the impression that sickeningly smug self-satisfaction was a "pythonic" characteristic. Let's hope for a Waco (cults, siege, bloodbath) style conclusion to the Google story. That would be truly (Monty) Pythonic. > Alex > From enleverlesX.XmcX at XmclaveauX.com Thu Jun 21 03:39:16 2007 From: enleverlesX.XmcX at XmclaveauX.com (Méta-MCI) Date: Thu, 21 Jun 2007 09:39:16 +0200 Subject: Invisible processes in Win2K References: Message-ID: <467a2b2b$0$25947$ba4acef3@news.orange.fr> Hi! When you lock (the cpu), interactive mode is off. You can try to use services, who run independently of sessions. But... From gagsl-py2 at yahoo.com.ar Thu Jun 14 13:20:58 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 14 Jun 2007 14:20:58 -0300 Subject: Is there any way to catch expections when call python method in C++ References: <1181727704.631721.269650@g37g2000prf.googlegroups.com> Message-ID: En Wed, 13 Jun 2007 12:03:00 -0300, Robert Bauck Hamar escribi?: > Allen wrote: > >> I use try catch, but cannot catch the execeptions of execution python >> method. > > No. CPython is written in C, not C++, and C has no concept of exceptions. > Exceptions in Python is usually indicated by return value in the > interpreter, and has no mapping to the C++ exception model. You should > never let C++ exceptions propagate into the python functions either. > PyImport_ImportModule will return NULL if an exception occured, and so > will > also PyObject_GetAttrString and PyEval_CallObject do. For an example on how to do this, see "Extending and Embedding the Python Interpreter" specially section 1.2 -- Gabriel Genellina From ppaterson at gmail.com Wed Jun 6 12:19:28 2007 From: ppaterson at gmail.com (Paul Paterson) Date: Wed, 06 Jun 2007 09:19:28 -0700 Subject: Can os.remove followed by os.path.isfile disagree? In-Reply-To: References: <1181140547.279974.83550@q66g2000hsg.googlegroups.com> Message-ID: <1181146768.062366.25230@o5g2000hsb.googlegroups.com> > Don't suppose you've got some kind of flashy software > running which intercepts OS file-manipulation calls for > Virus or Archiving purposes? > > TJG As I mentioned in another reply, this server is virtual and so is the drive. I'm wondering if this might also be significant. Paul From scott.daniels at acm.org Sat Jun 16 14:21:31 2007 From: scott.daniels at acm.org (Scott David Daniels) Date: Sat, 16 Jun 2007 11:21:31 -0700 Subject: Priority Queue with Mutable Elements In-Reply-To: <1182005565.861790.102360@q75g2000hsh.googlegroups.com> References: <1181939158.688317.207790@o61g2000hsh.googlegroups.com> <1182005565.861790.102360@q75g2000hsh.googlegroups.com> Message-ID: <1378ag43e8uu599@corp.supernews.com> Chris Lasher wrote: > On Jun 15, 5:52 pm, Josiah Carlson > wrote: >> See this implementation of a "pair heap": >> http://mail.python.org/pipermail/python-dev/2006-November/069845.html >> ...which offers the ability to update the 'priority' of an entry in the >> heap. It requires that the 'value' in (priority, value) pairs be unique >> (to the heap) and hashable. >> >> - Josiah > > Hmm. I won't be able to use that heap, as I can guarantee that the > value will be identical for two nodes when they have edges to each > other and no other nodes. Any suggestions on structures that can > accompany identical priority values? > > Thanks, > Chris > Make the priority value for element: (intended_value, id(element)) always a total order that obeys the partial order implied by intended_value. -- --Scott David Daniels scott.daniels at acm.org From josiah.carlson at sbcglobal.net Mon Jun 4 16:15:44 2007 From: josiah.carlson at sbcglobal.net (Josiah Carlson) Date: Mon, 04 Jun 2007 20:15:44 GMT Subject: Python, Dutch, English, Chinese, Japanese, etc. In-Reply-To: References: Message-ID: Steve Howell wrote: > I don't predict a huge upswing in Slavic-writing > Python programmers after PEP 3131, even among > children. Are you predicting a sharp upswing in Chinese-writing (or any language) Python programmers after PEP 3131 among children? If so, why certain groups of children and not others? - Josiah From kay.schluehr at gmx.net Fri Jun 15 18:06:38 2007 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Fri, 15 Jun 2007 15:06:38 -0700 Subject: Python's "only one way to do it" philosophy isn't good? In-Reply-To: References: <1181368143.874341.273140@r19g2000prf.googlegroups.com> <1181385768_30305@sp12lax.superfeed.net> Message-ID: <1181945198.152891.228520@q75g2000hsh.googlegroups.com> On 15 Jun., 22:58, Douglas Alan wrote: > For instance, I believe that Python is now too big, and that much of > what is in the language itself should be replaced with more general > Scheme-like features. > Then a good macro mechanism should be > implemented so that all the conveniences features of the language can > be implemented via macro definitions in the standard library. And why sould anyone reimplement the whole standard library using macro reductions? Because this is the "one obvious way to do it" for people who are addicted to Scheme? From john at datavoiceint.com Wed Jun 13 15:20:59 2007 From: john at datavoiceint.com (HMS Surprise) Date: Wed, 13 Jun 2007 12:20:59 -0700 Subject: Goto Message-ID: <1181762459.749538.151730@z28g2000prd.googlegroups.com> How does one effect a goto in python? I only want to use it for debug. I dasn't slap an "if" clause around the portion to dummy out, the indentation police will nab me. Thanx, jh From doug at alum.mit.edu Sat Jun 16 00:13:27 2007 From: doug at alum.mit.edu (Douglas Alan) Date: Sat, 16 Jun 2007 00:13:27 -0400 Subject: Python's "only one way to do it" philosophy isn't good? References: <1181368143.874341.273140@r19g2000prf.googlegroups.com> Message-ID: "Terry Reedy" writes: > > You are ignoring the fact that > This prefactory clause is false and as such it turns what was a true > statement into one that is not. Better to leave off such ad hominisms and > stick with the bare true statement. You went on about how Gerry Sussman's opinion is a crock and how he should look in the mirror, and then you get bent out of shape over the phrase, "you are ignoring"??? For the record, "you are ignoring" is not an ad hominem; "anyone who doesn't know how to spell 'ad hominem' has the intelligence of a mealworm" is an ad hominem. > > Scheme has a powerful syntax extension mechanism > I did not and do not see this as relevant to the main points of my > summary above. Python has powerful extension mechanisms too, but > comparing the two languages on this basis is a whole other topic. How do you know that Prof. Sussman doesn't consider the macro issue to be essential? Certainly other Lisp aficionados do, as does, I believe Guy Steele, the other inventor of Scheme. It appears to me that you are missing the point that having a minimalist disposition towards programming language design does not preclude believing that such languages should have features that are missing from Python. |>oug From david at boddie.org.uk Sun Jun 17 10:32:21 2007 From: david at boddie.org.uk (David Boddie) Date: Sun, 17 Jun 2007 16:32:21 +0200 Subject: Questions about mathematical and statistical functionality in Python Message-ID: <200706171632.22510.david@boddie.org.uk> On Fri Jun 15 03:08:08 CEST 2007, Josh Gilbert wrote: > In a similar vein, I wish there was a reasonable Free Software equivalent to > Spotfire. The closest I've found (and they're nowhere near as good) are > Orange (http://www.ailab.si/orange) and WEKA > (http://www.cs.waikato.ac.nz/ml/weka/). Orange is written in Python, but its > tied to QT 2.x as the 3.x series was not available on Windows under the GPL. It should be possible to get Orange working with Qt 4, which is available under the GPL on Windows, but it could take some work to update some of the more specialized components to use the latest classes. On a positive note, there should be enough information available to help with the "porting" process, and the updated components would be able to take advantage of the improvements made to Qt and PyQt since Qt 2 was released! David From aahz at pythoncraft.com Sat Jun 16 12:04:59 2007 From: aahz at pythoncraft.com (Aahz) Date: 16 Jun 2007 09:04:59 -0700 Subject: Want to learn Python References: <1181907696.878873.214760@i13g2000prf.googlegroups.com> <1181950960.793735.304570@c77g2000hse.googlegroups.com> <1hzrppt.1i3pamvoxog4rN%aleax@mac.com> Message-ID: In article <1hzrppt.1i3pamvoxog4rN%aleax at mac.com>, Alex Martelli wrote: >7stud wrote: >> >> The reference book "Python in a Nutshell" is excellent, however its >> index is so bad I hesitate to recommend it. A reference book should >> have a thorough index--you shouldn't have to hunt through the chapters >> trying to find the particular topic you are interested in. > >Try -- it will easily >generate for you queries on books.google.com such as, e.g.: > generator inauthor:"alex martelli" >to find 3 mentions of "generator" in the Nutshell and Cookbook. Not >quite a replacement for a good index, of course (you're welcome to write >O'Reilly spewing hate on how much you loathe that index - maybe that >will help convince them to put more time and effort into indexing on >their future projects, or offer some way for book authors to add >indexing indications as they write their books), but it still seems >potentially helpful. We didn't wait for Wiley to offer, we simply insisted on providing a list of index terms. That's why _Python for Dummies_ includes "genexp" in addition to "generator", and also why we have separate entries for "{} dict literal", "braces ({}) dict literal", and "curly braces ({}) dict literal". ;-) -- 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 Sat Jun 23 02:43:32 2007 From: nagle at animats.com (John Nagle) Date: Fri, 22 Jun 2007 23:43:32 -0700 Subject: urllib interpretation of URL with ".." Message-ID: Here's a URL, found in a link, which gives us trouble when we try to follow the link: http://sportsbra.co.uk/../acatalog/shop.html Browsers immediately turn this into http://sportsbra.co.uk/acatalog/shop.html and go from there, but urllib tries to open it explicitly, which results in an HTTP error 400. Is "urllib" wrong? John Nagle From owntheweb at gmail.com Wed Jun 20 11:32:15 2007 From: owntheweb at gmail.com (Ultrus) Date: Wed, 20 Jun 2007 15:32:15 -0000 Subject: Edit Audio Using Python? Message-ID: <1182353535.158899.128650@n2g2000hse.googlegroups.com> Hello Python Gurus, I picked up a book the other day on Python programming. Python rocks! I'm learning Python as I want to call upon it to handle some intensive tasks from PHP/web server. The top goal right now is automating audio editing using Python. Is it possible? I was able to do this directly through php, but it was reaaaallllyyyyy slowwwwwwww. PHP is not designed for that sort of thing. So far I googled the Snack Sound Toolkit at http://www.speech.kth.se/snack/ . It seems to have potential, but is very limited, and has not been a very active project lately from what I can tell. I'm not sure I can use it without learning C or C++ to make it do what I want (fading ends, appending - there but not working?, mixing). It may work once I learn more about it. Do you know of any other modules, scripts, or whatnot that allows for fast .wav audio editing from a Python script (not through a visual interface)? Would it be better to start from scratch? Thank you much for the advise :) From gagsl-py2 at yahoo.com.ar Mon Jun 18 22:43:26 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 18 Jun 2007 23:43:26 -0300 Subject: getting the size of an object References: <1182182932.947333.251020@o61g2000hsh.googlegroups.com> Message-ID: En Mon, 18 Jun 2007 16:48:36 -0300, filox escribi?: > "Brett Hoerner" wrote in message >> Although I have the feeling you mean "how many bytes does this object >> take in memory" - and I believe the short answer is no. > > is there a long answer? what i want is to find out the number of bytes > the > object takes up in memory (during runtime). since python has a lot of > introspection mechanisms i thought that should be no problem... Consider this: x = "x" * 1000000 x is a string taking roughly 1MB of memory. y = x y is a string taking roughly 1MB of memory *but* it is shared, in fact it is the same object. So you can't add them to get the total memory usage. z = (x,y) z takes just a few bytes: a pointer to x, to y, to its own type, its reference count. The total memory for the three objects is a few bytes more than 1MB. For arbitrary objects, a rough estimate may be its pickle size: len(dumps(x)) == 1000008 len(dumps(y)) == 1000008 len(dumps(z)) == 1000016 -- Gabriel Genellina From sjdevnull at yahoo.com Thu Jun 14 14:19:41 2007 From: sjdevnull at yahoo.com (sjdevnull at yahoo.com) Date: Thu, 14 Jun 2007 11:19:41 -0700 Subject: Method much slower than function? In-Reply-To: References: <1181781612.939800.238890@q19g2000prn.googlegroups.com> <1181795969.141307.94140@i13g2000prf.googlegroups.com> Message-ID: <1181845181.180244.38850@n15g2000prd.googlegroups.com> On Jun 14, 1:12 am, "Gabriel Genellina" wrote: > En Thu, 14 Jun 2007 01:39:29 -0300, sjdevn... at yahoo.com > escribi?: > > > > > Gabriel Genellina wrote: > >> In addition, += is rather inefficient for strings; the usual idiom is > >> using ''.join(items) > > > Ehh. Python 2.5 (and probably some earlier versions) optimize += on > > strings pretty well. > > > a="" > > for i in xrange(100000): > > a+="a" > > > and: > > > a=[] > > for i in xrange(100000): > > a.append("a") > > a="".join(a) > > > take virtually the same amount of time on my machine (2.5), and the > > non-join version is clearer, IMO. I'd still use join in case I wind > > up running under an older Python, but it's probably not a big issue > > here. > > Yes, for concatenating a lot of a's, sure... Try again using strings > around the size of your expected lines - and make sure they are all > different too. > > py> import timeit > py> > py> def f1(): > ... a="" > ... for i in xrange(100000): > ... a+=str(i)*20 > ... > py> def f2(): > ... a=[] > ... for i in xrange(100000): > ... a.append(str(i)*20) > ... a="".join(a) > ... > py> print timeit.Timer("f2()", "from __main__ import f2").repeat(number=1) > [0.42673663831576358, 0.42807591467630662, 0.44401481193838876] > py> print timeit.Timer("f1()", "from __main__ import f1").repeat(number=1) > > ...after a few minutes I aborted the process... Are you using an old version of python? I get a fairly small difference between the 2: Python 2.5 (r25:51908, Jan 23 2007, 18:42:39) [GCC 3.3.3 20040412 (Red Hat Linux 3.3.3-7)] on ELIDED Type "help", "copyright", "credits" or "license" for more information. >>> import timeit >>> a="" >>> def f1(): ... a="" ... for i in xrange(100000): ... a+=str(i)*20 ... >>> def f2(): ... a=[] ... for i in xrange(100000): ... a.append(str(i)*20) ... a="".join(a) ... >>> print timeit.Timer("f2()", "from __main__ import f2").repeat(number=1) [0.91355299949645996, 0.86561012268066406, 0.84371185302734375] >>> print timeit.Timer("f1()", "from __main__ import f1").repeat(number=1) [0.94637894630432129, 0.89946198463439941, 1.170320987701416] From showell30 at yahoo.com Tue Jun 12 19:07:47 2007 From: showell30 at yahoo.com (Steve Howell) Date: Tue, 12 Jun 2007 16:07:47 -0700 (PDT) Subject: SimplePrograms challenge In-Reply-To: <165631.5633.qm@web33502.mail.mud.yahoo.com> Message-ID: <581629.54778.qm@web33515.mail.mud.yahoo.com> --- I wrote: > [...] was the final straw in converting > me from Python to Perl. Er, Perl to Python. In looking backwards, I started writing backwards. And no, I'm not ever going back to Perl... ____________________________________________________________________________________ Boardwalk for $500? In 2007? Ha! Play Monopoly Here and Now (it's updated for today's economy) at Yahoo! Games. http://get.games.yahoo.com/proddesc?gamekey=monopolyherenow From rdm at rcblue.com Tue Jun 12 01:36:30 2007 From: rdm at rcblue.com (Dick Moores) Date: Mon, 11 Jun 2007 22:36:30 -0700 Subject: Problem with following python code In-Reply-To: <20070612045216.GA548@linux.ucla.edu> References: <1181622331.955264.31610@i38g2000prf.googlegroups.com> <20070612045216.GA548@linux.ucla.edu> Message-ID: <20070612053741.893EC1E4002@bag.python.org> At 09:52 PM 6/11/2007, Dan Hipschman wrote: >On Tue, Jun 12, 2007 at 04:25:31AM -0000, why? wrote: > > I've been having problem with the following code. It's supposed to > > print the prime numbers between 10 and 100. But i'm not getting any > > output, i.e. i guess the outer 'for' loop is being traversed only > > once. I would be greatful if you could help me out. Thanx! > > >>> f=1 > > >>> for i in range(10,100): > > ... for j in range(2,i): > > ... if i%j==0: > > ... f=0 > > ... break > > ... else: continue > > ... if f==1: > > ... print i, > > ... > >Move "f=1" inside the outer loop: > >for i in range(10,100): > f=1 > for j in range(2,i): > if i%j==0: > f=0 > break > else: continue > if f==1: > print i, > >It gets set to 0 in the first iteration and never has another chance to >be set to 1 after that. And of course the inner loop does too much work. Try: for i in range(10,100): f=1 max = int(i**.5 + 1) for j in range(2,max): if i%j==0: f=0 break else: continue if f==1: print i, Dick Moores From deets at nospam.web.de Mon Jun 18 06:07:15 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 18 Jun 2007 12:07:15 +0200 Subject: using Mac OS X CoreGraphics via ctypes References: <1181876264.097017.283110@n15g2000prd.googlegroups.com> <5deo7iF34h5s2U1@mid.uni-berlin.de> <1181909161.373930.134660@k79g2000hse.googlegroups.com> Message-ID: <5dn3qjF35ha5iU1@mid.uni-berlin.de> Daniel wrote: >> > # the next line causes a segfault - what's the right way to do this? >> > #GCS_RGB = cglib.kCGColorSpaceGenericRGB() >> >> Usually, things in the OSX lib that start with k* are a constant - not a >> function. As is this. >> >> Diez > > That's what I thought too. But when I try passing it directly as if it > were a constant: > > GCS_RGB = cglib.kCGColorSpaceGenericRGB > cs = cglib.CGColorSpaceCreateWithName(GCS_RGB) > > I get a segfault too. ctypes said kCGColorSpaceGenericRGB was a > function pointer, so I thought maybe I needed to call it to get the > value (not very good reasoning, I know). I'm not sure what that constant exported is - but how about looking the constant up in the ref docs and pass it as value? Usually these thingies are some 4-byte-string, or a normal zero-terminated one. Diez From hat at se-162.se.wtb.tue.nl Fri Jun 29 07:17:07 2007 From: hat at se-162.se.wtb.tue.nl (A.T.Hofkamp) Date: Fri, 29 Jun 2007 13:17:07 +0200 Subject: equality & comparison by default (was Re: Too many 'self' in python.That's a big flaw in this language.) References: <1182942154.185461.89620@e9g2000prf.googlegroups.com> <1i0cy8z.z94q5d1dxgexxN%aleax@mac.com> Message-ID: On 2007-06-29, Steve Holden wrote: > Just the same there are sound reasons for it, so I'd prefer to see you > using "counterintuitive" or "difficult to fathom" rather than "broken" > and "wrong". You are quite correct, in the heat of typing an answer, my wording was too strong, I am sorry. Albert From alexteo21 at yahoo.com Thu Jun 7 10:33:15 2007 From: alexteo21 at yahoo.com (alexteo21) Date: Thu, 07 Jun 2007 07:33:15 -0700 Subject: open function fail after running a day Message-ID: <1181226795.455934.177550@n15g2000prd.googlegroups.com> I have created a script using python that will batch process data files every hour The script is running on Solaris. Python version 2.3.3 t=open(filename,'rb') data=t.read() #processing data... t.close() The script is working fine on the day of execution. It is able to process the data files very hour. However, the processing fail one day later i.e. the date increment by 1. Traceback (most recent call last): File "./alexCopy.py", line 459, in processRequestModule sanityTestSteps(reqId,model) File "./alexCopy.py", line 699, in sanityTestSteps t = open(filename, 'rb') IOError: [Errno 24] Too many open files: I have explicitly closed the file. Is there something else I need to do? Appreciate your comments From flebber.crue at gmail.com Fri Jun 8 23:15:47 2007 From: flebber.crue at gmail.com (flebber) Date: Sat, 09 Jun 2007 03:15:47 -0000 Subject: Gzip - gunzip using zlib Message-ID: <1181358947.291489.85950@q19g2000prn.googlegroups.com> Hi Can anyone show me a working example of how to use gzip to decompress a file. I have read the docs at python.org and had many goes at it but just can't get it to work. Cheers flebber From martin at v.loewis.de Sun Jun 3 04:00:11 2007 From: martin at v.loewis.de (=?ISO-8859-15?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 03 Jun 2007 10:00:11 +0200 Subject: Python 2.5.1 broken os.stat module In-Reply-To: <-aOdnbFdroD_gP_bnZ2dnUVZ_uKknZ2d@comcast.com> References: <466140A6.1090100@v.loewis.de> <-aOdnbFdroD_gP_bnZ2dnUVZ_uKknZ2d@comcast.com> Message-ID: <4662750b$0$29898$9b622d9e@news.freenet.de> > The short explaination of this issue is that the timestamp shown when > you do a dir on a file that is on an NTFS volume changes by an hour > when DST starts and also when DST ends, even though the file has NOT > been modified!!! Note that this only happens if you have the setting > turned on to automatically adjust for DST (this is the default in > Windows). You are misinterpreting what you are seeing. Windows is not claiming that the modification time changes when DST starts. Instead, it is claiming that the *same* time now has a *different* textual representation, because the computer now has moved to a different time zone. When you explicitly change the time zone of your computer, you will notice that all file time stamps immediately change also. > Even though Python 2.5.1 is correct this presents a NEW problem > because it differs from what XP SP 2 (wrongly) reports. I am sure > this will cause a lot of confusion for people as it already appears > that others have stumbled on this difference. However, please understand that the problem is *not* caused by the results returned from os.stat. Instead, the difference comes from your choice of calling localtime() to break down the timestamp to day, hour, and minute. If you write a different function windows_localtime, that behaves the same way that the Windows rendering behaves, you will get the same results. > To the end user it appears the file was modifed when in fact it was > not. That's because the user is misinterpreting the data that Windows reports. Windows isn't saying the file changed, Windows says that the timezone changed. To understand this, you have to truly grasp the notion of absolute time. June 2, 2007, 9:40 is *not* a point in time. Instead, you have to provide a timezone also to make it point in time. So Windows is incorrect not giving the time zone; otherwise, it is correct. > This file was originally created 01/02/2007 12:00 AM GMT > which is the same locally as 01/01/2007 07:00 PM EST > but now everything EXCEPT Python 2.51 > is reporting that the file changed on 01/01/2007 08:00 PM EST Not true. Everything else is reporting that the time stamp is 01/01/2007 08:00 PM EDT (where EDT is the Eastern Daylight Time). > Having this difference between Python and Windows makes it difficult > to write code that depends on those values being in sync. No. Just write a windows_localtime function, and be done. Regards, Martin From bj_666 at gmx.net Fri Jun 1 07:18:27 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Fri, 01 Jun 2007 13:18:27 +0200 Subject: c[:]() References: <1180504190.055427.173610@h2g2000hsg.googlegroups.com> <1180554872.3356.30.camel@dot.uniqsys.com> <465DF3DE.40404@cc.umanitoba.ca> <1180566831.239580.199300@m36g2000hse.googlegroups.com> <005401c7a31a$136f7fe0$240110ac@Muse> <135tobve86qj808@corp.supernews.com> <135tru124pie2b3@corp.supernews.com> <135tv1bjqgbmsc9@corp.supernews.com> <9qudnbFRU9QHJsLbnZ2dnUVZ_rKvnZ2d@speakeasy.net> Message-ID: In , Warren Stringer wrote: >> Warren Stringer wrote: >> >> > As mentioned a while back, I'm now predisposed towards using `do(c)()` >> > because square brackets are hard with cell phones. The one mitigating >> factor >> > for more general use, outside of cell phones, is speed. >> >> The speed at which you can type code is almost _never_ a valid reason to >> make something brief. Code gains readability from verbosity. (That can >> be taken too far, of course, but that certainly doesn't apply here.) > > There is code that you type which persists and code that you type from a > command line. Two completely different idioms. A credo inside the cell phone > game industry is that you lose half your audience with each menu keystroke. > That's how precious keystrokes are. > > What may be confusing is speaking about both idioms at once. > > > >> In short, your repeated use of `c[:]()` indicates a fundamental >> misunderstanding about Pythonic style _and_ substance. > > Please define Pythonic. Is this like a certain US senator who defined porn > as "I know it when I see it." Yes you are right, "pythonic" is not a hard fact. But one indicator is consistency and no surprising behavior if possible. And that your insisting on ``c[:]()`` instead of just ``c()`` seems to indicate you want a change that is quite surprising. It would mean that a slice of a list returns an other type with the __call__ method implemented. > 28 years ago, I wrote a hierarchical DBMS that used lexical indentation. 15 > years ago I wrote a multimedia script language that used lexical indentation > and automatic garbage collection - it was deployed on millons of clients. 2 > years ago I hand coded every line of the Python 2.2 BNF into another style > of language description. Up until last month, I had tokenized a subset of > said definition in C++, using templates to manage cardinality. Recently, I > decided to forgo the C++ parser and am now rewriting it in Python. This is a > risk. So, what hoop does one jump though to earn that oh so coveted > "pythonic" merit badge? Grok The Zen of Python (``import this`` at the interpreter prompt)? Write "pythonic" code? I don't see how writing other languages and Python parsers and translators into other representations tells you much about the spirit and idiomatic *usage* of a language. Your proposal is not about syntax, it's about semantics. ``obj[:]()`` is basically syntactic sugar for: ``obj.__getitem__(slice(None)).__call__()`` and you want a change in the implementation of `list.__getitem__()` and `tuple.__getitem__()`. Ciao, Marc 'BlackJack' Rintsch From agillesp at gmail.com Fri Jun 22 06:08:45 2007 From: agillesp at gmail.com (alg) Date: Fri, 22 Jun 2007 10:08:45 -0000 Subject: Retrieving a stacktrace from an exception object / forwarding an exception In-Reply-To: <1182495252.513035.96890@m36g2000hse.googlegroups.com> References: <1182495252.513035.96890@m36g2000hse.googlegroups.com> Message-ID: <1182506925.757320.137170@d30g2000prg.googlegroups.com> Use the traceback module: def log_exception(): """This function will log the current exception's traceback to logfile """ import traceback f = open("logfile", 'a') traceback.print_exc(32, f) f.close() def my_func(): raise Exception def wrapper(): try: my_func() except Exception, e: log_exception() raise e On Jun 21, 11:54 pm, Samuel wrote: > Hi, > > I am trying to wrap a function that throws an exeption in such a way > that the stacktrace is logged into a file and the exception is > forwarded after that. For example: > > ------------------- > def my_func(): > raise Exception("hello") > > def wrapper(): > try: > my_func() > except Exception, e: > f = open("logfile", 'a') > f.write(e.stacktrace()) > raise e > > wrapper() # should throw the exception with a stacktrace showing > my_func() > ------------------- > > Any idea if and how this can be done? > > -Samuel From eugene.vandenbulke at gmail.com Tue Jun 19 04:14:58 2007 From: eugene.vandenbulke at gmail.com (EuGeNe Van den Bulke) Date: Tue, 19 Jun 2007 10:14:58 +0200 Subject: poplib.retr doens't flag message as read Message-ID: Hi there, I am trying to use the poplib library to get emails using the retr method. The small program bellow works but the message aren't flagged as read which puzzles me. I believe the pop server is qmail 1.0.6 / vpopmail 5.2.1 and I am running the following script on Windows using Pyhton 2.5. import poplib import email pop = poplib.POP3('mail.server.com') pop.user('email at server.com') pop.pass_('password') status, msg_list, octets = pop.list() for msg_number in [msg.split(' ')[0] for msg in msg_list]: status, lines, octets = pop.retr(msg_number) msg = email.message_from_string('\n'.join(lines)) if not msg.is_multipart() and msg.get_content_type() == 'text/plain': print msg.get('Subject') print msg.get_payload() pop.quit() Why aren't the message flagged as read? Is there a way to manually mark them read? Thanks, EuGeNe -- http://www.3kwa.com From apatheticagnostic at gmail.com Wed Jun 6 15:26:57 2007 From: apatheticagnostic at gmail.com (kaens) Date: Wed, 6 Jun 2007 15:26:57 -0400 Subject: Beginning Python In-Reply-To: <1181053786.724436.132900@n15g2000prd.googlegroups.com> References: <1181053786.724436.132900@n15g2000prd.googlegroups.com> Message-ID: <163f0ce20706061226o277c5303se1457a528d1585c@mail.gmail.com> On 6/5/07, abhiee wrote: > Hello , I have just begun learning python...and I'm loving it...Just > wanted to ask you that how much time would it take me to learn python > completely and which languages should i learn alongwith python to be a > good professional programmer?...Now i only know C.... > thanx in advance! > > -- > http://mail.python.org/mailman/listinfo/python-list > Speaking for myself - I've been messing around with various programming languages most of my life (I'm 21, young...). I've done a lot of work in C++, and a little bit in a whole lot of other languages. It took me around 6 hours to learn enough python to write a non-trivial app with it. I've been working with python for a little more than a month, and I'm starting to feel like I know the language decently - I don't have to look stuff up as much - but I'm still learning, as there's a lot to learn. As for how long it takes to become a professional programmer using python, I guess that depends on your definition of professional. I do freelance work, and I'm currently working on a python project - and I have relatively little experience with python, if you measure that in time. Keep a copy of the official docs handy, and always review your options for solving a particular problem and you should catch on pretty well in a relatively short amount of time. From bretthoerner at bretthoerner.com Mon Jun 18 12:08:52 2007 From: bretthoerner at bretthoerner.com (Brett Hoerner) Date: Mon, 18 Jun 2007 16:08:52 -0000 Subject: getting the size of an object In-Reply-To: References: Message-ID: <1182182932.947333.251020@o61g2000hsh.googlegroups.com> On Jun 18, 11:07 am, "filox" wrote: > is there a way to find out the size of an object in Python? e.g., how could > i get the size of a list or a tuple? "Size" can mean a lot of things, len(my_list) len(my_tuple) Although I have the feeling you mean "how many bytes does this object take in memory" - and I believe the short answer is no. Brett From DPhillips at cybergroup.com Mon Jun 11 00:48:36 2007 From: DPhillips at cybergroup.com (Doug Phillips) Date: Sun, 10 Jun 2007 23:48:36 -0500 Subject: Python optimization (was Python's "only one way to do it"philosophy isn't good?) In-Reply-To: <1181532143.803244.264740@w5g2000hsg.googlegroups.com> Message-ID: <9A9D5186629F3D428E3C7CBA92A66E47D2F296@mail-26ps.atlarge.net> > Is anyone out there who uses MS Word and doesn't deactivate > the "suggest" mode i.e. Clippy? Me... I don't install Clippy (or any of his horribly annoying friends) to start with. :) On the topic though, the suggest mode of the MS help system is generally way off-base, even for my 80-yr-old grandmother's needs. From bj_666 at gmx.net Wed Jun 13 13:45:43 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Wed, 13 Jun 2007 19:45:43 +0200 Subject: problem on waiting exit thread and write on file References: <1181749731.260357.192390@q19g2000prn.googlegroups.com> Message-ID: In <1181749731.260357.192390 at q19g2000prn.googlegroups.com>, Flyzone wrote: > I need to run in thread a command, one thread for one parameter. > So i made a for loop, creating 5 threads and waiting their stop with: > Main { > open file BW2 for write > ..... (creating list of thread with a counter).... > Stopped=False > while (Stopped == False): > if not thread5.isAlive(): > if not thread4.isAlive(): > if not thread3.isAlive(): > if not thread2.isAlive(): > if not thread1.isAlive(): > Stopped=True > if (Stopped == False): > time.sleep(0.3) If you create a list with threads where do the names `thread1` to `thread5` come from? This snippet expects the threads in a list or another iterable: for thread in threads: thread.join() Much shorter, isn't it!? :-) Ciao, Marc 'BlackJack' Rintsch From paul at boddie.org.uk Thu Jun 7 17:59:22 2007 From: paul at boddie.org.uk (Paul Boddie) Date: Thu, 07 Jun 2007 14:59:22 -0700 Subject: EuroPython 2007: Early Registration Deadline and Draft Timetable Message-ID: <1181253562.301173.127440@k79g2000hse.googlegroups.com> EuroPython is the European Python and Zope Conference, taking place this year in Vilnius, Lithuania from Monday 9th July to Wednesday 11th July. The last day of EuroPython's early registration period is upon us: reduced rates will only be available until the end of today, Friday 8th June; after this date, normal rates will apply. More information on registration can be found here: * http://www.europython.org/sections/registration_issues/how-to-register Help with issues related to registration is provided here: * http://www.europython.org/sections/registration_issues/help-on-registration In addition, a draft timetable of talks has now been made available on the EuroPython Web site: * http://www.europython.org/sections/tracks_and_talks/draft-timetable Act now to ensure your place at EuroPython and secure yourself a generous discount on the registration fee! From duncan.booth at invalid.invalid Wed Jun 13 04:04:10 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 13 Jun 2007 08:04:10 GMT Subject: Multiline lamba implementation in python. References: <1b0ce1b60706112002i761dc295x9ba9c4f589c41db1@mail.gmail.com> <1b0ce1b60706121648id58bee1mc0c184bf67271262@mail.gmail.com> Message-ID: "Gabriel Genellina" wrote: > But you already have "multiline" lambdas right now in that sense, no > need to add anything. I think you were talking about lambdas *with* > statements inside. > > bin = lambda x:((x&8 and '*' or '_') + > (x&4 and '*' or '_') + > (x&2 and '*' or '_') + > (x&1 and '*' or '_')) Or in more recent versions of Python: bin = lambda x:(('*' if x&8 else '_') + ('*' if x&4 else '_') + ('*' if x&2 else '_') + ('*' if x&1 else '_')) but seriously, any example of lambda which simply assigns the function to a variable is flawed. I can sort of understand the people who object to a named function taking the logic 'out of line', but any expression which actually requires a multi-statement function to be embedded in the middle of it is already in danger of causing my brain to implode. From basti.wiesner at gmx.net Sat Jun 30 07:31:48 2007 From: basti.wiesner at gmx.net (Sebastian Wiesner) Date: Sat, 30 Jun 2007 13:31:48 +0200 Subject: Building a Python app with Mozilla In-Reply-To: <5emhodF380g5gU2@mid.uni-berlin.de> References: <5emhodF380g5gU2@mid.uni-berlin.de> Message-ID: <200706301331.54436.basti.wiesner@gmx.net> [ "Diez B. Roggisch" ] > And as it has been said in this thread already, Qt has an excellent free > GUI-builder. Free as long as you develop free software. Development of proprietary, non-gpl software with Qt requires a commercial licence from Trolltech. -- Freedom is always the freedom of dissenters. (Rosa Luxemburg) -------------- 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 cody314 at gmail.com Mon Jun 4 15:18:06 2007 From: cody314 at gmail.com (cody314 at gmail.com) Date: Mon, 04 Jun 2007 19:18:06 -0000 Subject: Python Memory Leak using SWIG Message-ID: <1180984686.314914.296660@g37g2000prf.googlegroups.com> Versions: Python 2.5.1 (r251:54863, May 14 2007, 10:50:04) SWIG Version 1.3.20 Hello I have some code that wraps a C++ library so I may use it in python. The code basically just gets some data and puts it in the PyArrayObject* which is returned as a PyObject*. I then call it from python like so: self.c = __f2.fdct2_wrapper(x,self.nbs,self.nba,self.ac) I then loop (which pretty much only calls this function) over and over. I put the variable as a self.c hoping the garbage collector would know how to delete it after the class goes out of scope. I also tried explicitly deleting the variable (del var) in the loop with no success. In all cases quiet a large memory leak occurs (and grows rather quickly). I believe this is comming from the fact that the thing that is returned is a pointer to the data. So the returning object is a pointer. The python garbage collector then doesn't know how to delete this structure and probably (maybe) just deletes the pointer after the class goes out of scope. Leave the data there and causing the memory leak issue. I however doesn't know how to tell python that this variable is a pointer and to delete whats going to it. Or perhaps tell SWIG to delete the data, and return the structure some other way? Here is the c++ wrapping code, perhaps there is an easy way to fix this memory leak (I believe a lot of SWIG people probably do this) perhaps some function call from the python? or some special call from the SWIG? Thanks a bunch! // set up the list output PyListObject* out; PyArrayObject* output; out = (PyListObject*) PyList_New(0); npy_intp dims[2]; int i,j; for(i=0;iflags = output->flags | NPY_OWNDATA; } } return (PyObject*) out; From twisted0n3 at gmail.com Fri Jun 22 18:03:51 2007 From: twisted0n3 at gmail.com (Twisted) Date: Fri, 22 Jun 2007 22:03:51 -0000 Subject: The Modernization of Emacs: terminology buffer and keybinding In-Reply-To: References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182272495.990807.99110@a26g2000pre.googlegroups.com> <87tzt3ihev.fsf@kobe.laptop> <1182370216.961241.6960@n60g2000hse.googlegroups.com> Message-ID: <1182549831.068658.123870@i13g2000prf.googlegroups.com> On Jun 21, 10:52 am, Bjorn Borud wrote: > [Twisted ] > | > | Being beginner-friendly doesn't have to be at the expense of power or > | expert-user usability. > > depends on your definition of "expert". :-) Well, admittedly, if your definition of "expert" is "elitist pig who considers beginner-hostileness itself to be a required feature in order for him to regard the software as usable", then you may be right. That sort of negative-sum thinking is alien to me. Software being easy for beginners to get started using does not in and of itself detract from its value to expert users. Only if they "value" such perverse things as "being one of the exclusive club that can actually manage to use this thing" does any of this make sense. That's a form of artificial scarcity, and as I think I've mentioned before, artificial scarcity is one of the more major roots of evil. From fumanchu at amor.org Mon Jun 11 13:34:41 2007 From: fumanchu at amor.org (fumanchu) Date: Mon, 11 Jun 2007 10:34:41 -0700 Subject: Threads, signals and sockets (on UNIX) In-Reply-To: <1181558099.401945.298780@k79g2000hse.googlegroups.com> References: <1181558099.401945.298780@k79g2000hse.googlegroups.com> Message-ID: <1181583281.351853.277130@r19g2000prf.googlegroups.com> On Jun 11, 3:34 am, geoffbache wrote: > I have a Python program (on UNIX) whose main job is to listen on a > socket, for which I use the SocketServer module. However, I would also > like it to be sensitive to signals received, which it isn't if it's > listening on the socket. ("signals can only be received between atomic > actions of the python interpreter", presumably - and control will not > return to Python unless something appears on the socket). Does anyone > have a tip of a good way to do this? > > I can of course put the SocketServer in a thread and call > signal.pause() in the main thread, but this falls down when the > SocketServer terminates normally, as the signal.pause() cannot be > interrupted except via signals. So I tried sending a "dummy" signal > (SIGCHLD) from the thread when the SocketServer terminates, which > seems to work on Linux but not Solaris. And which in any case feels a > bit hackish - surely there has to be a better way? Use a timeout on your socket and put socket.accept() in a loop: mainsocket.settimeout(1) while True: try: childsocket, addr = mainsocket.accept() handle(childsocket, addr) except socket.timeout: pass Robert Brewer System Architect Amor Ministries fumanchu at amor.org From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Thu Jun 21 09:45:35 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Thu, 21 Jun 2007 15:45:35 +0200 Subject: Globals in nested functions References: <1182424010.561262.169170@j4g2000prf.googlegroups.com> Message-ID: <5dvdnvF3733m7U1@mid.individual.net> jm.suresh at no.spam.gmail.com wrote: > def f(): > a = 12 > def g(): > global a > if a < 14: > a=13 > g() > return a > > print f() > > This function raises an error. Is there any way to access the a in > f() from inside g(). Yes. Pass it to g when calling the latter and let g return the result. def f(): a = 12 def g(parm): if parm < 14: return 13 else: return a a = g(a) return a print f() Strange refactoring though. Regards, Bj?rn -- BOFH excuse #400: We are Microsoft. What you are experiencing is not a problem; it is an undocumented feature. From roberth+news at ifi.uio.no Wed Jun 13 11:03:00 2007 From: roberth+news at ifi.uio.no (Robert Bauck Hamar) Date: Wed, 13 Jun 2007 17:03:00 +0200 Subject: Is there any way to catch expections when call python method in C++ References: <1181727704.631721.269650@g37g2000prf.googlegroups.com> Message-ID: Allen wrote: > I use try catch, but cannot catch the execeptions of execution python > method. > > PYCALL_API void PyCall(const char * pszModule, const char * pszFunc, > void * pArg) > { > if (pszModule == NULL || pszFunc == NULL) > { > return; > } > > Py_Initialize(); > > PyObject * pModule = NULL; > PyObject * pFunc = NULL; > > try { > > pModule = PyImport_ImportModule(pszModule); > pFunc = PyObject_GetAttrString(pModule, pszFunc); > > PyEval_CallObject(pFunc, (PyObject*)pArg); > } catch (...) { > fprintf(stderr, "Error: call python method failed"); > } > > Py_Finalize(); > } > > Can I catch it from C++? No. CPython is written in C, not C++, and C has no concept of exceptions. Exceptions in Python is usually indicated by return value in the interpreter, and has no mapping to the C++ exception model. You should never let C++ exceptions propagate into the python functions either. PyImport_ImportModule will return NULL if an exception occured, and so will also PyObject_GetAttrString and PyEval_CallObject do. -- rbh From borud-news at borud.no Thu Jun 21 10:10:46 2007 From: borud-news at borud.no (Bjorn Borud) Date: 21 Jun 2007 16:10:46 +0200 Subject: The Modernization of Emacs References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182344981.372713.298580@w5g2000hsg.googlegroups.com> <86y7ieoiv7.fsf@lola.quinscape.zz> <1182347061.347199.133480@g4g2000hsf.googlegroups.com> <874pl2eg2j.fsf@W0053328.mgh.harvard.edu> <1182370016.986915.202150@u2g2000hsc.googlegroups.com> Message-ID: [Twisted ] | | Given that in its out-of-the-box configuration it's well-nigh unusable | without a printed-out "cheat sheet" of some kind, of the sort that | were supposed to have died out in the 80s, getting it customized poses | something of a catch-22 for anyone trying to get started using it. indeed, not adhering to the half a dozen keybinding and menu conventions that most newer applications use on OSX and Windows today is not ideal UI design, but it doesn't really present that much of a problem either; so it ends up being a non-issue to any regular user. (actually, it isn't merely a case of changing some keybindings and names -- the problem is that Emacs has a bunch of concepts that are not easily mapped to trivial editor semantics, so it would be hard to change without causing further confusion). Emacs isn't really meant for the casual user and there are editors far better suited for those who think spending an afternoon learning it is too much. (compare to VI or VIM, which probably takes even a bit longer to grasp, but which is beautifully practical once you understand how it works. there's this good tech-talk given by Bram Moolenaar available? on about text editing and VIM). ?) http://video.google.com/videoplay?docid=2538831956647446078 -Bj?rn From jim.hefferon at gmail.com Sun Jun 24 12:30:33 2007 From: jim.hefferon at gmail.com (Jim) Date: Sun, 24 Jun 2007 09:30:33 -0700 Subject: database design help In-Reply-To: References: Message-ID: <1182702633.557078.231310@n60g2000hse.googlegroups.com> It sounds to me that you want Subversion. There is a Python binding if you have anything you'd need to do beyond what already comes with the system (there are a variety of web interfaces already out there, for instance, so I don't know that you'd need to do anything extra). Just google "subversion". Jim From evan at yelp.com Wed Jun 20 00:43:56 2007 From: evan at yelp.com (Evan Klitzke) Date: Tue, 19 Jun 2007 21:43:56 -0700 Subject: Python IDE In-Reply-To: <5dq3n9F359hp0U1@mid.individual.net> References: <1182249585.535675.143460@m36g2000hse.googlegroups.com> <1182259143.375798.283620@k79g2000hse.googlegroups.com> <5dq3n9F359hp0U1@mid.individual.net> Message-ID: On 6/19/07, Bjoern Schliessmann wrote: > BartlebyScrivener wrote: > > VIM > > *clap-clap* > > BTW, are there tutorials on the more arcane vim functions that come > in handy with Python? I don't know of any vim functions that are python specific, but to me the two somewhat arcane things that are really important to using vim efficiently in programming in general are window splitting and folding. Folding can be immensely useful for moving through files and keeping important information visible. Ctags is also useful -- it lets you jump to where the class/function under the cursor is defined. Window tabbing is also new as of vim 7, but I prefer window splits. You'll probably want to write some vim macros to help you use the window splits more efficiently (e.g. to to move up a split and maximize it in one key stroke). There's a script on vim.org for using the unittest module with the :make command, which is also useful if you use that module a lot. And of course if you build vim with python support, you can script vim using python! Another thing I've noticed is that there are a couple of different work flows that people have for testing code they're writing in vim. The simplest way to run a script is with ":!python %" (sans quotes), which runs the script with the output going to vim which pretends to be a terminal. I think this is sort of suboptimal because vim isn't a real terminal so some programs will act strangely this way. The workflow I have is a screen session with vim in one (or more) "windows" and another "window" that is just a shell, which I run my scripts in. Another method that I've seen is to just background vim with Ctrl-Z, run the program, and then foreground the vim session to go back to the code. Either way, I think running your session in screen is really, really useful because you can do a search through the screen buffer for occurrences of certain words (I tend to do a backwards search, with Ctrl-a [ ?search_term), which can help you search through the output of your program quickly when things go awry. IF you're a fan of screen (or want to use it), I have a pretty nifty .screenrc that I use that shows the screen "windows" on a status line at the bottom with some other nifty information (the hostname of the machine screen is running on, the load information, and the time) as well, plus support for 256 colors, which lets you use those nice 256 color vim colorschemes. If you're interested you can grab it at http://eklitzke.org/files/.screenrc -- Evan Klitzke From dak at gnu.org Tue Jun 26 10:25:13 2007 From: dak at gnu.org (David Kastrup) Date: Tue, 26 Jun 2007 16:25:13 +0200 Subject: The Modernization of Emacs: terminology buffer and keybinding References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182547318.325617.16370@o11g2000prd.googlegroups.com> <1182657564.912472.55570@g4g2000hsf.googlegroups.com> <5eaptcF378d21U3@mid.individual.net> <1182811109.258156.306150@k79g2000hse.googlegroups.com> <1182837690.585067.165060@p77g2000hsh.googlegroups.com> <1182838964.721578.196400@p77g2000hsh.googlegroups.com> <5eclebF37uh5mU1@mid.dfncis.de> Message-ID: <867ipqsshi.fsf@lola.quinscape.zz> Matthias Buelow writes: > Twisted wrote: > > [...] > > Hey dude, > > get back to selling used cars and leave us computer geeks alone, > will ya? Well, how will his customers react to the stories about avoiding Mercedes cars because of people getting hit in the face by the crank start? -- David Kastrup From eugene.vandenbulke at gmail.com Wed Jun 20 05:42:15 2007 From: eugene.vandenbulke at gmail.com (EuGeNe Van den Bulke) Date: Wed, 20 Jun 2007 11:42:15 +0200 Subject: poplib.retr doens't flag message as read References: Message-ID: Gabriel Genellina wrote: > The POP protocol has no concept of "read" or "unread" messages; the LIST > command simply shows all existing messages. My mistake, I guess I was confused by the documentation retr( which) Retrieve whole message number which, and set its seen flag. Result is in form (response, ['line', ...], octets). What is the seen flag? Nothing it seems http://mail.python.org/pipermail/python-list/2005-July/329888.html Thanks for your help, EuGeNe -- http://www.3kwa.com From deets at nospam.web.de Tue Jun 12 08:46:16 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 12 Jun 2007 14:46:16 +0200 Subject: Python optimization (was Python's "only one way to do it" philosophy isn't good?) References: <1181368143.874341.273140@r19g2000prf.googlegroups.com> <9OVai.7525$u56.7287@newssvr22.news.prodigy.net> <5d4broF31klo5U1@mid.uni-berlin.de> Message-ID: <5d7isoF32nsm9U1@mid.uni-berlin.de> John Nagle wrote: > Diez B. Roggisch wrote: >> Regardless of the possibility of speeding it up - why should one want >> this? Coding speed is more important than speed of coding in 90%+ of all >> cases. > > When you have to start buying more servers for the server farm, > it's a real pain. I'm actually facing that because Python's HTML > parsing is so slow. I can't believe that this is a general "python is to slow"-issue. After all, lxml and cElementTree are _really_ fast - and written in C. For example in TurboGears, there are two python-only templating systems - KID & genshi (apart from others). The latter is a magnitude faster than the former. After all, O(n^3) is O(n^3), regardless of the language... And if only the html-parsing is slow, you might consider creating an extension for that. Using e.g. Pyrex. Diez From nick at craig-wood.com Mon Jun 4 05:30:05 2007 From: nick at craig-wood.com (Nick Craig-Wood) Date: Mon, 04 Jun 2007 04:30:05 -0500 Subject: Comments appreciated on Erlang inspired Process class. References: Message-ID: Brian L. Troutwine wrote: > Lately I've been tinkering around with Erlang and have begun to sorely want > some of its features in Python, mostly the ease at which new processes can be > forked off for computation. To that end I've coded up a class I call, > boringly enough, Process. It takes a function, its args and keywords and runs > the function in another process using os.fork. Processes can be treated as > callables to retrieve the return value of the passed in function. > > The code is pasted here: http://deadbeefbabe.org/paste/4972. A simple > exposition of Process is included at the end of the code in some __main__ > magic. (Note: The code will not run on any system which lacks os.fork and > spawns 100 child processes while running.) > > I'd very much appreciate people to look the code over and give me their > reactions to it, or suggests for improvement. As it stands, I see three major > defects with the current implementation: > > 1) Process hangs forever if its child errors out. > > 2) Process isn't portable because of its use of os.fork(). > > 3) Process should use AF_UNIX when available instead of TCP. You could use os.pipe() or socket.socketpair(). It would simplify the code a lot too! The biggest problem I see is that there is no non-blocking way of seeing whether the Process() has finished or not, and no way to wait on more than one Process() at once. If there is an exception then you should return it to the parent (see the subprocess module for an example). -- Nick Craig-Wood -- http://www.craig-wood.com/nick From jimxu at google.com Fri Jun 15 17:44:46 2007 From: jimxu at google.com (Yongjian Xu) Date: Fri, 15 Jun 2007 14:44:46 -0700 Subject: Get the current date, python 2.2 In-Reply-To: References: Message-ID: <9c09a1210706151444o1ac6a35h4cc69fddf3e805cc@mail.gmail.com> time.strftime('%Y-%m-%d', time.localtime()) gives you just the date format. Jim On 6/15/07, nano wrote: > > Using python 2.2 what is the simplest way to get the current date value? > I have looked in so many places. The question is often asked and the > usual response indicates how to get the current date and time like > > now = time.localtime() > > I want just the date, like 2007-06-15. The value will go into a > postgresql Date type column. > > Also, if postgres field of this type is set to time.localtime(), is the > time portion of the date discarded, or stored 'invisibly', of will there > be an error of some type? Just thought someone here might know. > -- > http://mail.python.org/mailman/listinfo/python-list > -- Yongjian (Jim) Xu =========== Sysops -------------- next part -------------- An HTML attachment was scrubbed... URL: From grante at visi.com Mon Jun 4 15:48:52 2007 From: grante at visi.com (Grant Edwards) Date: Mon, 04 Jun 2007 19:48:52 -0000 Subject: Who uses Python? References: <1180985830.288414.208850@q69g2000hsb.googlegroups.com> Message-ID: <1368r54f8u69848@corp.supernews.com> On 2007-06-04, walterbyrd wrote: > Anything else? Finance? Web-analytics? SEO? Digital art? Electrical engineering. It's pretty handy for writing programs to talk to embedded systems using various protocols/interface (async-serial, ethernet, etc.). It's also good for analyzing communications, analyzing performance tests for analog instruments, and so on. -- Grant Edwards grante Yow! Edwin Meese made me at wear CORDOVANS!! visi.com From http Wed Jun 27 04:15:16 2007 From: http (Paul Rubin) Date: 27 Jun 2007 01:15:16 -0700 Subject: Python's "only one way to do it" philosophy isn't good? References: <1182750077.570603.160240@q69g2000hsb.googlegroups.com> <7xir9cbm0g.fsf@ruckus.brouhaha.com> <7xejjzmk7u.fsf@ruckus.brouhaha.com> <7xy7i7xjl5.fsf@ruckus.brouhaha.com> Message-ID: <7x4pkt4xuz.fsf@ruckus.brouhaha.com> Dennis Lee Bieber writes: > What happens when two individuals release "libraries" using these > proposed macros -- and have implement conflicting macros using the same > identifiers -- and you try to use both libraries in one application? Something like the current situation with Python web frameworks ;) From kinch1967 at gmail.com Sun Jun 10 08:36:16 2007 From: kinch1967 at gmail.com (bullockbefriending bard) Date: Sun, 10 Jun 2007 05:36:16 -0700 Subject: matching objects by a tuple field criterion In-Reply-To: <5d286hF32u0ciU1@mid.uni-berlin.de> References: <1181473124.790391.293120@r19g2000prf.googlegroups.com> <1181476538.812941.37490@r19g2000prf.googlegroups.com> <5d286hF32u0ciU1@mid.uni-berlin.de> Message-ID: <1181478976.576396.139890@j4g2000prf.googlegroups.com> > There are certainly cases where the speedup is tremendous - think of a > single integer in the first criteria - but then the overall performance > depends on the real-live queries. If lot's of wildcards are used, you > might end up slower if the tree-walk takes more time than the > C-implemented list-iteration will cost you. hopefully, won't need to do this then. i'll test the filter approach tonight. generally speaking, going to be mostly wildcards most of the time. From harry.g.george at boeing.com Mon Jun 25 00:54:57 2007 From: harry.g.george at boeing.com (Harry George) Date: Mon, 25 Jun 2007 04:54:57 GMT Subject: Setuptools, build and install dependencies References: <87645gx0qb.fsf@benfinney.id.au> Message-ID: Robert Kern writes: > Harry George wrote: > >> We need to know the dependencies, install them in dependency order, >> and expect the next package to find them. "configure" does this for >> hundreds of packages. cmake, scons, and others also tackle this >> problem. Python's old setup.py seems to be able to do it. > > No, generic setup.py scripts don't do anything of that kind. > Ok, setup.py itself may not do the work, but from the end users' perspective it works that way. Setup.py runs a configure and a make, which in turn find the right already-installed libraries. The point is, setup.py plays well in such an environment. > -- > 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 > -- Harry George PLM Engineering Architecture From lobais at gmail.com Tue Jun 5 11:15:39 2007 From: lobais at gmail.com (Thomas Dybdahl Ahle) Date: Tue, 05 Jun 2007 17:15:39 +0200 Subject: subprocess leaves child living References: <1181052375.551083.117390@p47g2000hsd.googlegroups.com> Message-ID: Den Tue, 05 Jun 2007 07:06:15 -0700 skrev Rob Wolfe: > Thomas Dybdahl Ahle wrote: > >> Problem is - I can't do that when I get killed. Isn't it possible to >> open processes in such a way like terminals? If I kill the terminal, >> everything open in it will die too. > > On POSIX platform you can use signals and ``os.kill`` function. Fo > example: > > > import os, signal > from subprocess import Popen > from time import sleep > > def handler(signum, frame): > print 'Signal handler called' > raise KeyboardInterrupt > > signal.signal(signal.SIGTERM, handler) > > try: > popen = Popen(["ping", "google.com"]) try: > sleep(100) > except KeyboardInterrupt: > pass > finally: > if popen.poll() is None: > print "killing process: %d" % popen.pid os.kill(popen.pid, > signal.SIGTERM) > But you can't ever catch sigkill. Isn't there a way to make sure the os kills the childprocess when the parrent dies? From steven.bethard at gmail.com Sat Jun 2 12:12:37 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Sat, 02 Jun 2007 10:12:37 -0600 Subject: Observer-Pattern by (simple) decorator In-Reply-To: References: <1180781727.519949.172580@q75g2000hsh.googlegroups.com> Message-ID: Wildemar Wildenburger wrote: >>>> class Observable(object): > ... def __init__(self, func, instance=None, observers=None): > ... self.func = func > ... self.instance = instance > ... self.observers = observers or [] Unless you also changed code in __get__, this means you'll get a new list every time you access the "meth" attribute since the __get__ method is called anew for every attribute access:: >>> class SomeActor(object): ... @Observable ... def meth(self, foo): ... print foo ... >>> def callback(instance): ... print "Yippie, I've been called on", instance ... instance.bar = True ... >>> # only accessing the "meth" attribute once >>> meth = a1.meth >>> meth.add_callback(callback) >>> meth('a1') a1 Yippie, I've been called on <__main__.SomeActor object at 0x00E87CB0> >>> # accessing the "meth" attribute multiple times >>> a1 = SomeActor() >>> a1.meth.add_callback(callback) >>> a1.meth('a1') a1 See my other post for how to get instance-level observer lists using a WeakKeyDictionary. STeVe From showell30 at yahoo.com Thu Jun 7 19:45:55 2007 From: showell30 at yahoo.com (Steve Howell) Date: Thu, 7 Jun 2007 16:45:55 -0700 (PDT) Subject: Bragging about Python In-Reply-To: Message-ID: <664296.60496.qm@web33502.mail.mud.yahoo.com> --- Georg Brandl wrote: > >> > >> 15 small programs here: > >> > >> http://wiki.python.org/moin/SimplePrograms > >> > > > > IMHO a few python goodies are missing there. > > "It's a Wiki." ;) > Yes indeed. Please feel free to add to the page, or make your own fork. See link above. ____________________________________________________________________________________ Bored stiff? Loosen up... Download and play hundreds of games for free on Yahoo! Games. http://games.yahoo.com/games/front From bbrown at speakeasy.net Fri Jun 22 01:23:46 2007 From: bbrown at speakeasy.net (Robert Brown) Date: Fri, 22 Jun 2007 01:23:46 -0400 Subject: Python's "only one way to do it" philosophy isn't good? References: <1181368143.874341.273140@r19g2000prf.googlegroups.com> <7x3b0nmkk6.fsf@ruckus.brouhaha.com> Message-ID: Neil Cerutti writes: > On 2007-06-21, Douglas Alan wrote: >> A prime example of this is how CLOS, the Common Lisp Object System was >> implemented completely as a loadable library (with the help of many >> macros) into Common Lisp, which was not an OO language prior to the >> adoption of CLOS. > > Is there a second example? ;) There are many useful macro packages that syntactically extend Common Lisp. Here are a few representative examples. comp an implementation of list comprehensions http://rali.iro.umontreal.ca/Publications/urls/LapalmeLispComp.pdf iterate a domain specific language for expressing complex iteration http://common-lisp.net/project/iterate/ screamer support for nondeterministic programming http://www.cis.upenn.edu/~screamer-tools/screamer-intro.html cl-who a domain specific language for HTML generation http://weitz.de/cl-who/ parenscript a domain specific language for JavaScript generation http://common-lisp.net/project/parenscript/ From http Sat Jun 23 11:22:38 2007 From: http (Paul Rubin) Date: 23 Jun 2007 08:22:38 -0700 Subject: SIMD powered Python References: <1182554657.444684.268050@i13g2000prf.googlegroups.com> <1182607699.214626.85230@u2g2000hsc.googlegroups.com> Message-ID: <7xbqf6r8zl.fsf@ruckus.brouhaha.com> Marc 'BlackJack' Rintsch writes: > > True... But maybe in NumPy arrays that would be more feasible...? > > Yes but that's in external libraries and not in the Python interpreter. > So it won't speed up Python code like list comprehensions but "just" calls > to external functions written in C, Fortran or assembler if those make use > of SIMD instructions. Right, Python has such poor control over side effects that it has not much chance of parallelizing stuff like list comprehensions in general. Maybe there's some chance of doing it for some special cases with RPython. See http://www.google.com/search?q="nested+data+parallelism" for what's happening with some other languages. From gagsl-py2 at yahoo.com.ar Thu Jun 14 02:12:51 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 14 Jun 2007 03:12:51 -0300 Subject: How to save python codes in files? References: <1181711063.512249.289520@x35g2000prf.googlegroups.com> <1181721972.486523.37680@g37g2000prf.googlegroups.com> <1181722913.777141.279570@n15g2000prd.googlegroups.com> <1181796973.366518.245050@x35g2000prf.googlegroups.com> Message-ID: En Thu, 14 Jun 2007 01:56:13 -0300, why? escribi?: > I tried but its not working. Here's a code for sum of two numbers. Now > how do i save it? > >>>> #! /usr/bin/env python > ... >>>> def sum(x,y): > ... return x+y > ... >>>> x=int(raw_input('Enter a number: ')) > Enter a number: 35 >>>> y=int(raw_input('Enter a number: ')) > Enter a number: 7 >>>> print 'sum is', sum(x,y) > sum is 42 You *don't* write your program inside Python; the interactive prompt is just for testing a few lines of code. Instead, use another program (a text editor) to create a file containing your source code, save it using a name like test1.py, and run it from a shell prompt using: python test1.py I think that Red Hat comes with gedit as the default editor, you should find it under Accesories, Text Editor or similar; any other editor (like nano) would be fine too. Open it and write your program: === begin === #! /usr/bin/env python def sum(x,y): return x+y x=int(raw_input('Enter a number: ')) y=int(raw_input('Enter a number: ')) print 'sum is', sum(x,y) === end === Copy all text between the marks === begin ===, and === end === (but not including those marks). Save it into your home directory - when prompted for a name, type "test1.py" (without quotes). (If you don't know what is your home directory, read your OS documentation). Now open a shell prompt (or terminal). Run the command "ls" (without quotes; press ENTER). You should see test1.py listed. (If not, use the cd command to go to your home directory and try again). Now execute "python test1.py" (again, without quotes) and you should be asked for the numbers, and the program should display the sum (as you already have seen inside the Python interpreter). If you want to change the program: go back into the editor, modify it, save it (with the same name, or a different one), switch to the shell prompt and run it again. These are the very basics of writing a text file and executing a Python program from the shell prompt. There are more powerful editors that are aware of Python syntax, by example, and can display the source code with different colors for keywords, numbers, comments, etc. Other programs combine an editor + debugger + code autocompletion + other nice features (they're called IDEs, in general). I hope this is of some help. You should read the OS documentation for more info on how to edit a file and such things. -- Gabriel Genellina From toby at tobiah.org Wed Jun 6 18:13:57 2007 From: toby at tobiah.org (Tobiah) Date: Wed, 06 Jun 2007 15:13:57 -0700 Subject: Accessing function in a module by name Message-ID: <466724f7$0$16372$88260bb3@free.teranews.com> Is there a way to call function in an imported module having only the name? func_name = 'doit' real_func = foo.some_magic(func_name) #Now call it real_func(args) I'm trying to set up a function dispatcher for a SOAP server. Thanks, Tobiah -- Posted via a free Usenet account from http://www.teranews.com From Leo.Kislov at gmail.com Thu Jun 14 01:46:01 2007 From: Leo.Kislov at gmail.com (Leo Kislov) Date: Wed, 13 Jun 2007 22:46:01 -0700 Subject: Method much slower than function? In-Reply-To: <1181781612.939800.238890@q19g2000prn.googlegroups.com> References: <1181781612.939800.238890@q19g2000prn.googlegroups.com> Message-ID: <1181799961.148499.32210@o11g2000prd.googlegroups.com> On Jun 13, 5:40 pm, ido... at gmail.com wrote: > Hi all, > > I am running Python 2.5 on Feisty Ubuntu. I came across some code that > is substantially slower when in a method than in a function. > > >>> cProfile.run("bar.readgenome(open('cb_foo'))") > > 20004 function calls in 10.214 CPU seconds > >>> cProfile.run("z=r.readgenome(open('cb_foo'))") > > 20004 function calls in 0.041 CPU seconds > I suspect open files are cached so the second reader picks up where the first one left: at the of the file. The second call doesn't do any text processing at all. -- Leo From ptmcg at austin.rr.com Thu Jun 21 12:55:05 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: Thu, 21 Jun 2007 09:55:05 -0700 Subject: newbie question: parsing street name from address In-Reply-To: <1182433644.485185.197690@w5g2000hsg.googlegroups.com> References: <1182433644.485185.197690@w5g2000hsg.googlegroups.com> Message-ID: <1182444905.895324.326870@o61g2000hsh.googlegroups.com> On Jun 21, 8:47 am, cjl wrote: > P: > > I am working on a project that requires geocoding, and have written a > very simple geocoder that uses the Google service. > > I would like to be able to extract the name of the street from the > addresses in my data, however they vary significantly. Here a some > examples: > > 25 Main St > 2500 14th St > 12 Bennet Pkwy > Pearl St > Bennet Rd and Main st > 19th St > > As you can see, sometimes I have the house number, and sometimes I do > not. Sometimes the street name is a number. Sometimes I simply have > the names of intersecting streets. > > I would like to be able to parse the above into the following: > > Main St > 14th St > Bennet Pkwy > Pearl St > Bennet Rd > Main St > 19th St > > How might I approach this complex parsing problem? > > -CJL Parsing street addresses is a very complex parsing problem. Please look at this example (http://pyparsing.wikispaces.com/space/showimage/ streetAddressParser.py) from the pyparsing wiki, which includes support for these test cases: 100 South Street 123 Main 221B Baker Street 10 Downing St 1600 Pennsylvania Ave 33 1/2 W 42nd St. 454 N 38 1/2 21A Deer Run Drive 256K Memory Lane 12-1/2 Lincoln 23N W Loop South 23 N W Loop South I took your list and added them to the test cases, which broke a few lines in the grammar. The current online version now includes support for your new formats as well. Here is some sample output from the pyparsing example: 100 South Street ['100', 'South', 'Street'] - name: South - number: 100 - street: ['100', 'South', 'Street'] - name: South - number: 100 - type: Street - type: Street Street is South 221B Baker Street ['221B', 'Baker', 'Street'] - name: Baker - number: 221B - street: ['221B', 'Baker', 'Street'] - name: Baker - number: 221B - type: Street - type: Street Street is Baker Street 10 Downing St ['10', 'Downing', 'St'] - name: Downing - number: 10 - street: ['10', 'Downing', 'St'] - name: Downing - number: 10 - type: St - type: St Street is Downing St 1600 Pennsylvania Ave ['1600', 'Pennsylvania', 'Ave'] - name: Pennsylvania - number: 1600 - street: ['1600', 'Pennsylvania', 'Ave'] - name: Pennsylvania - number: 1600 - type: Ave - type: Ave Street is Pennsylvania Ave 33 1/2 W 42nd St. ['33 1/2', 'W 42 nd', 'St'] - name: W 42 nd - number: 33 1/2 - street: ['33 1/2', 'W 42 nd', 'St'] - name: W 42 nd - number: 33 1/2 - type: St - type: St Street is W 42 nd St 454 N 38 1/2 ['454', 'N 38 1/2'] - name: N 38 1/2 - number: 454 - street: ['454', 'N 38 1/2'] - name: N 38 1/2 - number: 454 Street is N 38 1/2 25 Main St ['25', 'Main', 'St'] - name: Main - number: 25 - street: ['25', 'Main', 'St'] - name: Main - number: 25 - type: St - type: St Street is Main St 2500 14th St ['2500', '14 th', 'St'] - name: 14 th - number: 2500 - street: ['2500', '14 th', 'St'] - name: 14 th - number: 2500 - type: St - type: St Street is 14 th St 12 Bennet Pkwy ['12', 'Bennet', 'Pkwy'] - name: Bennet - number: 12 - street: ['12', 'Bennet', 'Pkwy'] - name: Bennet - number: 12 - type: Pkwy - type: Pkwy Street is Bennet Pkwy Pearl St ['Pearl', 'St'] - name: Pearl - street: ['Pearl', 'St'] - name: Pearl - type: St - type: St Street is Pearl St Bennet Rd and Main St ['Bennet', 'Rd', 'and', 'Main', 'St'] - crossStreet: ['Bennet', 'Rd'] - name: Bennet - type: Rd - name: Main - street: ['Main', 'St'] - name: Main - type: St - type: St Street is Main St 19th St ['19 th', 'St'] - name: 19 th - street: ['19 th', 'St'] - name: 19 th - type: St - type: St Street is 19 th St -- Paul From sjmachin at lexicon.net Sun Jun 10 08:26:42 2007 From: sjmachin at lexicon.net (John Machin) Date: Sun, 10 Jun 2007 05:26:42 -0700 Subject: matching objects by a tuple field criterion In-Reply-To: <1181473124.790391.293120@r19g2000prf.googlegroups.com> References: <1181473124.790391.293120@r19g2000prf.googlegroups.com> Message-ID: <1181478402.671782.75280@r19g2000prf.googlegroups.com> On Jun 10, 8:58 pm, bullockbefriending bard wrote: > i have a large collection of python objects, each of which contains an > integer 6-tuple as part of its data payload. what i need to be able to > do is select only those objects which meet a simple tuple element > wildcard matching criterion. e.g. given the following python objects: > > object A includes tuple (1,2,3,4,5,6) > object B includes tuple (1,4,4,4,11,1) > object C includes tuple (1,3,9,1,1,1) > > all tuples are unique. for what it's worth, the values in each field > are independent of the other fields and range from 1 to 14. although > 'large', my collection is sparse cf. the 14^6 possible tuples. > > i want to search on *one only* tuple field/value. if my search > criterion is (*,*,*,4,*,*), then i want to find object A and object B. > if (1,*,*,*,*,*), i want to find objects A, B, and C, etc. i will only > ever specify an integer match for one tuple field. > > i can think of some naive approaches, but is there an elegant way to > do this? You are going to have to tell us how many is in a "large" collection, how often you will do this query, how much memory you have to spare, how fast you want the answer back, whether you want the answer as a generator, or in a list/tuple/set/whatever -- or you are going to have to do a fair bit of prototyping and benchmarking. Steven has given you one end of the spectrum: a naive serial scan. Now I'll give you another end: a naive pre-build all possible answers method: [quite untested] # build 14x6 array of empty sets answer = [[set() for what in range(14)] for slot in range(6)] # populate the sucker for obj in obj_list: for slot in range(6): answer[slot][obj.data[slot]-1].add(obj) Later, the answer to 'Which objects have the value 11 in slot 3?' is answer[3][11-1] HTH, John From jgilbert.python at gmail.com Fri Jun 15 22:18:52 2007 From: jgilbert.python at gmail.com (Josh Gilbert) Date: Fri, 15 Jun 2007 22:18:52 -0400 Subject: Multiline lamba implementation in python. In-Reply-To: References: <1b0ce1b60706112002i761dc295x9ba9c4f589c41db1@mail.gmail.com> Message-ID: <200706152218.52121.jgilbert.python@gmail.com> On Wednesday 13 June 2007 4:04 am, Duncan Booth wrote: > "Gabriel Genellina" wrote: > > But you already have "multiline" lambdas right now in that sense, no > > need to add anything. I think you were talking about lambdas *with* > > statements inside. > > > > bin = lambda x:((x&8 and '*' or '_') + > > (x&4 and '*' or '_') + > > (x&2 and '*' or '_') + > > (x&1 and '*' or '_')) > > Or in more recent versions of Python: > > bin = lambda x:(('*' if x&8 else '_') + > ('*' if x&4 else '_') + > ('*' if x&2 else '_') + > ('*' if x&1 else '_')) > > but seriously, any example of lambda which simply assigns the function to a > variable is flawed. > > I can sort of understand the people who object to a named function taking > the logic 'out of line', but any expression which actually requires a > multi-statement function to be embedded in the middle of it is already in > danger of causing my brain to implode. You're correct, my lambda function handles statements as well as multiple expressions. That code, however, is bloody hideous. If that's what I had to do to do multiline callbacks I'd always use def. Ew. From deets at nospam.web.de Tue Jun 26 10:46:03 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 26 Jun 2007 16:46:03 +0200 Subject: Installing python under the linux References: <1182800785.231113.199750@n2g2000hse.googlegroups.com> <1182802267.969628.156960@o61g2000hsh.googlegroups.com> <1182845417.526433.59690@c77g2000hse.googlegroups.com> <4680F3DB.6040901@web.de> <1182867273.230244.151900@w5g2000hsg.googlegroups.com> Message-ID: <5ecn5bF38f35hU1@mid.uni-berlin.de> vedrandekovic at v-programs.com wrote: > Hello, > >>No. The only way to change the keywords would be to edit the >>Python source and re-compile it. > > This was very helpful information , I already know that but I don't > know how > to that.PLEASE HELP ME ABOUT THIS, I WILL BE VERY GRATEFUL TO YOU. > > ( IF you can please step by step how to I install that source ) Stop shouting. Start reading this: http://www.catb.org/~esr/faqs/smart-questions.html And for god's sake, follow the suggestions you got when asking the same question over and over: Stop trying to do what you want to do - altering python. That is _NOT_ the way to go. Especially not if someone is obviously not skilled enough to really dig into the guts of the interpreter. Instead, tell us what you really want. Write a preprocessor to alter your user's code to become python code. Diez From flebber.crue at gmail.com Sun Jun 10 01:06:44 2007 From: flebber.crue at gmail.com (flebber) Date: Sun, 10 Jun 2007 05:06:44 -0000 Subject: read xml file from compressed file using gzip In-Reply-To: <466AE729.8070602@web.de> References: <1181278784.312152.99910@r19g2000prf.googlegroups.com> <466AE729.8070602@web.de> Message-ID: <1181452004.347078.241840@q19g2000prn.googlegroups.com> On Jun 10, 3:45 am, Stefan Behnel wrote: > flebber wrote: > > I was working at creating a simple program that would read the content > > of a playlist file( in this case *.k3b") and write it out . the > > compressed "*.k3b" file has two file and the one I was trying to read > > was maindata.xml > > The k3b format is a ZIP archive. Use the zipfile library: > > file:///usr/share/doc/python2.5-doc/html/lib/module-zipfile.html > > Stefan Thanks for all the help, have been using the docs at python.org and the magnus t Hetland book. Is there any docs tha re a little more practical or expressive as most of the module documentation is very confusing for a beginner and doesn't provide much in the way of examples on how to use the modules. Not criticizing the docs as they are probably very good for experienced programmers. From evan at yelp.com Fri Jun 22 14:46:56 2007 From: evan at yelp.com (Evan Klitzke) Date: Fri, 22 Jun 2007 11:46:56 -0700 Subject: Tailing a log file? In-Reply-To: References: Message-ID: On 6/22/07, Evan Klitzke wrote: > Everyone, > > I'm interested in writing a python program that reads from a log file > and then executes actions based on the lines. I effectively want to > write a loop that does something like this: > > while True: > log_line = log_file.readline() > do_something(log_line) > > Where the readline() method blocks until a new line appears in the > file, unlike the standard readline() method which returns an empty > string on EOF. Does anyone have any suggestions on how to do this? > Thanks in advance! I checked the source code for tail and they actually poll the file by using fstat and sleep to check for changes in the file size. This didn't seem right so I thought about it more and realized I ought to be using inotify. So I guess I answered my own question. -- Evan Klitzke From andre.roberge at gmail.com Mon Jun 25 12:37:35 2007 From: andre.roberge at gmail.com (=?iso-8859-1?B?QW5kcuk=?=) Date: Mon, 25 Jun 2007 16:37:35 -0000 Subject: listing all property variables of a class instance Message-ID: <1182789455.818944.227660@g37g2000prf.googlegroups.com> Suppose I define a class with a number of variables defined as properties. Something like: class MyClass(object): def __init__(self): self.some_variable = 42 self._a = None self._b = "pi" def get_a(self): return self._a def set_a(self, value): self._a = value def get_b(self): return self._b def set_b(self, value): self._b = value a = property(get_a, set_a, None, "a is a property") b = property(get_b, set_b, None, "b is a property") Is there a way to write a method that would list automatically all the variables defined as a property (say by printing their docstring and/ or their value), and only those variables? Andr? From deets at nospam.web.de Tue Jun 19 09:46:16 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 19 Jun 2007 15:46:16 +0200 Subject: static python classes ? References: <1182254405.901790.189190@p77g2000hsh.googlegroups.com> Message-ID: <5dq518F35ubh4U1@mid.uni-berlin.de> Tom Gur wrote: > Hi, > > I'm new to python, and I can't seem to find in the docs how to create > the python equivalent of what's called in most OOP languages "static > classes", can you give me a hint ? With other OOP languages you mean Java. Which does have static methods because they lack the notion of a function by its own, so the shoehorned them into their "everything is inside a class"-paradigm. Forget about that. As well as getters and setters, interfaces and the like. Just use a module-level function. diez From micahel at gmail.com Fri Jun 22 05:07:55 2007 From: micahel at gmail.com (Michael Hudson) Date: Fri, 22 Jun 2007 10:07:55 +0100 Subject: Vilnius/Post EuroPython PyPy Sprint 12-14th of July Message-ID: The PyPy team is sprinting at EuroPython again and we invite you to participate in our 3 day long sprint at the conference hotel - Reval Hotel Lietuva. If you plan to attend the sprint we recommend you to listen to the PyPy technical talks (`EuroPython schedule`_) during the conference since it will give you a good overview of the status of development. On the morning of the first sprint day (12th) we will also have a tutorial session for those new to PyPy development. As 3 days is relatively short for a PyPy sprint we suggest to travel back home on the 15th if possible (but it is ok to attend less than 3 days too). ------------------------------ Goals and topics of the sprint ------------------------------ There are many possible and interesting sprint topics to work on - here we list some possible task areas: * completing the missing python 2.5 features and support * write or port more extension modules (e.g. zlib is missing) * identify slow areas of PyPy through benchmarking and work on improvements, possibly moving app-level parts of the Python interpreter to interp-level if useful. * there are some parts of PyPy in need of refactoring, we may spend some time on those, for example: - rctypes and the extension compiler need some rethinking - support for LLVM 2.0 for the llvm backend - ... * some JIT improvement work * port the stackless transform to ootypesystem * other interesting stuff that you would like to work on ...;-) ------------ Registration ------------ If you'd like to come, please subscribe to the `pypy-sprint mailing list`_ and drop a note about your interests and post any questions. More organisational information will be sent to that list. Please register by adding yourself on the following list (via svn): http://codespeak.net/svn/pypy/extradoc/sprintinfo/post-ep2007/people.txt or on the pypy-sprint mailing list if you do not yet have check-in rights: http://codespeak.net/mailman/listinfo/pypy-sprint --------------------------------------- Preparation (if you feel it is needed): --------------------------------------- * read the `getting-started`_ pages on http://codespeak.net/pypy * for inspiration, overview and technical status you are welcome to read `the technical reports available and other relevant documentation`_ * please direct any technical and/or development oriented questions to pypy-dev at codespeak.net and any sprint organizing/logistical questions to pypy-sprint at codespeak.net * if you need information about the conference, potential hotels, directions etc we recommend to look at http://www.europython.org. We are looking forward to meet you at the Vilnius Post EuroPython PyPy sprint! The PyPy team .. See also .. .. _getting-started: http://codespeak.net/pypy/dist/pypy/doc/getting-started.html .. _`pypy-sprint mailing list`: http://codespeak.net/mailman/listinfo/pypy-sprint .. _`the technical reports available and other relevant documentation`: http://codespeak.net/pypy/dist/pypy/doc/index.html .. _`EuroPython schedule`: http://europython.org/timetable From pacovegavilla at yahoo.com.mx Mon Jun 18 10:29:16 2007 From: pacovegavilla at yahoo.com.mx (pacovegavilla at yahoo.com.mx) Date: Mon, 18 Jun 2007 07:29:16 -0700 Subject: Discover As Beginning Successful Business In Internet. Message-ID: <1182176956.089640.178340@a26g2000pre.googlegroups.com> Discover As Beginning Successful Business In Internet. If you believed that to begin business in internet single era for experts........ This very mistaken one! Discover our system proven to begin business in Internet. Entering RIGHT NOW http://www.freedom.ws/pacovegavilla Alone to visit our place web he/she is entitled to request our confidential report valued totally FREE in more than US $100: Francisco Fermin Vega Villa Director of http://www.freedom.ws/pacovegavilla "US wins $21.699 Monthly Before 20 Months. Discover As People With Minimum Knowledge In Internet they are Creating A Great Fortune With Our Proven System Of Business." http://www.freedom.ws/pacovegavilla From cam.ac.uk at mh391.invalid Sun Jun 10 10:05:50 2007 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Sun, 10 Jun 2007 15:05:50 +0100 Subject: Pyrex problem with cdef'd attribute In-Reply-To: References: <1181325223.819835.115600@a26g2000pre.googlegroups.com> Message-ID: skip at pobox.com wrote: > I'll play around a bit > more and if I continue to confuse myself will subscribe to the pyrex mailing > list (or at least use the somewhat clunky gmane.org interface). I find that using a newsreader for gmane stuff is far more convenient. I use Thunderbird to access various infrequently-used mailing lists via NNTP and Gmane. -- Michael Hoffman From bj_666 at gmx.net Sun Jun 3 16:03:25 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Sun, 03 Jun 2007 22:03:25 +0200 Subject: c[:]() References: <1180504190.055427.173610@h2g2000hsg.googlegroups.com> <1180504773.374529.161740@q66g2000hsg.googlegroups.com> <1180878080.630213.258230@q75g2000hsh.googlegroups.com> <1180886141.096451.68060@k79g2000hse.googlegroups.com> Message-ID: In <1180886141.096451.68060 at k79g2000hse.googlegroups.com>, Stebanoid at gmail.com wrote: >>> [using `map()`] >> And has the same issue as a list comprehension if all you want is the side >> effect of the calls: a useless temporary list full of `None`\s is build. > > functoins can return a values, and you get it. I don't think that it > is bad side effect. I don't either. By definition it's not a side effect at all. Side effects are the "things that happen" besides the return values. Warren Stringer wanted to call the functions just for the side effects without interest in the return values. So building a list of return values which is immediately thrown away is a waste of time and memory. > When you write simple >>>> def a(): print "From Russia with love." >>>> a() > you have side effect too - returning "None". No, the side effect is the printing of 'From Russia with love.' IMHO there's a difference between this single `None` that can't be prevented and abusing a list comprehension or `map()` just for side effects and not for building a list with meaningful content. Ciao, Marc 'BlackJack' Rintsch From showell30 at yahoo.com Fri Jun 1 07:35:45 2007 From: showell30 at yahoo.com (Steve Howell) Date: Fri, 1 Jun 2007 04:35:45 -0700 (PDT) Subject: execute a function after each source code line ? In-Reply-To: <41c66$465ffa9d$83aef404$5115@news1.tudelft.nl> Message-ID: <718029.44296.qm@web33503.mail.mud.yahoo.com> --- stef wrote: > the language I want to simulate (JAL), > is very Pascal like, > and therefor can be easily converted into equivalent > Python code. > One more idea. If you haven't already, maybe you can post something to the PyPy community to effect of this: ''' I have a Python-like language that I translate to Python code, and I want to write another Python program in wxPython that executes the former Python program in a step-by-step fashion. ''' I'm sure there are some folks there that eventually want to tackle the same problem, and if nothing else, they might help you out with some terminology for describing your problem. ____________________________________________________________________________________ Sick sense of humor? Visit Yahoo! TV's Comedy with an Edge to see what's on, when. http://tv.yahoo.com/collections/222 From wildemar at freakmail.de Sat Jun 16 13:04:38 2007 From: wildemar at freakmail.de (Wildemar Wildenburger) Date: Sat, 16 Jun 2007 19:04:38 +0200 Subject: a_list.count(a_callable) ? In-Reply-To: <1181981527.960296.135820@i13g2000prf.googlegroups.com> References: <1181850818.567840.251090@x35g2000prf.googlegroups.com> <1181853479.914070.217270@i13g2000prf.googlegroups.com> <1181855184.511137.100870@z28g2000prd.googlegroups.com> <1181916937.648267.163070@z28g2000prd.googlegroups.com> <1181981527.960296.135820@i13g2000prf.googlegroups.com> Message-ID: <46741826.6060905@freakmail.de> Ping wrote: > On 6 16 , 2 06 , "BJ?rn Lindqvist" wrote: > >> Maybe you could extend count() analogous to how sort() works: >> > > Wow! This jumps out of my screen! I like it very much. > How to get the extension into the language? > Well, you subclass list and extend/override the method. class SmartCountingList(list): def count(self, item, func=lambda x: x): return len([item for item in self if func(item) is True]) ... or whatever (this is dummy code, not tested and probably riddled with stupid errors --- so take this as a pseudocode example) /W From gagsl-py2 at yahoo.com.ar Tue Jun 19 22:27:54 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 19 Jun 2007 23:27:54 -0300 Subject: Reference current module? References: <4678201b$0$16340$88260bb3@free.teranews.com> Message-ID: En Tue, 19 Jun 2007 16:34:50 -0300, Steven Bethard escribi?: > Tobiah wrote: >> >> getattr(current_module, 'foo') >> >> where 'current_module' is a handle the the one >> that the code is in? Just like > > You can try __import__() with __name__:: > > >>> foo = 42 > >>> mod = __import__(__name__) > >>> getattr(mod, 'foo') > 42 A simple way would be using sys.modules[__name__]. But I prefer using globals()['foo'] as it is simpler and does not assume additional requirements (like __name__ still being the same, or the module still available for importing). -- Gabriel Genellina From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Sat Jun 2 07:00:54 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Sat, 02 Jun 2007 13:00:54 +0200 Subject: Python Pop Quiz References: <1180751587.951837.191480@h2g2000hsg.googlegroups.com> Message-ID: <5cd0v6F30ajrdU1@mid.individual.net> snorble at hotmail.com wrote: > Bonus: A rabbi walks into a bar while nursing a baby goat. He is > closely followed by a priest, and a Perl hacker. Explain. Getting religious, eh? :) http://xkcd.com/c224.html Regards, Bj?rn -- BOFH excuse #14: sounds like a Windows problem, try calling Microsoft support From doug at alum.mit.edu Tue Jun 19 19:34:27 2007 From: doug at alum.mit.edu (Douglas Alan) Date: Tue, 19 Jun 2007 19:34:27 -0400 Subject: Python's "only one way to do it" philosophy isn't good? References: <1181368143.874341.273140@r19g2000prf.googlegroups.com> Message-ID: "Terry Reedy" writes: > Nonetheless, picking on and characterizing Tim's statement as > anti-flexibility and un-scientific is to me writing of a sort that I > would not tolerate from my middle-school child. Now it is you who are taking Sussman's comments out of context. Sussman does not claim that Python is "un-scientific" -- he merely holds it up as a example of canonical engineering that eschews the kinds of flexibility that is to be found in biological systems and in the practice of science. In this regard, Sussman is merely criticizing engineering "best practices" in general, not Python in specific, and is arguing that if we want to engineer systems that are as robust as biological systems then we need to start exploring radically different approaches to software design. > Python is an algorithm language and a tool used to engineering > information systems, which is something different. The next > sections are about exploratory behavior. Languages do not 'behave', > let alone 'explore'. I think you are missing the point. Sussman is making a broad criticism of software engineering in general, as it is understood today. The essay in questions was written for a graduate-level MIT computer science class that aims to explore potential avenues of research into new languages and approaches that encourage and facilitate more robust software systems. As good as Python is, it is still largely an encapsulation of the best ideas about software engineering as it was understood in the early 80's. We're now 20+ years on, and it behooves our future Computer Science researchers to consider if we might not be able to do better than we could in 1984. > So Python seems to have the sort of flexibility that he implicitly > claims it does not. Python most certainly does *not* have the type of flexibility that he is talking about. For instance, one of the things that he talks about exploring for more robust software systems is predicate dispatching, which is an extension of multiple dispatch. Although you might be able to cobble something like this together in Python, it would end up being very cumbersome to use. (E.g., Guido wrote an essay on doing multiple dispatch in Python, but you wouldn't actually want to write Python code that way, because it would be too syntactically cumbersome.) In dialects of Lisp (such as Scheme), however, subsystems to explore such alternative programming models can be written completely within the language (due, in part to their syntax extension facilities). This is how the Common Lisp Object System came to be, for instance. CLOS supports all sorts of OO stuff that even Python doesn't, and yet Lisp without CLOS isn't even an OO language. > The general problems of software inflexibility that he mentioned in > a previous section have nothing specific to do with Python. Right. And he never said they did. > When he gets to solutions, one long section (page 13) somewhat > specific to languages, versus applications thereof, is about > extensible generic operations "where it is possible to define what > is meant by addition, multiplication, etc., for new datatypes > unimagined by the language designer." Well, golly gee. Guess what? > Not only is Python code generic unless specialized (with isinstance > tests, for instance), but it is highly extensible for new datatypes, > just as Sussman advocates. There is a special method for just about > every syntactic construct and builtin function. And 3.0 may add a > new generic function module to dispatch on multiple arguments and > possibly predicates. You didn't read the paper very carefully. Sussman points out that traditional OO languages are up to this sort of stuff to some extent, but not to the extent which he thinks is required to solve future challenges. He things, for instance, that predicate dispatching, backtracking, and first-class continuations will be required. |>oug From abhishekrane at gmail.com Tue Jun 5 10:29:46 2007 From: abhishekrane at gmail.com (abhiee) Date: Tue, 05 Jun 2007 14:29:46 -0000 Subject: Beginning Python Message-ID: <1181053786.724436.132900@n15g2000prd.googlegroups.com> Hello , I have just begun learning python...and I'm loving it...Just wanted to ask you that how much time would it take me to learn python completely and which languages should i learn alongwith python to be a good professional programmer?...Now i only know C.... thanx in advance! From showell30 at yahoo.com Sat Jun 2 11:29:59 2007 From: showell30 at yahoo.com (Steve Howell) Date: Sat, 2 Jun 2007 08:29:59 -0700 (PDT) Subject: subexpressions (OT: math) In-Reply-To: Message-ID: <493645.97553.qm@web33513.mail.mud.yahoo.com> --- Steven D'Aprano wrote: > On Sat, 02 Jun 2007 05:54:51 -0700, Steve Howell > wrote: > > >> > >> def f(x): y = x*x; return sin(y)+cos(y); > >> > > > > Although I know valid trigonometry is not the > point of > > this exercise, I'm still trying to figure out why > > anybody would ever take the square of an angle. > > What's the square root of pi/4 radians? > > Approximately 0.886 radians. It corresponds to the > angle of a point on the > unit circle quite close to (sqrt(2/5), sqrt(3/5)), > or if you prefer > decimal approximations, (0.632, 0.775). > > Angles are real numbers (in the maths sense), so > sqrt(pi/4) radians is > just as reasonable an angle as pi/4 radians. Both > are irrational numbers > (that is, can't be written exactly as the ratio of > two integers). > Yes, I understand that, but what is the geometrical meaning of the square root of an arc length? And what would the units be? If you take the square root of an area, the units change from acres to feet, or from square meters to meters. ____________________________________________________________________________________ Got a little couch potato? Check out fun summer activities for kids. http://search.yahoo.com/search?fr=oni_on_mail&p=summer+activities+for+kids&cs=bz From adelagon at gmail.com Tue Jun 19 04:05:07 2007 From: adelagon at gmail.com (Alvin Delagon) Date: Tue, 19 Jun 2007 16:05:07 +0800 Subject: sizeof() in python Message-ID: <7a01f6c00706190105g934276w1adcac048b295688@mail.gmail.com> Thanks for the reply, yes you're right I just realized it sooner. -------------- next part -------------- An HTML attachment was scrubbed... URL: From Stebanoid at gmail.com Sun Jun 3 12:42:26 2007 From: Stebanoid at gmail.com (Stebanoid at gmail.com) Date: Sun, 03 Jun 2007 09:42:26 -0700 Subject: getting rid of leading zeros in float expotential In-Reply-To: References: Message-ID: <1180888946.125397.287380@n4g2000hsb.googlegroups.com> On 3 , 11:47, t... at finland.com wrote: > Hi! I'm wondering whether there's an easy way to remove unnecessary > leading zeros from my floating point number. > > realS = float(-1.25e-5) > imgS = float(-7.6e4) > > print complex(realS, imgS) > > >> (-1.25e-005-76000j) > > I would like it to look like (-1.25e-5-76000j) why? For printing? try to process it as a string >>>def my_func(a): return my_del_zeros_func(str(a)) From apatheticagnostic at gmail.com Thu Jun 21 01:00:36 2007 From: apatheticagnostic at gmail.com (kaens) Date: Thu, 21 Jun 2007 01:00:36 -0400 Subject: PEP 3107 and stronger typing (note: probably a newbie question) In-Reply-To: <5dtmtnF36t3pfU1@mid.uni-berlin.de> References: <1182369568.941307.316260@p77g2000hsh.googlegroups.com> <5dtmtnF36t3pfU1@mid.uni-berlin.de> Message-ID: <163f0ce20706202200y761bda4fpec35498f1d84f179@mail.gmail.com> On 6/20/07, Diez B. Roggisch wrote: > That is exactly the problem - there is no "some more" static typing. > There is static typing - or not. You can't have it "just a bit". Couldn't a language be made so that if you declared a variable like, say: string foo = "I'm a string" it would be a string, and always a string, and if you declared a variable like foo = "i'm a dynamic variable" it would be considered dynamic? This doesn't seem like it would be too hard to add in to a language that already had dynamic typing (But then again, I am inexperienced - although interested in - language design). It seems to me like this could be really useful, but I'm not aware of any language implementing something like this. From m_tayseer82 at yahoo.com Sun Jun 3 11:59:51 2007 From: m_tayseer82 at yahoo.com (Mohammad Tayseer) Date: Sun, 3 Jun 2007 08:59:51 -0700 (PDT) Subject: Why Python? In-Reply-To: <20d6f8950706030807u4c37ffb9xfa063edcc26d056f@mail.gmail.com> Message-ID: <845345.35122.qm@web31111.mail.mud.yahoo.com> Why you should use Python http://spellcoder.com/blogs/tayseer/archive/2007/04/08/why_you_should_use_python.aspx Chris Stewart wrote: What is it about Python that makes it such a suitable language for you? For instance, why would you use it over something similarly portable as Java, or PHP? I know personally, in my small exposure to Python, I can see it as a great learning tool for a basic introduction to programming and even OOP. It's wonderful how your .py file can simply start making expressions without any overhead, import/using statements, class declarations, etc. -- Chris Stewart compiledmonkey at gmail.com http://www.compiledmonkey.com -- http://mail.python.org/mailman/listinfo/python-list Mohammad Tayseer http://spellcoder.com/blogs/tayseer --------------------------------- Park yourself in front of a world of choices in alternative vehicles. Visit the Yahoo! Auto Green Center. -------------- next part -------------- An HTML attachment was scrubbed... URL: From vinay_sajip at yahoo.co.uk Tue Jun 26 12:32:12 2007 From: vinay_sajip at yahoo.co.uk (Vinay Sajip) Date: Tue, 26 Jun 2007 09:32:12 -0700 Subject: logging anomaly In-Reply-To: <1182869316.358944.133430@n2g2000hse.googlegroups.com> References: <1182869316.358944.133430@n2g2000hse.googlegroups.com> Message-ID: <1182875532.669958.266180@w5g2000hsg.googlegroups.com> On Jun 26, 3:48 pm, Jesse James wrote: > > 2007-06-26 07:59:38,192 vor.uploader INFO ----- start uploading file: > 7_Canyons_Clip_1.flv > 2007-06-26 07:59:38,206 vor.uploader INFO ----- done uploading file: > 7_Canyons_Clip_1.flv > > I know this is wrong because this is a large file that took almost a > minute to upload. > > Seems like, with my experience with log4j, upon which I believe the > pythonloggingmodule was modeled, this should just work as expected. > > What am I missing here? Not sure...it depends on your logging configuration. Ordinarily, the event would be processed straight away...delays in seeing output could be because of e.g. unflushed I/O buffers or buffering via MemoryHandler (however, this would not affect the time printed for the event, which is determined at the time the event is logged). Does this same behaviour occur if the message is logged to a console handler? (StreamHandler with sys.stderr as the stream, which is not redirected to a file). Regards, Vinay Sajip From Stebanoid at gmail.com Thu Jun 7 13:30:09 2007 From: Stebanoid at gmail.com (Stebanoid) Date: Thu, 07 Jun 2007 10:30:09 -0700 Subject: running a random function In-Reply-To: <1654405.LVbK4P6cM3@teancum> References: <1654405.LVbK4P6cM3@teancum> Message-ID: <1181237409.757551.243620@p47g2000hsd.googlegroups.com> On 7 , 19:56, David Bear wrote: > I would like to write some code that would randomly select a function from a > list of functions and call it. I was looking in the globals names space and > randomly selecting items that were of type function.. but I didn't see a > way of actually running the function. > > Any pointers? > > -- > David Bear > -- let me buy your intellectual property, I want to own your thoughts -- if you have a list of functions you can try this: import random import math m[int(math.ceil(random.random()))]() #seems like Lisp code :) but what about functions arguments? Strange task... Very strange.... From Graham.Dumpleton at gmail.com Mon Jun 25 20:38:57 2007 From: Graham.Dumpleton at gmail.com (Graham Dumpleton) Date: Tue, 26 Jun 2007 00:38:57 -0000 Subject: server wide variables In-Reply-To: <1182817788.562497.44430@z28g2000prd.googlegroups.com> References: <1182785365.877473.298170@q75g2000hsh.googlegroups.com> <1182817788.562497.44430@z28g2000prd.googlegroups.com> Message-ID: <1182818337.081578.55550@z28g2000prd.googlegroups.com> On Jun 26, 10:29 am, Graham Dumpleton wrote: > On Jun 26, 1:29 am, Jay Sonmez wrote: > > > I want to be able to save some server variables as long as Apache runs > > on the server (mod_python). > > > How is that possible in Python? > > It depends on whether you expect all Apache child processes for that > server to be able to access the data and for the data to be able to > survive the killing off and start up of individual Apache child > processes. > > For background on some of the issues read: > > http://www.dscpl.com.au/wiki/ModPython/Articles/TheProcessInterpreter... > > Saving data in os.environ is not recommended even if they have to > survive just within the context of that specific interpreter within > that process, as os.environ access and update is not thread protected > and Apache child processes may be multithreaded. Before someone decides to shoot me down, yes I know that dictionaries themselves are thread safe and thus os.environ itself is thread safe. In making that comment I am looking more at the higher level locking aspects of a combined set of data, ie., the same as you might have for global data in a module and what is required to protect that in the presence of multiple threads. The os.environ dictionary being what it is, people may not appreciate the need that locking may still be required if one is going to use it as a means of holding data that can change over time. In short, os.environ simply shouldn't be used for that anyway. Graham From hat at se-126.se.wtb.tue.nl Fri Jun 1 06:42:30 2007 From: hat at se-126.se.wtb.tue.nl (A.T.Hofkamp) Date: Fri, 01 Jun 2007 12:42:30 +0200 Subject: generating a tree-like structure References: <1180638948.157965.210260@q66g2000hsg.googlegroups.com> Message-ID: On 2007-05-31, Thorsten Kampe wrote: > * (31 May 2007 12:15:48 -0700) >> On May 31, 12:44 pm, Thorsten Kampe wrote: >> > This is a fairly general question: is there some kind of module or >> > framework that allows building a tree like structure from certain kind >> > of data? >> > >> > To be specific: I have a program that dumps the content of a LDAP >> > directory including all properties and values and groups the result >> > from the LDAP search by objClass. >> > >> > Now I was thinking: would it be possible to generate from the totally >> > unordered output that the LDAP server gives me, a tree like >> > representation that displays the hierarchy (omitting the values or >> > even properties if necessary)? >> > >> > It should be a textual representation of what you see in GUI programs >> > like "LDAP Administrator" but the output should be represented like >> > the "tree" program in Linux or Windows "tree.com". >> >> I think you might be able to use ElementTree. The website for the >> module claims it can be used for hierarchical data structures: >> http://effbot.org/zone/element-index.htm >> >> Did you look at any of the Python LDAP tools? They might be useful >> too. See some of the links below: >> http://linuxjournal.com/article/6988 >> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/303336 >> >> Hopefully they'll give some guidance. I've not used LDAP myself as of >> yet. > > I already have the LDAP output part working - with python-ldap under > Cygwin - and I generate HMTL output with markup.py. Pretty simple. But > a tree structure output would be even prettier... I would probably generate a DOT file to get a 2D visualization. DOT is part of Graphviz (graphviz.org), and there are quite a few graphviz front-ends available in Python to make DOT generation easier (pydot, yapgvb, and probably a few others). Albert From user at superhoost.com Sat Jun 16 22:48:32 2007 From: user at superhoost.com (ed) Date: Sat, 16 Jun 2007 22:48:32 -0400 Subject: Newbie question: how to get started? Message-ID: <2007061622483250073-user@superhoostcom> Hi, I'm interested in starting to learn python. I'm looking for any reccomendations or advice that I can use to get started. Looking forward to any help you can give! Thanks! -e From mpeters42 at gmail.com Sat Jun 2 14:43:08 2007 From: mpeters42 at gmail.com (Mark Peters) Date: Sat, 02 Jun 2007 18:43:08 -0000 Subject: Error message if there is a space in the source directory In-Reply-To: <1180807933.269404.208750@m36g2000hse.googlegroups.com> References: <1180807933.269404.208750@m36g2000hse.googlegroups.com> Message-ID: <1180809788.996217.46790@w5g2000hsg.googlegroups.com> > When using a source like this on line 5: > > source = [r'C:\test\test 2\\'] > > which has a space in the title, the program will not work. Try wrapping that argument in double quotes when you build the command From prashantkisanpatil at gmail.com Thu Jun 7 08:12:16 2007 From: prashantkisanpatil at gmail.com (prashantkisanpatil at gmail.com) Date: Thu, 07 Jun 2007 05:12:16 -0700 Subject: How to wrap a Japanese text in Python Message-ID: <1181218336.318399.59910@w5g2000hsg.googlegroups.com> Hi All, I am trying to wrap a japanese text in Python, by the following code. if len(message) > 54: message = message.decode("UTF8") strlist = textwrap.wrap(message,54) After this I am wirting it to you a CAD Software window. While displaying in this window some Japanese characters at the end of the line & some at the begining of the line are not displayed at all. Meaning the text wrapping is not happening correctly. Can any body please help me out in resolving this problem. Thanks in advance. Regards, Prashant From roy at panix.com Wed Jun 27 09:03:33 2007 From: roy at panix.com (Roy Smith) Date: Wed, 27 Jun 2007 09:03:33 -0400 Subject: Too many 'self' in python.That's a big flaw in this language. References: <1182942154.185461.89620@e9g2000prf.googlegroups.com> Message-ID: Marc 'BlackJack' Rintsch wrote: > Use a shorter name than `self` or an editor with auto completion. Of the two, I'd strongly vote for the auto completion (assuming you feel the need to "solve" this problem at all). The name "self" is so ingrained in most Python programmers minds, that it's almost a keyword. Changing it to "this" or "s" or "me" will just make your program a little harder for other people to understand. Changing it to "this" would be particularly perverse since it's not even any less typing. In fact, on a standard keyboard, it's harder to type since it involves moving off the home row more :-) From duncan.booth at invalid.invalid Fri Jun 1 16:13:50 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 1 Jun 2007 20:13:50 GMT Subject: Detecting an active exception References: Message-ID: "NeBlackCat (lists)" wrote: > Depending on what you read, sys.exc_info() is supposed to return > (None,None,None) when there is no active exception, but it seems that > it returns info about the last exception when there isn't one > currently active. > > For example: > > try: > a = a + 1 > except: > pass > > print sys.exc_info() > > produces: >, instance at 0x00B5E508>, > > Where the traceback object identifies the offending a=a+1 line (of > course). > > Is there another way of doing this? Note that I can't rely on using > sys.exc_clear() in any solution, unfortunately. I think you have misunderstood the definition of when an exception is 'currently active'. When an exception is caught, it remains currently active so long as you are in the same function, or in a function which it calls (i.e. so long as the current scope is still active). When you return from that function the exception is no longer active and the previous exception becomes active (or None if there has not been one or you have used sys.exc_clear()). Try this: --------- t.py ------------- import sys def f(): try: a = a + 1 except: pass g() print "f", sys.exc_info() def g(): print "g", sys.exc_info() def h(): f() print "h", sys.exc_info() h() ---------------------------- The output is: g (, UnboundLocalError("local variable 'a' referenced before assignment",), ) f (, UnboundLocalError("local variable 'a' referenced before assignment",), ) h (None, None, None) As you can see the exception remains 'currently active' only until the function in which it was caught returns. From goon12 at gmail.com Tue Jun 5 08:15:22 2007 From: goon12 at gmail.com (Joe Riopel) Date: Tue, 5 Jun 2007 08:15:22 -0400 Subject: Embedding Python in C In-Reply-To: <1181027545.180197.162650@m36g2000hse.googlegroups.com> References: <1180969118.795850.15160@w5g2000hsg.googlegroups.com> <1181025679.979188.52960@h2g2000hsg.googlegroups.com> <1181027545.180197.162650@m36g2000hse.googlegroups.com> Message-ID: <6a2ccd190706050515y39f3b826v8b8541830bd5c0c3@mail.gmail.com> This seems like a pretty good resource, although I didn't read it all yet: http://www.ibm.com/developerworks/edu/l-dw-linux-pythonscript-i.html From richardjones at optushome.com.au Fri Jun 15 23:57:18 2007 From: richardjones at optushome.com.au (Richard Jones) Date: Sat, 16 Jun 2007 13:57:18 +1000 Subject: Open Source Developers' Conference 2007 - Brisbane - Call for Papers Message-ID: <200706161357.18654.richardjones@optushome.com.au> Call for Papers Open Source Developers' Conference 2007 - Brisbane Australia "Success in Development & Business" OSDC is an Australian grass-roots conference providing Open Source developers with an opportunity to meet, share, learn, and of course show-off. OSDC focuses on Open Source developers building solutions directly for customers and other end users, anything goes as long as the code or the development platform is Open Source. Last year's conference attracted over 180 people, 60 talks, and 6 tutorials. Entry for delegates is kept easy by maintaining a low registration fee (approx $300), which always includes the conference dinner. This year OSDC will be held in Brisbane (Australia) from the 26th to the 29th of November, with an extra dedicated stream for presentations on Open Source business development, case studies, software process, and project management. The theme for this year's conference is "Success in Development & Business". If you are an Open Source maintainer, developer or user we would encourage you to submit a talk proposal on the open-source tools, solutions, technologies, or languages you are working with. Previous years have included numerous talks on topics such as: - FOSS Software Development Tools, Software Process and Project Management - Languages/Platforms: C/C++, Java, C#/Mono/OSS.Net - Scripting: Perl, PHP, Python, Ruby - Databases - Education - Web Technologies - Emerging Technologies and Innovation For more details and to submit your proposal(s), see http://osdc.com.au/papers/cfp.html If you have any questions or require assistance with your submission, please don't hesitate to ask! We recognise the increasing importance of Open Source in providing a medium for collaboration between individuals, researchers, business and government. In recognition of this, we offer optional peer- review for those members of our community who desire it. We are still finalising our review board, in addition to which those requesting peer-review will be asked to contribute reviews for up to three papers. OSDC 2007 Brisbane (Australia) - Key Program Dates: 30 Jun - Initial proposals (short abstract) due 31 Jul - Proposal acceptance 31 Aug - Submission deadline 15 Sep - Peer-review response (optional) 30 Sep - Final version for proceedings 26 Nov - OSDC 2007 Tutorials 27-29 Nov - OSDC 2007 Main Conference! For all information, contacts and updates, see the OSDC conference web site at http://osdc.com.au/ We gratefully acknowledge the following companies for their early commitment in sponsoring OSDC 2007: - Apress (http://apress.com/) - Common Ground (http://commongroundgroup.com/) - Google (http://google.com.au/) - OpenGear (http://opengear.com.au/) Interested in sponsoring also? See http://www.osdc.com.au/sponsors/opportunities.html From george.sakkis at gmail.com Tue Jun 12 10:54:40 2007 From: george.sakkis at gmail.com (George Sakkis) Date: Tue, 12 Jun 2007 14:54:40 -0000 Subject: Multiline lamba implementation in python. In-Reply-To: <1181657523.655499.161880@g37g2000prf.googlegroups.com> References: <1b0ce1b60706112002i761dc295x9ba9c4f589c41db1@mail.gmail.com> <1181657523.655499.161880@g37g2000prf.googlegroups.com> Message-ID: <1181660080.153532.320600@d30g2000prg.googlegroups.com> On Jun 12, 10:12 am, Kay Schluehr wrote: > On 12 Jun., 14:57, Facundo Batista wrote: > > > Remember that the *only* difference between the two functions is that > > one is anonymous, and for other you have to came up with a name (name > > that if is well thought, actually adds readibility to your code). > > The difference is that one can be inlined since it is an expression > and the other has to be a statement and a reusable ( named ) > abstraction even when you don't need one. I have a very hard time to > defend this as a good design decision even when it is just a minor > pain point in almost all my practical purposes. I think of it more as a "necessary evil" rather than a conscious design choice. IIRC the "official" justification is that nobody came up with an acceptable syntax for multiline lambdas; TOOWTDI is a secondary reason (as one can easily come up with a dozen TOOWTDI violations in other parts of the language). I agree though that in practice it's a very small limitation. George From gherron at islandtraining.com Sun Jun 3 13:43:36 2007 From: gherron at islandtraining.com (Gary Herron) Date: Sun, 03 Jun 2007 10:43:36 -0700 Subject: subexpressions (OT: math) In-Reply-To: <1180890214.317409.85100@w5g2000hsg.googlegroups.com> References: <4662675b$1_5@news.bluewin.ch> <1180890214.317409.85100@w5g2000hsg.googlegroups.com> Message-ID: <4662FDC8.9080407@islandtraining.com> Stebanoid at gmail.com wrote: > On 3 , 14:05, Steven D'Aprano > wrote: > >> On Sun, 03 Jun 2007 09:02:11 +0200, Leonhard Vogt wrote: >> >>>> bla-bla >>>> >> Hmmm... perhaps that's why the author of the "units" program doesn't >> treat angles as dimensionless when taking square roots. >> >> Given that, I withdraw my claim that the sqrt of an angle is just an >> angle. I can't quite see why it shouldn't be, but the evidence is fairly >> solid that it isn't. >> >> -- >> Steven >> > > angle is dimensionless unit. > Of course not! Angles have units, commonly either degrees or radians. However, sines and cosines, being ratios of two lengths, are unit-less. > To understand it: sin() can't have dimensioned argument. It is can't > to be - sin(meters) > No it's sin(radians) or sin(degrees). > it is difficult to invent what is a "sqrt from a angle" but it can be. > I don't know of any name for the units of "sqrt of angle", but that doesn't invalidate the claim that the value *is* a dimensioned quantity. In lieu of a name, we'd have to label such a quantity as "sqrt of degrees" or "sqrt of radians". After all, we do the same thing for measures of area. We have some units of area like "acre", but usually we label areas with units like "meters squared" or "square meters". That's really no stranger than labeling a quantity as "sqrt of degrees". Gary Herron, PhD. Department of Computer Science DigiPen Institute of Technology From NevilleD.python at sgr-a.net Tue Jun 19 22:45:47 2007 From: NevilleD.python at sgr-a.net (Neville D) Date: Wed, 20 Jun 2007 14:45:47 +1200 Subject: Q: listsort and dictsort - official equivalents? In-Reply-To: <740c3aec0706191757i43204155o89f4b37ed0bc68eb@mail.gmail.com> References: <1182302544.4202.40.camel@delta.sgr-a.net> <740c3aec0706191757i43204155o89f4b37ed0bc68eb@mail.gmail.com> Message-ID: <1182307547.4202.57.camel@delta.sgr-a.net> Choice answer. It exactly hit the mark. I implemented "sorted" as follows: #!/usr/bin/env python d=dict(zip("cba",(2,1,3))) for k in sorted(d,key=lambda k: d[k]): print k,d[k] Output: b 1 c 2 a 3 I am glad I asked. Now I know. Than? NevilleDNZ On Wed, 2007-06-20 at 02:57 +0200, BJ?rn Lindqvist wrote: > You can even sort by the gid: > > for group in sorted(open("/etc/group"), key = lambda x: int(x.split(':')[2])): > print group, -- Neville D - NZ ??????????????????????????????????????????????? note: This document contains Anglo-Saxon Futhorci UTF-8 characters from: http://junicode.sourceforge.net/ - eg ?? ????? ??? From thomas at jollans.com Fri Jun 29 16:50:32 2007 From: thomas at jollans.com (Thomas Jollans) Date: Fri, 29 Jun 2007 22:50:32 +0200 Subject: HTML Render Support in PyGTK In-Reply-To: <1ef9860e0706291305x4c1de081p508d1edba9a8f981@mail.gmail.com> References: <1ef9860e0706291305x4c1de081p508d1edba9a8f981@mail.gmail.com> Message-ID: <200706292250.32997.thomas@jollans.com> There was no need to re-ask so soon. On Friday 29 June 2007, senthil arasu wrote: > Hi, > I am trying to render HTML in PyGTK widget but iam not getting the expected ^^^^^^ What have you tried so far ? > result. > I would like to know whether PyGTK supports HTML rendering feature or not. I believe GTK+2 has an HTML renderer, I don't know whether it's included in PyGTK by default etc. -- Regards, Thomas Jollans GPG key: 0xF421434B may be found on various keyservers, eg pgp.mit.edu Hacker key : v4sw6+8Yhw4/5ln3pr5Ock2ma2u7Lw2Nl7Di2e2t3/4TMb6HOPTen5/6g5OPa1XsMr9p-7/-6 -------------- 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 kyosohma at gmail.com Mon Jun 11 13:37:49 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Mon, 11 Jun 2007 10:37:49 -0700 Subject: Accessing global namespace from module In-Reply-To: <1181577768.728377.262720@m36g2000hse.googlegroups.com> References: <1181577768.728377.262720@m36g2000hse.googlegroups.com> Message-ID: <1181583469.562064.29440@p77g2000hsh.googlegroups.com> On Jun 11, 11:02 am, reubendb wrote: > Hello, > I am new to Python. I have the following question / problem. > I have a visualization software with command-line interface (CLI), > which essentially is a Python (v. 2.5) interpreter with functions > added to the global namespace. I would like to keep my own functions > in a separate module and then import that module to the main script > (that will be executed using the CLI interpreter). The problem is, I > cannot access the functions in the global namespace of the main script > from my module. Is there anyway to do that ? > > Here is an example of what I meant. The function AddPlot() and > DrawPlots() are added to the global namespace by the software CLI. If > I do this: > > mainscript.py: > --------------------------- > AddPlot("scatter", "coordinate") > # set other things here > DrawPlots() > > it works fine. But I want to be able to do this: > > myModule.py: > ---------------------- > def defaultScatterPlot(): > AddPlot("scatter", "coordinate") > #do other things > DrawPlots() > > and then in mainscript.py: > --------------------------------------- > import myModule > myModule.defaultScatterPlot() > > This won't work because myModule.py doesnot have access to AddPlot(). > How do I do something like this ? > > Thank you in advance for any help. > RDB I think you're doing it backwards. If you want access to AddPlot, then you should import mainscript into that module instead of the other way around. When I have common methods I want to call from different scripts, I put those methods/functions into their own module/file. Then I just import the module and call whatever script I need. commonMods.py --------------------- AddPlot(*args, *kwargs): # Do something DrawPlots(*args, *kwargs): # Do something --------------------- mainProgram.py ------------------------ from commonMods import AddPlot AddPlot("scatter", "coordinate") # etc etc ------------------------- myModule.py ------------------------ from commonMods import AddPlot AddPlot("scatter", "coordinate") # etc etc ------------------------- Hope that helps. Mike From bjourne at gmail.com Sun Jun 10 18:13:18 2007 From: bjourne at gmail.com (=?ISO-8859-1?Q?BJ=F6rn_Lindqvist?=) Date: Mon, 11 Jun 2007 00:13:18 +0200 Subject: Select one of 2 functions with the same name ? In-Reply-To: References: Message-ID: <740c3aec0706101513h617756d4n39ce84a5acbfb90c@mail.gmail.com> On 6/10/07, Stef Mientki wrote: > I can realize it with a simple switch within each function, > but that makes the code much less readable: > > def Some_Function(): > if simulation_level == 1: > ... do things in a way > elif simulation_level == 2: > ... do things in another way > elif simulation_level == 3: > ... do things in yet another way If you only have three levels, then that definitely is the best way to solve the problem. If you have more, and if they may change, then use a dispatch-dict: def simulator_1(): print 'mooo' ... simulators = {1 : simulartor_1, 2 : simulator_2, 3 : simulator_3} def Some_Function(): simulators[simulation_level]() -- mvh Bj?rn From showell30 at yahoo.com Sat Jun 2 08:54:51 2007 From: showell30 at yahoo.com (Steve Howell) Date: Sat, 2 Jun 2007 05:54:51 -0700 (PDT) Subject: subexpressions In-Reply-To: <9120$46612665$d443bb3a$31035@news.speedlinq.nl> Message-ID: <208507.43365.qm@web33502.mail.mud.yahoo.com> > > def f(x): y = x*x; return sin(y)+cos(y); > Although I know valid trigonometry is not the point of this exercise, I'm still trying to figure out why anybody would ever take the square of an angle. What's the square root of pi/4 radians? ____________________________________________________________________________________ Looking for earth-friendly autos? Browse Top Cars by "Green Rating" at Yahoo! Autos' Green Center. http://autos.yahoo.com/green_center/ From dak at gnu.org Wed Jun 20 09:28:28 2007 From: dak at gnu.org (David Kastrup) Date: Wed, 20 Jun 2007 15:28:28 +0200 Subject: The Modernization of Emacs References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182344981.372713.298580@w5g2000hsg.googlegroups.com> Message-ID: <86y7ieoiv7.fsf@lola.quinscape.zz> Kaldrenon writes: > I'm very, very new to emacs. I used it a little this past year in > college, but I didn't try at all to delve into its features. I'm > starting that process now, and frankly, the thought of it changing - > already- upsets me. I don't feel like the program ought to change in > order to accommodate me. Actually, the "E" in "Emacs" stands for "extensible". Part of the appeal of Emacs is that you can change it to accommodate you. > I'm excited about the prospect of mastering something new and > different. The fewer resemblances to the common- denominator, > extra-friendly stuff I've worked with in the past, the better. > > Emacs' uniqueness may hurt its adoption rate, but it still has > plenty of users, who are all perfectly happy with how things are > done. Oh, but Emacs is not TeX: it _is_ being developed further. And some changes are done in order to synchronize Emacs with the "other world" where the latter has been oversleeping. For example, Emacs 23 will internally use utf-8/Unicode as its encoding when it has used emacs-mule up to now, a multibyte code of its own. In spirit, this will not change Emacs much, yet it will remove other-world friction and make Emacs more obviously the incarnation of editing descended into this world. -- David Kastrup From pelonpelon at gmail.com Mon Jun 11 21:11:12 2007 From: pelonpelon at gmail.com (pelon) Date: Tue, 12 Jun 2007 01:11:12 -0000 Subject: Feature request: New string conversion type to ignore list item In-Reply-To: <1181042863.724725.128250@p77g2000hsh.googlegroups.com> References: <1181040836.014198.223080@h2g2000hsg.googlegroups.com> <1181042863.724725.128250@p77g2000hsh.googlegroups.com> Message-ID: <1181610672.246608.191270@n15g2000prd.googlegroups.com> On Jun 5, 6:27 am, thomas.p... at gmail.com wrote: > On 5 Jun., 13:12, Peter Otten <__pete... at web.de> wrote: > > > or like this: > > > >>> "%s %.s %s" % ("first", "second", "third") > > > 'first third' > > Hey, that's great, thanks Peter! > > Tom Why not be consistent with other aspects of the language: "%s %!s %s" % ("first", "second", "third") From iansan at gmail.com Wed Jun 6 23:35:40 2007 From: iansan at gmail.com (IamIan) Date: Wed, 06 Jun 2007 20:35:40 -0700 Subject: Splitting SAX results Message-ID: <1181187340.685296.284850@i38g2000prf.googlegroups.com> Hi list, I have a very simple SAX script from which I get results like 'Title1:Description','Title2:Description'. I want to split each result on the colon, using the two resulting elements as key/value pairs in a dictionary. I've tried a couple different approaches with lists etc, but I keep getting an 'IndexError: list index out of range' when I go to split the results. Probably an easy fix but it's my first hack at SAX/XML. Thank you! from xml.sax import make_parser from xml.sax.handler import ContentHandler class reportHandler(ContentHandler): def __init__(self): self.isReport = 0 def startElement(self, name, attrs): if name == 'title': self.isReport = 1 self.reportText = '' def characters(self, ch): if self.isReport: self.reportText += ch def endElement(self, name): if name == 'title': self.isReport = 0 print self.reportText parser = make_parser() parser.setContentHandler(reportHandler()) parser.parse('http://www.some.com/rss/') From bbxx789_05ss at yahoo.com Tue Jun 26 03:41:25 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: Tue, 26 Jun 2007 00:41:25 -0700 Subject: can't start Apache on Mac OS X--no listening sockets available? In-Reply-To: <1182843294.719751.225690@o61g2000hsh.googlegroups.com> References: <1182824632.015853.317970@g4g2000hsf.googlegroups.com> <1182826067.067254.247940@j4g2000prf.googlegroups.com> <1182838193.195172.206160@u2g2000hsc.googlegroups.com> <1182840123.203387.173210@q75g2000hsh.googlegroups.com> <1182841462.240341.321340@q69g2000hsb.googlegroups.com> <1182843294.719751.225690@o61g2000hsh.googlegroups.com> Message-ID: <1182843685.283663.12510@c77g2000hse.googlegroups.com> On Jun 26, 1:34 am, 7stud wrote: > Where is that coming from? Is the original index.html page(before I > changed it and added "Apache 2.2.4") cached by Safari somehow? That > doesn't make any sense to me because when I explicitly request > index.html, I get the changed output. I looked around in Safari for a bit, and I found Empty Cache under the Safari menu item. So I emptied the cache and now when I use the address http://localhost, I get the changed index.html page. So Safari was caching the original page. I guess Safari associate the address http://localhost with the original index.html page, and Safari would not display the updated index.html page when I used that address again. From nick at craig-wood.com Wed Jun 6 01:33:30 2007 From: nick at craig-wood.com (Nick Craig-Wood) Date: Wed, 06 Jun 2007 00:33:30 -0500 Subject: subprocess leaves child living References: <1181052375.551083.117390@p47g2000hsd.googlegroups.com> Message-ID: Thomas Dybdahl Ahle wrote: > But you can't ever catch sigkill. > Isn't there a way to make sure the os kills the childprocess when the > parrent dies? Not as far as I know. If you've got a pipe open to the child then killing the parent should deliver SIGPIPE to the child which may (or may not) kill it. At least it got some sort of notification. -- Nick Craig-Wood -- http://www.craig-wood.com/nick From bbxx789_05ss at yahoo.com Sun Jun 3 03:28:18 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: Sun, 03 Jun 2007 00:28:18 -0700 Subject: How to control the creation of an instance? In-Reply-To: References: <1180851453.441872.107890@k79g2000hse.googlegroups.com> <1180851949.266727.272980@q69g2000hsb.googlegroups.com> Message-ID: <1180855698.781847.5440@m36g2000hse.googlegroups.com> On Jun 3, 12:50 am, Steven D'Aprano wrote: > On Sat, 02 Jun 2007 23:25:49 -0700, 7stud wrote: > > Oops. This line: > > >> temp = object.__new__(Sample, args, kwds) > > > should be: > > > temp = object.__new__(cls, args, kwds) > > > although it would seem that cls is always going to be Sample, so I'm > > not sure what practical difference that makes. > > What if you are calling it from a sub-class? > > -- > Steven. cls it is! From gagsl-py2 at yahoo.com.ar Wed Jun 13 23:19:19 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 14 Jun 2007 00:19:19 -0300 Subject: save class References: <1181784016.454693.42340@o11g2000prd.googlegroups.com> <1181787082.712869.72770@z28g2000prd.googlegroups.com> Message-ID: En Wed, 13 Jun 2007 23:11:22 -0300, nik escribi?: > On Jun 13, 6:48 pm, "Gabriel Genellina" > wrote: >> En Wed, 13 Jun 2007 22:20:16 -0300, nik escribi?: >> >> > I would like to create a class and then save it for re-use later. I >> > have tried to usepickle, but am not sure if that is right. I am >> > sorry, but I am new to python. >> >> Do you want to save the *source*code* of your class, or do you want to >> save created *instances* -objects- of your classes to retrieve them >> later (like a database)? > It would seem that I want to actually save the source code for the > class. I know that I could of course open up an editor and just make > it, but my ideal would be to have the base class, Map, be able to make > the sub-classes. I don't want the class definition. What I want is an > actual class that I could later import and use somewhere else. I am > planning to have each one of these map objects contain a different > dictionary and then be able to import the map into the application, > but have certain methods defined in the Map super-class to draw data > out of the specific map's specific dictionary. I hope that makes > sense. > > Something like, > class Map: > dict = {} > def DoSomething(self): > pass > > def MakeNewMapSubClass(self, newclassname): > """ make a new file, newclassname.py that contains a new > class > newclassname(Map) that inherits from base-class Map. And are you sure you actually need different subclasses? Will you construct them several instances of each subclass? From the above description I feel you want just different Map *instances*, each with its own dict, not different *subclasses*. -- Gabriel Genellina From bruno.42.desthuilliers at wtf.websiteburo.oops.com Fri Jun 1 07:34:02 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Fri, 01 Jun 2007 13:34:02 +0200 Subject: subexpressions In-Reply-To: References: Message-ID: <46600409$0$24674$426a74cc@news.free.fr> Steve Holden a ?crit : (snip) > Stop thinking of three lines as "extensive coding" and your problem > disappears immediately. Lol ! +1 QOTW From alia_khouri at yahoo.com Sat Jun 9 20:15:16 2007 From: alia_khouri at yahoo.com (Alia Khouri) Date: Sat, 09 Jun 2007 17:15:16 -0700 Subject: Ableton Live Python API is out! Message-ID: <1181434516.793174.70260@g4g2000hsf.googlegroups.com> I have been waiting for this ages and it's finally happened! Python meet Live, Live meet Python! There's now a wonderful (public) bridge between (arguably) the most exciting and innovative and easy-to-use realtime software sequencer and (arguably) the most exciting and innovative and easy-to-use computer programming language out there. I know the love will flow both ways (btw, they're having problems with the mac os x port, hint, hint... ) I rushed to update http://wiki.python.org/moin/PythonInMusic but lo and behold someone beat me to it. I love it when that happens especially since I kicked off the earliest version of that page back in the day ;-) Some important links: Ableton Live is at http://www.ableton.com The forum thread announcing the api is at : http://www.ableton.com/forum/viewtopic.php?t=66118&postdays=0&postorder=asc&start=0 And last but not least the Live python SDK sits at http://www.liveapi.org/ Enjoy! Alia K From fred at adventistcare.org Fri Jun 1 11:48:04 2007 From: fred at adventistcare.org (Sells, Fred) Date: Fri, 1 Jun 2007 11:48:04 -0400 Subject: MySQLdb insert fails on one table Message-ID: I have this table mysql> describe valid_individuals; +-------+--------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +-------+--------------+------+-----+---------+-------+ | fname | varchar(30) | YES | | NULL | | | lname | varchar(30) | YES | | NULL | | | alias | varchar(30) | YES | | NULL | | | email | varchar(100) | YES | | NULL | | +-------+--------------+------+-----+---------+-------+ I call this function def insertRecords(self, tablename, columnnames, values, clear=True): cursor = self.Connection.cursor() sql = "INSERT INTO %s (%s) VALUES (%s)" % (tablename, ','.join(columnnames), ','.join(['%s' for x in columnnames])) print >>sys.stderr, sql, values[:3] cursor.executemany(sql, values) cursor.close() which prints: INSERT INTO valid_individuals (fname,lname,alias,email) VALUES (%s,%s,%s,%s) [['xxxx', 'yyyy', 'zzzzz', 'aaaaaa']] this function works fine for several other tables, but on this one I get no errors and there is nothing in the table. If I run the equivalent insert on the command line, it's just fine. I'm lost here; Python 2.4.4 and latest MySQLdb for 2.4.4; anyone got a clue? --------------------------------------------------------------------------- The information contained in this message may be privileged and / or confidential and protected from disclosure. If the reader of this message is not the intended recipient, you are hereby notified that any dissemination, distribution or copying of this communication is strictly prohibited. If you have received this communication in error, please notify the sender immediately by replying to this message and deleting the material from any computer. --------------------------------------------------------------------------- From gcmartijn at gmail.com Fri Jun 8 08:07:15 2007 From: gcmartijn at gmail.com (gcmartijn at gmail.com) Date: Fri, 08 Jun 2007 05:07:15 -0700 Subject: soap - sessions ? In-Reply-To: <1181302110.333627.112900@h2g2000hsg.googlegroups.com> References: <1181302110.333627.112900@h2g2000hsg.googlegroups.com> Message-ID: <1181304435.073193.51780@w5g2000hsg.googlegroups.com> When I use SOAPpy.Config.dumpSOAPOut = 1 SOAPpy.Config.dumpSOAPIn = 1 will display: *** Outgoing SOAP ****************************************************** <postcode href="#i7"/> <key href="#i8"/> <lastname href="#i9"/> <acc_password href="#i1"/> <address1 href="#i10"/> <company href="#i11"/> <email href="#i12"/> <acc_username href="#i1"/> <initials href="#i13"/> </createOrUpdateContact> <domaincontactid xsi:type="xsd:string" id="i1" SOAP-ENC:root="0"></ domaincontactid> <city xsi:type="xsd:string" id="i2" SOAP-ENC:root="0">fsdfsd</city> <firstname xsi:type="xsd:string" id="i3" SOAP-ENC:root="0">sdfsad</ firstname> <area xsi:type="xsd:string" id="i4" SOAP-ENC:root="0">NL</area> <phone xsi:type="xsd:string" id="i5" SOAP-ENC:root="0">+31.243770011</ phone> <title xsi:type="xsd:string" id="i6" SOAP-ENC:root="0">M 3432VD EASYNICAPI2_3057578_53854283 dfasdf dfasdf 3 safasdf info at emasdfil.com fsdfas ************************************************************************ *** Incoming SOAP ****************************************************** RESPONSECODE 999 RESPONSETEXT Your session key does not exist or has expired ************************************************************************ From stuart.tett at gmail.com Sat Jun 23 14:25:35 2007 From: stuart.tett at gmail.com (stuart.tett at gmail.com) Date: Sat, 23 Jun 2007 18:25:35 -0000 Subject: C API: passing by reference Message-ID: <1182623135.952521.174410@w5g2000hsg.googlegroups.com> I'm writing my own python extension module with the C API. In python all functions pass arguments by reference, but how can I make use of this in C? Right now, I am using: PyArg_ParseTuple(args, "(ii)(ii)", &faceId1, &vertId1, &faceId2, &vertId2) I want the to change the faceId's in my function. From what I've seen you can't do this safely with PyArg_ParseTuple. Do I have another option? Otherwise, I just have to return an extra variable. But it would be much much nicer to just have the faceId's change if the arguments passed were variables. Thanks! From arkanes at gmail.com Fri Jun 29 08:44:36 2007 From: arkanes at gmail.com (Chris Mellon) Date: Fri, 29 Jun 2007 07:44:36 -0500 Subject: Python's "only one way to do it" philosophy isn't good? In-Reply-To: References: <7xejjzmk7u.fsf@ruckus.brouhaha.com> <7xy7i7xjl5.fsf@ruckus.brouhaha.com> Message-ID: <4866bea60706290544g23f6094id2f9ff603b871837@mail.gmail.com> On 6/28/07, Douglas Alan wrote: > "Chris Mellon" writes: > > > Obviously. But theres nothing about the with statement that's > > different than using smart pointers in this regard. > > Sure there is -- smart pointers handle many sorts of situations, while > "with" only handles the case where the lifetime of the object > corresponds to the scope. > The entire point of RAII is that you use objects who's lifetime corresponds with a scope. Smart pointers are an RAII technique to manage refcounts, not a resource management technique in and of themselves. > > To the extent that your code ever worked when you relied on this > > detail, it will continue to work. > > I've written plenty of Python code that relied on destructors to > deallocate resources, and the code always worked. > This is roughly equivilent to someone saying that they don't bother initializing pointers to 0 in C, because it's always worked for them. The fact that it works in certain cases (in the C case, when you're working in the debug mode of certain compilers or standard libs) does not mean that code that relies on it working is correct. > > There are no plans to replace pythons refcounting with fancier GC > > schemes that I am aware of. > > This is counter to what other people have been saying. They have been > worrying me by saying that the refcounter may go away and so you may > not be able to rely on predictable object lifetimes in the future. > Well, the official language implementation explicitly warns against relying on the behavior you've been relying on. And of course, for the purposes you've been using it it'll continue to work even if python did eliminate refcounting - "soon enough" deallocation of non-time sensitive resources. So I don't know what you're hollering about. You're arguing in 2 directions here. You don't want refcounting to go away, because you rely on it to close things exactly when there are no more references. On the other hand, you're claiming that implicit management and its pitfalls are fine because most of the time you don't need the resource to be closed in a deterministic manner. If you're relying on refcounting for timely, guaranteed, deterministic resource managment then your code is *wrong* already, for the same reason that someone who assumes that uninitialized pointers in C will be 0 is wrong. If you're relying on refcounting for "soon enough" resource management then it'll continue to work no matter what GC scheme python may or may not move to. > > Nothing about Pythons memory management has changed. I know I'm > > repeating myself here, but you just don't seem to grasp this > > concept. Python has *never* had deterministic destruction of > > objects. It was never guaranteed, and code that seemed like it > > benefited from it was fragile. > > It was not fragile in my experience. If a resource *positively*, > *absolutely* needed to be deallocated at a certain point in the code > (and occasionally that was the case), then I would code that way. But > that has been far from the typical case for me. > Your experience was wrong, then. It's fragile because it's easy for external callers to grab refcounts to your objects, and it's easy for code modifications to cause resources to live longer. If you don't *care* about that, then by all means, don't control the resource explicitly. You can continue to do this no matter what - people work with files like this in Java all the time, for the same reason they do it in Python. Memory and files are not the end all of resources. You're arguing against explicit resource management with the argument that you don't need to manage resources. Can you not see how ridiculously circular this is? From eadmund42 at NOSPAMgmail.com Sat Jun 23 02:04:40 2007 From: eadmund42 at NOSPAMgmail.com (Robert Uhl) Date: Sat, 23 Jun 2007 00:04:40 -0600 Subject: The Modernization of Emacs: terminology buffer and keybinding References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182272495.990807.99110@a26g2000pre.googlegroups.com> <87tzt3ihev.fsf@kobe.laptop> <1182370216.961241.6960@n60g2000hse.googlegroups.com> <85zm2ufjpb.fsf@lola.goethe.zz> <1182372592.803332.288260@u2g2000hsc.googlegroups.com> <1182373919.262388.100740@c77g2000hse.googlegroups.com> <85r6o6fhkb.fsf@lola.goethe.zz> <1182375045.626510.188170@m36g2000hse.googlegroups.com> <85myyufgwj.fsf@lola.goethe.zz> <1182375528.985142.293900@q69g2000hsb.googlegroups.com> <1182545268.055596.228700@i38g2000prf.googlegroups.com> Message-ID: Twisted writes: > > How clunky versus usable an interface to a tool is is for those who > invest some, but not extraordinary amounts of, time into its use to > decide. If it requires years of mastery, it is clunky -- period. This > may be unavoidable if it's something involved in nuclear power plants, > delicate neurosurgery, or whatever. If it's a text editor, on the > other hand, it's clearly going to have superior competition in the > area of usability. Of course, emacs doesn't take years of mastery. It takes 30, 40 minutes. And a functioning intellect, of course. Incidentally, a violin requires years of mastery, and is hardly cranky. Granted, there are few people with the talent to play a violin well. Maybe an automobile is a better example... > Besides, ANY interface that involves fumbling around in the dark > trying to find a light switch is clunky. That sounds like vi, not emacs. > Applications that not only eschew normal methods of navigation of the > interface, but force you to fumble your way between the help and the > task you're trying to do, are definitely clunky. a) emacs doesn't 'eschew normal methods of navigation'; it's been doing its own thing since before there _were_ Mac OS or Windows b) I believe you've never used the emacs tutorial, which is quite definitely designed for you _not_ to have to fumble around between windows > The interface never improved over that time -- the biggest problem > consistently being that whenever focus was successfully transferred to > the document window, the help window was invariably open to the > instructions for switching windows, so you could never be doing > something with the document and have the help for that something > available at a glance. That doesn't even make sense. Either your memory is faulty, you've never actually used emacs (something I'm beginning to suspect more and more) or you're just making things up. If I'm browsing the manual online, I can switch from said manual to my document buffer without making the manual scroll to the documentation for switch-to-buffer. In fact, I am not aware of any package which auto-changes the *info* or *Help* buffers to reflect the last keyboard command. > Even though it would be at the price of no full- text search > capability -- not that I could ever get that to work in emacs > anyway. There was no apparent way to do a simple substring search and > click "next match" or "previous match" to navigate among the > hits...more arcane keypresses would be required, and as soon as it > showed you the first match inside the help, the keypress documentation > of course vanished. Dude, you hit C-s; you're prompted for a search string; you hit C-s to search for the next match. From line 899 of the tutorial: >> Now type C-s to start a search. SLOWLY, one letter at a time, type the word 'cursor', pausing after you type each character to notice what happens to the cursor. Now you have searched for "cursor", once. >> Type C-s again, to search for the next occurrence of "cursor". If you had actually, you know, actually _read_ it this would not be a surprise. I hate to be rude, but I just don't see how you could ever have actually done what you claim to have done. > Infrequently used commands you can stand to hunt for in menus. When > you find you use one frequently, you can try to learn the keyboard > shortcut -- and you can find it without even consulting the help, > simply by finding the command's menu item. This is no different from emacs. There's a menu bar; it displays commands and shortcuts next to them; one can learn to use them instead, at one's own pace. > Every time you want to use the command but can't remember the shortcut > you just find it in the menu and activate it from there, and see the > shortcut while you're at it, helping to eventually memorize it. And > the commonest sorts of File and Edit menu items have near-universal > shortcuts, the big variation tending to be whether Redo is > shift-ctrl-Z, ctrl-Y, nonexistent, or menu-only. You've actually hit on another advantage of emacs: consider emacs itself as an operating system hosting multiple applications, in which the vast majority of commands are the same. I can use the same text-editing commands for reading & writing emails, reading & writing Usenet posts, reading & writing code, browsing the web, organising my schedule and so forth. The vast majority of what we do on a computer is reading & writing text--wouldn't it be cool to have a full-fledged text editing environment always available for that sort of thing? Wouldn't it be cool not to have one program implement search in one way, and another a second way, and yet another a third? Wouldn't it be cool to have access to a proper text editor when editing text on a web page? > But you can start using it right away with low productivity, and > increase your productivity with proficiency and learning (optional) > shortcuts, chiefly those to the commands you happen to use a lot. That's how I learnt emacs. I was 13, and had only ever used Mac software up until that point. I had a fairly limited command set (basically, C-x C-f, C-x C-s & C-x C-c). > One person elsewhere in this thread even went so far as to suggest > that to avoid having a similar hurdle with every application you just > use emacs for everything. If you like being claustrophobically trapped > in 80x24x8BPP instead of 1280x1024x32BPP, that may be your cup of tea. Do you realise that emacs has a GUI these days? I'm writing this in a 70-line window, with gtk+ widgets. Which means full-resolution, full-colour. -- Robert Uhl A wealthy man is one who earns $100 a year more than his wife's sister's husband. --H.L. Mencken From roy at panix.com Sat Jun 2 07:54:46 2007 From: roy at panix.com (Roy Smith) Date: Sat, 02 Jun 2007 07:54:46 -0400 Subject: Python Pop Quiz References: <1180751587.951837.191480@h2g2000hsg.googlegroups.com> Message-ID: In article , Marc 'BlackJack' Rintsch wrote: > In , Roy Smith > wrote: > > > In article <1180751587.951837.191480 at h2g2000hsg.googlegroups.com>, > > snorble at hotmail.com wrote: > >> 7. How many Z80 assembly language programmers does it take to equal > >> one Python guru? > > > > Trick question, the Z80 was a figment of your imagination. > > http://en.wikipedia.org/wiki/Zilog_Z80 Wikipedia is a figment of your imagination. And, having once had a Trash-80 (complete with audio cassette storage), I certainly hope the Z-80 was also. > > >> Essay: "C++ is better than C", agree or disagree? (four word maximum) > > > > STL compile error diagnostics. > > So do you agree or disagree!? ;-) Depends. Are we talking four 32-bit words or four 64-bit words? From laurent.pointal at limsi.fr Mon Jun 25 10:54:53 2007 From: laurent.pointal at limsi.fr (Laurent Pointal) Date: Mon, 25 Jun 2007 16:54:53 +0200 Subject: Changing sound volume In-Reply-To: References: Message-ID: simon kagwe a ?crit : > Hi, > > I am playing sounds using the winsound module. Is there a way I can change the > volume? > Maybe with pyGame, but you may have to switch from winsound to pygame.mixer.music http://www.pygame.org/ http://www.pygame.org/docs/ref/music.html A+ Laurent. From aleax at mac.com Thu Jun 28 01:53:26 2007 From: aleax at mac.com (Alex Martelli) Date: Wed, 27 Jun 2007 22:53:26 -0700 Subject: nested list comprehension and if clauses References: <1183007216.684569.222450@k79g2000hse.googlegroups.com> Message-ID: <1i0e21c.m73ptlth8j5mN%aleax@mac.com> Jyotirmoy Bhattacharya wrote: > I'm a newcomer to Python. I have just discovered nested list > comprehensions and I need help to understand how the if-clause > interacts with the multiple for-clauses. I have this small program: > > def multab(n): > print 'multab',n > return [n*i for i in range(5)] > > print [(m,n) for m in range(5) for n in multab(m) if m>2] > > It produces the output: > multab 0 > multab 1 > multab 2 > multab 3 > multab 4 > [(3, 0), (3, 3), (3, 6), (3, 9), (3, 12), (4, 0), (4, 4), (4, 8), (4, > 12), (4, 16)] > > I was wondering if there is some way to write the if-clause so that it > is 'hoisted' out of the inner loop and the multab function is not > called at all for m=0,1,2. That would seem to be important if multab > were an expensive function. Sure, just place the if clause where it needs to apply (between the two for clauses) [apart from the fact that this example is best expressed by using range(3,5), as somebody already said;-)]. Generally, the semantics of: x = [ for if for ] are exactly those of x = [] for : if : for : x.append(expr) and similarly for other mixes of for and if clauses (except that the first clause must always be a for clause) -- you can always, simply and mechanically conceptually translate them into an equivalent nest of for and if statements, ending in a somelist.append(...) [where somelist may be a "temporary anonymous" list if you're just going to use the listcomp further rather than just assigning it to a name]. Alex From aleax at mac.com Fri Jun 22 11:30:14 2007 From: aleax at mac.com (Alex Martelli) Date: Fri, 22 Jun 2007 08:30:14 -0700 Subject: PEP 3107 and stronger typing (note: probably a newbie question) References: <1182369568.941307.316260@p77g2000hsh.googlegroups.com> <5dtmtnF36t3pfU1@mid.uni-berlin.de> Message-ID: <1i03op4.16876ph18b32yzN%aleax@mac.com> Dave Baum wrote: ... > I still think it would be handy to easily specify the expected types of > function arguments. I sometimes write code in this pattern: > > def foo(a, b): > "a, b - instances of Bar" > assert isinstance(a, Bar) > assert isinstance(b, Bar) > # do some stuff so in 3.0 you'll be able to spell that @checkanddoc def foo(a: Bar, b: Bar): ... for some suitable decorator checkanddoc (and be assured that there will be a bazillion such decorators written to exploit the new syntax, of varying intent and quality). That's why 3.0 introduces that syntax (args can be spelled :) without giving it any semantics beyond the fact that the info is recorded with the function object and can be introspected from it -- enabling a thousand flowers to bloom in terms of such decorators. > On the downside, this sort of mechanism might do more harm than good. > For one thing, it would really clash with duck typing. For another, > anyone coming to Python from Java/C++ would probably use those > declarations *everywhere*, even when there isn't a good reason to limit > the type. Sure, even more than they currently use wanton isinstance calls (or even worse, type(x)==... checks). But hopefully the new "syntax hook" will also allow GOOD decorators to emerge (e.g., ones doing adaptation rather than mere checks). Alex From duncan.booth at invalid.invalid Thu Jun 21 08:01:16 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 21 Jun 2007 12:01:16 GMT Subject: Globals in nested functions References: <1182424010.561262.169170@j4g2000prf.googlegroups.com> Message-ID: "jm.suresh at no.spam.gmail.com" wrote: > def f(): > a = 12 > def g(): > global a > if a < 14: > a=13 > g() > return a > > print f() > > This function raises an error. Is there any way to access the a in f() > from inside g(). > > I could find few past discussions on this subject, I could not find > the simple answer whether it is possible to do this reference. > 'global' means global to the module, it prevents the lookup happening in current or nested scopes. Simple answer: You can access an object referenced by a nested scope variable and you can mutate the object accessed in that way, but you cannot rebind the name to a different object without resorting to hackery. To get the effect you want, simply use a mutable object: >>> def f(): class v: a = 12 def g(): if v.a < 14: v.a=13 g() return v.a >>> f() 13 and as soon as the code starts looking at all complex, refactor that so the class is the thing you interact with: >>> class F(object): def g(self): if self.a < 14: self.a = 13 def __call__(self): self.a = 12 self.g() return self.a >>> f = F() >>> f() 13 From bdesth.quelquechose at free.quelquepart.fr Mon Jun 25 23:29:22 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Tue, 26 Jun 2007 05:29:22 +0200 Subject: Collections of non-arbitrary objects ? In-Reply-To: <1182780863.067601.89320@d30g2000prg.googlegroups.com> References: <1182449993.223262.229500@z28g2000prd.googlegroups.com> <87k5twx4hf.fsf@benfinney.id.au> <1182559502.069773.321620@i38g2000prf.googlegroups.com> <87wsxvrzsj.fsf@benfinney.id.au> <1182620734.940718.196520@e16g2000pri.googlegroups.com> <467ed491$0$27132$426a34cc@news.free.fr> <1182780863.067601.89320@d30g2000prg.googlegroups.com> Message-ID: <46801791$0$32172$426a34cc@news.free.fr> walterbyrd a ?crit : > On Jun 24, 10:31 pm, Bruno Desthuilliers > wrote: > > >>>Especially since variables in python do not have to be explicitly >>>assigned >> >>??? > > > I have probably expressed this incorrectly. What I meant was: > > >>>>a = [1,2,3] >>>>b = a >>>>a[1] = 'spam' > > > Here, I have changed b, without an explicit assignment. You haven't changed b, you have changed the object bound to name 'b'. Which happens to be also bound to name 'a'. > After I > assigned a to b, Well, I guess the term "assignment" is misleading you then. "binding" would be more accurate - you bound names 'a' and 'b' to the same object. Then, whether you access this object via name 'a' or name 'b', you're still accessing the same object. > I never did another "b =" yet b changed anyway Doing 'b = some_other_object' would still not 'change b' - you don't change a name - but rebind name 'b' to another object. You perhaps don't know this, but most statically typed languages have the notion of either pointers or references, that can cause similar - and usually worse - problems. > because I changed a. I am not saying there is anything wrong with > this, I'm just explaining what I meant. > > So let's say I have list L, and I have a routine that expects every > item in L to be a dictionary like: {'name':'joe', 'job':'dev', 'pay': > min_wage}. > > Not only could the app crash if an incorrect item where inserted into > L. But the app could crash if an incorrect item were inserted in lists > X,Y, or Z. Yes - assuming names L, X, Y and Z are bound to the same list. And it would also crash if one the dicts was modified between the moment it is added to the list and the moment you pass the list to your function. Which makes "typed" lists totally useless anyway. And even if you use a smarter 'correctness' test (like a callback function checking that every item added or inserted supports keying and has the correct keys), it would still be useless since you could still manage to modify one of the items of the list *after* it has been added to it. > Of course, you can always work around this by just programming very > carefully, You do program carefully, don't you ?-) > and doing a lot of error checking. That's usually not even necessary - most of the time (ie: almost always), you'll have a nice traceback in the minutes following the moment you introduced the error. > That is always true in > any language. Nope. In Python, you seldom have to do error *checking* - the language do it for you (that's what exceptions are for). What you have to do is 1/ testing, and 2/ error *handling*. Now did you actually had any effective problem with Python's dynamism ? Or are you just scared ? You know, Python is now something like 17 years old, and is used by a *lot* of peoples for a *lot* of programs - some of them far from trivial. I think you can be confident in this experience. IOW, just write your code, and you'll find out that the kind of problems you seem to fear so much will not happens that often. > But, I think sometimes it's helpful to use a structure that is little > more restrictive, to sort of enforce a degree of integrity. Sometimes you do have to check the validity of the data you are supposed to work on, true - mostly when it comes to program inputs (be it wia files, sockets, forms, environment, whatever). Once this is done, you shouldn't have to worry too much - just let Python crash when there's something wrong, carefully read the traceback, and correct the offending code (which is very likely in the last modifications you made). > An example > I have already given: why use tuples instead of a list? Tuples are > actually a bit more restrictive. You don't use tuples "instead of" lists. Lists are collections, tuples are structured data. > I don't think there is anything wrong with the data structures that > exist in python. I was just wondering if there was a structure that > would restrict a collection to only allow certain types. Not builtin. You can roll your own if it makes you happy, but that would be a waste of time - been here, done that, you see... > The > "restrictedlist" class discussed in another thread may be the sort of > thing I was looking for. So please take time to read the whole thread. > BTW: I think polymorphism is great and all. But it does have (and IMO > should have) it's limitations. Yes, indeed - if an object doesn't understand a message, then you have an exception. But since the only way to know if an object can handle a message is to send the message (please refer to my previous post), enforcing 'type'-based (with 'type'=='class') restriction in Python is not only useless, it's also harmful. IOW, stop fighting against the language - just use it. > For example, I don't think you can > divide a string by another string. No, because this operation is not implemented for strings - IOW, strings doesn't understand this message. What would be the meaning of dividing strings anyway ? (while concatening string is a well-known operation). From devicerandom at gmail.com Thu Jun 28 08:41:18 2007 From: devicerandom at gmail.com (massimo s.) Date: Thu, 28 Jun 2007 05:41:18 -0700 Subject: problem with hack using multiple inheritance for plugins In-Reply-To: <46839f4c$0$22380$426a74cc@news.free.fr> References: <1183026288.857294.91620@q69g2000hsb.googlegroups.com> <1183028051.940679.145680@q69g2000hsb.googlegroups.com> <46839f4c$0$22380$426a74cc@news.free.fr> Message-ID: <1183034478.587345.214570@w5g2000hsg.googlegroups.com> On 28 Giu, 13:45, Bruno Desthuilliers wrote: > wxFrame is obviously a new-style class. I don't know if it's true, however. I tried that: >>> class A(object): ... def __init__(self): ... print type(self) ... >>> a=A() so in fact what I see has something to do with new style classes (if subclassing 'object' is enough). The new-style behaviour only appears when wxFrame is plugged with the current hack. That is: - print type(self) in wxFrame alone returns - print type(self) in the plugged (multiply inherited) wxFrame returns < class '__main__.MainWindowPlugged'> So the problem is that I acquire a new style behaviour somewhere! I tried to let the plugin class be a new style class (subclassing 'object': again, I can't find a simple reference about it, I tried to read www.python.org/doc/newstyle.html links but they are far too much theoretical for my knowledge) and nothing seems to change at all. m. From Stebanoid at gmail.com Thu Jun 7 14:02:18 2007 From: Stebanoid at gmail.com (Stebanoid) Date: Thu, 07 Jun 2007 11:02:18 -0700 Subject: running a random function In-Reply-To: <1654405.LVbK4P6cM3@teancum> References: <1654405.LVbK4P6cM3@teancum> Message-ID: <1181239338.068346.323050@h2g2000hsg.googlegroups.com> On 7 , 19:56, David Bear wrote: > I would like to write some code that would randomly select a function from a > list of functions and call it. I was looking in the globals names space and > randomly selecting items that were of type function.. but I didn't see a > way of actually running the function. > > Any pointers? > > -- > David Bear > -- let me buy your intellectual property, I want to own your thoughts -- if you have a list of functions you can try this: import random import math m[int(math.floor(len(m)*random.random()))]() # seems like Lisp code :D where m - is list of functions. but what about functions arguments? Strange task.. Very strange... From conor.robinson at gmail.com Thu Jun 14 14:41:01 2007 From: conor.robinson at gmail.com (py_genetic) Date: Thu, 14 Jun 2007 18:41:01 -0000 Subject: Efficient way of generating original alphabetic strings like unix file "split" Message-ID: <1181846461.238047.84140@j4g2000prf.googlegroups.com> Hi, I'm looking to generate x alphabetic strings in a list size x. This is exactly the same output that the unix command "split" generates as default file name output when splitting large files. Example: produce x original, but not random strings from english alphabet, all lowercase. The length of each string and possible combinations is dependent on x. You don't want any repeats. [aaa, aab, aac, aad, .... aax, ...... bbc, bbd, .... bcd] I'm assumming there is a slick, pythonic way of doing this, besides writing out a beast of a looping function. I've looked around on activestate cookbook, but have come up empty handed. Any suggestions? Thanks, Conor From devicerandom at gmail.com Thu Jun 28 10:56:28 2007 From: devicerandom at gmail.com (massimo s.) Date: Thu, 28 Jun 2007 07:56:28 -0700 Subject: problem with hack using multiple inheritance for plugins In-Reply-To: References: <1183026288.857294.91620@q69g2000hsb.googlegroups.com> <1183028051.940679.145680@q69g2000hsb.googlegroups.com> <46839f4c$0$22380$426a74cc@news.free.fr> <1183034478.587345.214570@w5g2000hsg.googlegroups.com> <1183036068.348031.240690@n60g2000hse.googlegroups.com> Message-ID: <1183042588.206452.323780@g4g2000hsf.googlegroups.com> On 28 Giu, 15:37, Peter Otten <__pete... at web.de> wrote: > massimo s. wrote: > > Again: using a new-style plugin class for multiple inheritance does > > not work. > > This statement is certainly too broad. > > [earlier] > > > TypeError: unbound method _plug_init() must be called with > > dummyguiplugGui instance as first argument (got MainWindowPlugged > > instance instead) > > So it looks like you failed to make dummyguiplugGui a base class of > MainWindowPlugged. Right (Checked with dir() -dummyguiplugGui methods do not appear ). > > What can I do now? > > Post a self-contained example. I'll try. m. From bbxx789_05ss at yahoo.com Sun Jun 10 13:11:11 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: Sun, 10 Jun 2007 10:11:11 -0700 Subject: Select one of 2 functions with the same name ? In-Reply-To: References: Message-ID: <1181495471.075900.16470@k79g2000hse.googlegroups.com> On Jun 10, 10:37 am, Stef Mientki wrote: > hello, > > For a simulation at different levels, > I need different functions with the same name. > Is that possible ? > > I can realize it with a simple switch within each function, > but that makes the code much less readable: > > def Some_Function(): > if simulation_level == 1: > ... do things in a way > elif simulation_level == 2: > ... do things in another way > elif simulation_level == 3: > ... do things in yet another way > > thanks, > Stef Mientki Try something like this: class Simulation1(object): def greet(self): print "hello" class Simulation2(object): def greet(self): print "hello" class Simulation3(object): def greet(self): print "hello" def someFunc(simObj): simObj.greet() s1 = Simulation1() s2 = Simulation2() s3 = Simulation3() someFunc(s1) someFunc(s2) someFunc(s3) From sjmachin at lexicon.net Mon Jun 18 19:30:53 2007 From: sjmachin at lexicon.net (John Machin) Date: Mon, 18 Jun 2007 16:30:53 -0700 Subject: getting the size of an object In-Reply-To: <1182207606.651533.285020@c77g2000hse.googlegroups.com> References: <1182207606.651533.285020@c77g2000hse.googlegroups.com> Message-ID: <1182209453.019399.321210@e9g2000prf.googlegroups.com> On Jun 19, 9:00 am, 7stud wrote: > On Jun 18, 10:07 am, "filox" wrote: > > > is there a way to find out the size of an object in Python? e.g., how could > > i get the size of a list or a tuple? > > > -- > > You're never too young to have a Vietnam flashback > > You can use the struct module to find the size in bytes: > > import struct > > mylist = [10, 3.7, "hello"] > > int_count = 0 > float_count = 0 > char_count = 0 > > for elmt in mylist: > if type(elmt) == int: > int_count += 1 > elif type(elmt) == float: > float_count += 1 > elif type(elmt) == str: > char_count += len(elmt) > > format_string = "%di%dd%dc" % (int_count, float_count, char_count) > list_size_in_bytes = struct.calcsize(format_string) > print list_size_in_bytes > > --output:-- > 17 That would give you the size taken up by the values. However each object has in addition to its value, a pointer to its type, and a reference count -- together an extra 8 bytes each on a 32-bit CPython implementation. A second problem is that your calculation doesn't allow for the interning of some str values and some int values. A third problem is that it caters only for int, float and str elements -- others count for nothing. From deets at nospam.web.de Thu Jun 7 18:47:05 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 08 Jun 2007 00:47:05 +0200 Subject: Running a process every N days In-Reply-To: <1181255261.648057.184930@x35g2000prf.googlegroups.com> References: <1181255261.648057.184930@x35g2000prf.googlegroups.com> Message-ID: <5crg7gF32cpdtU1@mid.uni-berlin.de> danmcleran at yahoo.com schrieb: > What's the best way to run either an entire python process or a python > thread every N days. I'm running Python 2.4.3 on Fedora Core 5 Linux. > My code consists of a test and measurement system that runs 24/7 in a > factory setting. It collects alot of data and I'd like to remove all > data older than 30 days. My ideal solution would be something that > runs in the background but only wakes up to run every few days to > check for old data. Use cron, the periodic task scheduler of your OS. Diez From showell30 at yahoo.com Sun Jun 3 17:52:59 2007 From: showell30 at yahoo.com (Steve Howell) Date: Sun, 3 Jun 2007 14:52:59 -0700 (PDT) Subject: another thread on Python threading In-Reply-To: <1180906374.041535.296410@k79g2000hse.googlegroups.com> Message-ID: <235075.86523.qm@web33514.mail.mud.yahoo.com> --- "cgwalters at gmail.com" wrote: > One random idea is to for Python 3000, make the > equivalent of > __slots__ the default, *but* instead gather > the set of attributes from all member variables set > in __init__. Are you suggesting to do this at startup time or runtime? The pitfall here is that to reduce code duplication, you might initialize certain variables in a method called by __init__, because your object might want to return to its initial state. An example might be an object that flipflops between waiting for headers and waiting for payloads. You might have code like this: class MessageReader: def __init__(self, incoming_port): self.incoming_port = incoming_port self.start_waiting_for_headers() def start_waiting_for_headers(self): self.waiting_for_headers = '' self.header = '' self.payload = '' def handle_payload(self): self.do_something_with(self.payload) self.start_waiting_for_headers() # ... ____________________________________________________________________________________ Looking for a deal? Find great prices on flights and hotels with Yahoo! FareChase. http://farechase.yahoo.com/ From twisted0n3 at gmail.com Sun Jun 24 19:57:30 2007 From: twisted0n3 at gmail.com (Twisted) Date: Sun, 24 Jun 2007 23:57:30 -0000 Subject: The Modernization of Emacs: terminology buffer and keybinding In-Reply-To: References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182272495.990807.99110@a26g2000pre.googlegroups.com> <87tzt3ihev.fsf@kobe.laptop> <1182370216.961241.6960@n60g2000hse.googlegroups.com> <85zm2ufjpb.fsf@lola.goethe.zz> <1182372592.803332.288260@u2g2000hsc.googlegroups.com> <5dtk4tF34jrimU1@mid.dfncis.de> <1182375388.814275.227380@n2g2000hse.googlegroups.com> <87645h73ei.fsf@W0053328.mgh.harvard.edu> <1182548563.561252.82480@i13g2000prf.googlegroups.com> <1182666078.511962.280030@w5g2000hsg.googlegroups.com> Message-ID: <1182729450.495841.296140@q69g2000hsb.googlegroups.com> On Jun 24, 6:52 pm, Robert Uhl wrote: > > Really? None of [navigating a folder window analogue] happens if > > you just do the straightforward file-open command, which should > > obviously at least provide a navigable directory tree, but > > definitely does not. > > The first does. Really, it does. Fire up emacs (which you've never > done before) and type C-x C-f. Whoa, Nellie. I seem to recall we were discussing the file-open command. That was something else, like C-x C-o or something. More apples-and- oranges? > You will be presented with a prompt > something like 'Find file: ~/'; hit tab once; you'll see the message > '[Complete, but not unique]'; hit tab again and you will be presented a > list of all files in that directory. Sounds clunky anyway. I don't need a bunch of keypresses to do the equivalent in an Explorer-based file-open dialog in a native Windows app. Just a double-click. Emacs, with your C-x C-f: C-x C-f tab tab ("Startofnameofdirectory somethingElse otherstuff") Startofname tab tab ("Subdirectory anotherSubdirectory") Subd tab tab Windows: Alt, f, o ("Startofnameofdirectory somethingElse otherstuff") Click-click or Startofname-down-enter ("Subdirectory anotherSubdirectory") Click-click or Subd-down-enter Worst case (all keyboard): one fewer keypress. Best case (judicious use of the mouse and smart hand placement, one by left alt and one on the mouse): five TOTAL gestures. In particular, C-x C-f tab tab is replaced by alt f o (four down to three keypresses) or click file, click open (two instead of three inputs, but you have to locate the File menu from halfway across the screen with the pointer, so count it as three as well). Being able to pick an item from a list just by touching the damn thing instead of typing in a sufficiently long prefix is definitely an advantage, and if a lot of things share the same 16-character prefix in a particular directory, the emacs way starts to look SLOW. Of course, there's an even faster Windows way, if you don't mind not seeing lists of possible items: Alt, f, o Startofname-down-/-Subd-down-/ Straight to the subdirectory without waiting for it to display the parent directory or the root. Same number of inputs. And of course there's the super-fast Alt, f, o, C-v, enter if you happen to have the exact path in the clipboard already. I'd like to see emacs do that, at least if the text to paste originated outside emacs. (If I'm doing this in Winword's file open dialog it could have originated in Notepad, Firefox, or just about anywhere else, not just Winword.) > If you like 'em, though, just select File:Visit New File. It gives you > a platform-default (gtk+, for me) file selector. Now we're talking about a graphical port instead of stock emacs again. :P > Nope, because of the way emacs works you can stop what you're doing, do > something else and come back to the minibuffer. After spending a while brushing up on my Tibetan, I may or may not agree, but until I've got some real meaning out of your use of jargon like "minibuffer", I'll have to pass on this one. Nonetheless, stuff you can do but can't know you can do without learning Tibetan is unlikely to be of much help to the average user. :) > Fortunately, folks brighter than you & I have imagined a nice way for > us. It pops up a new Emacs window (pane, if you prefer the terminology) > showing a list of all filenames. You could continue typing, or just > click on a filename in the window, or hit return while the cursor is on > a filename in that window. Back to discussing a graphical port again. Besides the apples and oranges issue, this amounts to implementing a dodgy imitation of a file open dialog anyway. Why bother with such an imitation when you can use a natively-GUI editor written for your platform and get access to the real thing? From gagsl-py2 at yahoo.com.ar Tue Jun 5 23:18:24 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 06 Jun 2007 00:18:24 -0300 Subject: get_traceback References: <1180977780.997361.133320@g37g2000prf.googlegroups.com> <1181008984.098975.152110@a26g2000pre.googlegroups.com> Message-ID: En Mon, 04 Jun 2007 23:03:04 -0300, escribi?: > Thanks Gabriel. That was exactly what I was looking for. Also, I'm > glad to make a connection to the StringIO class. I'm sure I will > remember it the next time I need it. Glad to see it helped. Certainly StringIO is a good thing to carry in your toolbox... -- Gabriel Genellina From bruno.42.desthuilliers at wtf.websiteburo.oops.com Thu Jun 21 03:04:01 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Thu, 21 Jun 2007 09:04:01 +0200 Subject: PEP 3107 and stronger typing (note: probably a newbie question) In-Reply-To: References: <1182369568.941307.316260@p77g2000hsh.googlegroups.com> Message-ID: <467a22d0$0$28538$426a74cc@news.free.fr> Stephen R Laniel a ?crit : > On Wed, Jun 20, 2007 at 09:41:09PM +0100, Michael Hoffman wrote: >> If you asked Java programmers why you couldn't turn *off* Java's static >> type checking if you wanted to, you'd probably get a similar response. > > Perhaps it would help for me to explain what I'd like. > > Under both Perl and Python, I've found myself > having/wanting to write things like so: > > def my_func( int_arg, str_arg ): > try: > int_arg = int( int_arg ) > str_arg = str( str_arg ) > except ValueError: > sys.stderr.write( "Args are not of the right type\n" ) > sys.exit(1) > Just a question : what will happen if you get rid of the try/except block ?-) From gagsl-py2 at yahoo.com.ar Tue Jun 12 00:08:46 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 12 Jun 2007 01:08:46 -0300 Subject: Set PyObject value from C extension References: <1181617770.268753.70660@j4g2000prf.googlegroups.com> Message-ID: En Tue, 12 Jun 2007 00:09:30 -0300, Allen escribi?: > I have the PyObject pointers, and want to set different type of values > to them. > > For example, > > INT8 nValue1 = 0; > INT16 nValue2 = 1; > FLOAT32 fValue = 1.0f; > > PyObject* var1 <= nValue1 > PyObject* var2 <= nValue2 > PyObject* var3 <= nValue3 > > How to do it? What do you mean by "I have the PyObject pointers"? Integers and floats are immutable in Python. You can't "set" an existing PyIntObject or PyFloatObject to another value. But you can create *new* objects from the desired values, using PyInt_FromLong and PyFloat_FromDouble. If this is your first approach to Python, I suggest first become familiar with the language, and later try to mix it with C code. -- Gabriel Genellina From tjreedy at udel.edu Thu Jun 7 14:23:06 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 7 Jun 2007 14:23:06 -0400 Subject: Where can I suggest an enchantment for Python Zip lib? References: <4667D967.4070200@gmail.com> Message-ID: "durumdara" wrote in message news:4667D967.4070200 at gmail.com... | Hi! | | Where can I ask it? | | I want to ask that developers change the Python's Zip lib in the next | versions. On the sourceforge tracker, http://sourceforge.net/tracker/?group_id=5470 there is a Feature Request category. From doug at alum.mit.edu Fri Jun 15 23:44:33 2007 From: doug at alum.mit.edu (Douglas Alan) Date: Fri, 15 Jun 2007 23:44:33 -0400 Subject: Python's "only one way to do it" philosophy isn't good? References: <1181368143.874341.273140@r19g2000prf.googlegroups.com> Message-ID: Steven D'Aprano writes: > On Fri, 15 Jun 2007 17:05:27 -0400, Douglas Alan wrote: >> You are ignoring the fact that Scheme has a powerful syntax extension >> mechanism (i.e., hygenic macros), which means that anyone in the world >> can basically extend Scheme to include practically any language >> feature they might like it to have. > You say that like it is a good thing. A chaque son gout. |>oug From bdesth.quelquechose at free.quelquepart.fr Sat Jun 30 00:12:53 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sat, 30 Jun 2007 06:12:53 +0200 Subject: PEP 3107 and stronger typing (note: probably a newbie question) In-Reply-To: References: <1182448413.966430.299590@m36g2000hse.googlegroups.com> <7xhcp0fom4.fsf@ruckus.brouhaha.com> <87tzt0tgol.fsf@benfinney.id.au> <1182533987.715191.159850@m36g2000hse.googlegroups.com> Message-ID: <468567b3$0$26422$426a74cc@news.free.fr> Eduardo "EdCrypt" O. Padoan a ?crit : > On 6/22/07, John Nagle wrote: > Remember that pure CPython has no different "compile time" and > runtiime. Oh yes ? So what's the compiler doing, and what are those .pyc files ? (hint: read the doc) From derekacolley at googlemail.com Mon Jun 18 10:24:09 2007 From: derekacolley at googlemail.com (DAC) Date: Mon, 18 Jun 2007 14:24:09 -0000 Subject: Having lots of fun passing parameters ... help! In-Reply-To: <5dnha8F35ca42U1@mid.uni-berlin.de> References: <1182174634.676242.222140@n60g2000hse.googlegroups.com> <5dnha8F35ca42U1@mid.uni-berlin.de> Message-ID: <1182176649.297709.61040@n2g2000hse.googlegroups.com> On 18 Jun, 14:57, "Diez B. Roggisch" wrote: > DAC wrote: > > I've defined a single method in Python using: > > > def funcAdjacents(inputWord, outputFile): > > ... > > lots of boring stuff > > ... > > > and then called it using: > > > funcAdjacents("SampleWord","outputFile.file") > > > Which works OK in Python - I get the results I want. But what I'm > > trying to do is get inputWord and outputFile to be parameters are > > passed on the command line, e.g. > > > C:\Python\> myScript.py "SampleWord" "outputFile.file" > > > And just to add to the fun, once I've reached this stage I would like > > to either a) be able to execute this .py file from a HTML environment > > or b) execute this file as a .exe and embed into HTML (which I can > > do). > > You get the parameters to a script executed at the shell using > > import sys > print sys.argv > > or in your case > > funcAdjacents(*sys.argv[1:]) > > Executing this from HTML requires the usage of CGI. But without further > details what you really are after here and what your webenvironment is, we > won't be able to help you. > > Diez- Hide quoted text - > > - Show quoted text - Thanks Diez, I understand what you mean. I'm fine with the CGI aspect of things, it was just getting those parameters across which was difficult. DAC. From duncan.booth at invalid.invalid Thu Jun 28 04:31:04 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 28 Jun 2007 08:31:04 GMT Subject: Help needed with translating perl to python References: <1182870250.890390.28970@g37g2000prf.googlegroups.com> <1182873580.469958.220390@z28g2000prd.googlegroups.com> <1182878536.544941.68070@e16g2000pri.googlegroups.com> Message-ID: attn.steven.kuo at gmail.com wrote: > Let me add that instead of an an-close-as-possible translation > from the original Perl code, one can rewrite this as: > >>>> def bcdlen(length): > ... strlen = "%04s" % length > ... return chr(int(strlen[2:4], 16)) + chr(int(strlen[0:2], 16)) > > > which is more "Pythonic" to me. Throwing an exception for values of length less than 100 doesn't seem terribly good. Did you mean "%04d"? Personally I think I'd split the number up before round-tripping through the string. Maybe: def bcdbyte(b): return chr(int(str(b), 16)) def bcdlen(length): return bcdbyte(length%100) + bcdbyte(length//100) From gagsl-py2 at yahoo.com.ar Fri Jun 1 22:25:23 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 01 Jun 2007 23:25:23 -0300 Subject: c[:]() References: <1180504190.055427.173610@h2g2000hsg.googlegroups.com> <1180554872.3356.30.camel@dot.uniqsys.com> <465DF3DE.40404@cc.umanitoba.ca> <1180566831.239580.199300@m36g2000hse.googlegroups.com> <005401c7a31a$136f7fe0$240110ac@Muse> <135tobve86qj808@corp.supernews.com> <135tru124pie2b3@corp.supernews.com> <135tv1bjqgbmsc9@corp.supernews.com> <9qudnbFRU9QHJsLbnZ2dnUVZ_rKvnZ2d@speakeasy.net> <005f01c7a471$6f4b8b30$240110ac@Muse> Message-ID: En Fri, 01 Jun 2007 14:22:29 -0300, Warren Stringer escribi?: > I am not insisting on anything. I use ``c[:]()`` as shorthand way of > saying > "c() for c in d where d is a container" I begin to think you are some kind of Eliza experiment with Python pseudo-knowledge injected. Anyway, the code below defines a simple "callable" list; it just calls each contained item in turn. Don't bother to use [:], it won't work. py> class CallableList(list): ... def __call__(self): ... for item in self: ... item() ... py> def a(): print "a" ... py> def b(): return 4 ... py> def c(): pass ... py> def d(): ... global z ... z = 1 ... py> z="A" py> x = CallableList([a,b,c,d]) py> x() a py> z 1 -- Gabriel Genellina From stargaming at gmail.com Fri Jun 22 11:39:06 2007 From: stargaming at gmail.com (Stargaming) Date: Fri, 22 Jun 2007 17:39:06 +0200 Subject: Changing the names of python keywords and functions In-Reply-To: <1182452862.872909.206780@u2g2000hsc.googlegroups.com> References: <1182452862.872909.206780@u2g2000hsc.googlegroups.com> Message-ID: <467bed1f$0$2991$9b622d9e@news.freenet.de> vedrandekovic at v-programs.com schrieb: > Hello, > > I am trying to make a program for 3D modelling with "programming".And > I want make my own program commands, > > for example when user type code in my program: > > "<> OS"- (THIS IS MY IMAGINARY EXAMPLE OF KEYWORD), > > my program must write this code in some user file, but my > > program must read this command like: "import os".How > > can I do something like that?? > > Please, HELP ME somebody!!! > Besides your request is sorta weird (languages are mostly meant to give a ruleset of expressions, not a framework of mutability, at least the more widespread ones), Python does not support something like this out of the box. There have been several discussions about such features and they were all abandoned due to unification. You can, of course, follow the "normal" track to implement any language and write a parser, lexer, compiler and whatever. Tools like `pyparsing`_ or `PLY`_ might help you (there are much more). Though, there *is* a mutable codeset of Python called `Logix`_. As far as I glanced at it, it is pretty mutable and might fit your needs perfectly. Ah, and if you perhaps remove the leading << there, this might be pretty much implementable by overloading __rshift__ at your koristiti object. HTH, Stargaming .. _pyparsing: http://pyparsing.wikispaces.com/ .. _PLY: http://www.dabeaz.com/ply/ply.html .. _Logix: http://livelogix.net/logix/ From paul at boddie.org.uk Fri Jun 1 08:04:03 2007 From: paul at boddie.org.uk (Paul Boddie) Date: Fri, 01 Jun 2007 05:04:03 -0700 Subject: subexpressions In-Reply-To: References: Message-ID: <1180699443.822567.256680@g4g2000hsf.googlegroups.com> On 1 Jun, 12:55, Steve Howell wrote: > > FWIW there's the possibility that even without a > subexpression syntax, some Python implementations > would detect the duplication of x*x and optimize that > for you. It would have to know that x*x had no side > effects, which I think is a safe assumption even in a > dynamic language like Python. On the basis of you believing that x is one of the built-in numeric types, yes, but how does the compiler know that? Paul From linuxprog at gmail.com Wed Jun 20 12:58:34 2007 From: linuxprog at gmail.com (linuxprog) Date: Wed, 20 Jun 2007 16:58:34 +0000 Subject: need help with re module Message-ID: <46795CBA.9040807@gmail.com> hello i have that string "helloworldok" and i want to extract all the text , without html tags , the result should be some thing like that : helloworldok i have tried that : from re import findall chaine = """helloworldok""" print findall('[a-zA-z][^(<.*>)].+?[a-zA-Z]',chaine) >>> ['html', 'hell', 'worl', 'anyt', 'ag>o'] the result is not correct ! what would be the correct regex to use ? From sergio at sergiomb.no-ip.org Tue Jun 19 16:21:08 2007 From: sergio at sergiomb.no-ip.org (=?UTF-8?B?U8Opcmdpbw==?= Monteiro Basto) Date: Tue, 19 Jun 2007 21:21:08 +0100 Subject: HTMLParser.HTMLParseError: EOF in middle of construct References: <1182195498.16548.5.camel@localhost.localdomain> <4677e790$0$2840$a729d347@news.telepac.pt> Message-ID: <46783ab1$0$1266$a729d347@news.telepac.pt> First, sorry about the mess, let see if kontact works better with newsgroups. Marc 'BlackJack' Rintsch wrote: >> ok but my problem is not understand what is the specific problem at line >> 1173 > > You can't just look at that line and ignore the rest. ?There are 604 (!) > errors, some about table rows, before this line. ?So the parser may be > confused at this point and be already in an internal state that sees that > line in a completely different light than you do. Ok , but is one single error that blocks this. Finally I found it , it is : <1182071765.760451.298490@u2g2000hsc.googlegroups.com> Message-ID: <1hzuiyo.sa2r1312qz16qN%aleax@mac.com> David Wahler wrote: ... > Tuples are immutable (can't be modified once created). Try this: > > def BDllids(): > conn = sqlite.connect('tasques.db') > cursor = conn.cursor() > cursor.execute('SELECT * FROM tasques') > a = [row[0] for row in cursor] > return tuple(a) > > Is there some particular reason you need to return a tuple as opposed to a > list? Assuming there is (need to use it as a dict key, RHS operand of string formatting % operator, etc) I would suggest collapsing the last 2 statements in your excellent code into return tuple(row[0] for row in cursor) > P.S. Accessing fields of a SELECT * by numeric index is prone to > breakage if the order of your fields changes. You can make your code > more robust by either specifying the column name explicitly in the > SELECT statement. Alternatively, you may be interested in the Absolutely true -- in this case, return tuple(cursor) will suffice. Alex From x31equsenet at gmail.com Tue Jun 19 09:02:39 2007 From: x31equsenet at gmail.com (Graham Breed) Date: Tue, 19 Jun 2007 13:02:39 -0000 Subject: Trivial string substitution/parser References: Message-ID: <1182258159.121481.118010@e9g2000prf.googlegroups.com> Duncan Booth wote: > If you must insist on using backslash escapes (which introduces the > question of how you get backslashes into the output: do they have to be > escaped as well?) then use string.Template with a custom pattern. If anybody wants this, I worked out the following regular expression which seems to work: (?P\\)\$ | # backslash escape pattern \$(?: (?P[_a-z][_a-z0-9]*) | # delimiter and Python identifier {(?P[_a-z][_a-z0-9]*)} | # delimiter and braced identifier (?P) # Other ill-formed delimiter exprs ) The clue is string.Template.pattern.pattern So you compile that with verbose and case-insensitive flags and set it to "pattern" in a string.Template subclass. (In fact you don't have to compile it, but that behaviour's undocumented.) Something like >>> regexp = """ ... (?P\\\\)\\$ | # backslash escape pattern ... \$(?: ... (?P[_a-z][_a-z0-9]*) | # delimiter and identifier ... {(?P[_a-z][_a-z0-9]*)} | # ... and braced identifier ... (?P) # Other ill-formed delimiter exprs ... ) ... """ >>> class BackslashEscape(Template): ... pattern = re.compile(regexp, re.I | re.X) ... Graham From gagsl-py2 at yahoo.com.ar Tue Jun 12 07:59:26 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 12 Jun 2007 08:59:26 -0300 Subject: Postpone creation of attributes until needed References: <1181553891.447344.109390@g4g2000hsf.googlegroups.com> <1181559496.911368.219210@p77g2000hsh.googlegroups.com> <1181564855.890242.116840@m36g2000hse.googlegroups.com> <1181626546.323759.80500@i13g2000prf.googlegroups.com> Message-ID: En Tue, 12 Jun 2007 08:18:40 -0300, Steven D'Aprano escribi?: > On Mon, 11 Jun 2007 22:35:46 -0700, Frank Millman wrote: > >> Because, as I have tried to explain elsewhere (probably not very >> clearly), not all the information required to perform compute() is >> available at __init__ time. > > I'm sorry, but this explanation doesn't make sense to me. > > Currently, something like this happens: > > (1) the caller initializes an instance > => instance.x = some known value > => instance.y is undefined > (2) the caller tries to retrieve instance.y > (3) which calls instance.__getattr__('y') > (4) which calls instance.compute() > => which forces the necessary information to be available > => instance.__dict__['y'] = some value > (5) finally returns a value for instance.y > > Since, as far as I can tell, there is no minimum time between creating > the > instance at (1) and trying to access instance.y at (2), there is no > minimum time between (1) and calling compute() at (4), except for the > execution time of the steps between them. So why not just make compute() > the very last thing that __init__ does? As far as I understand what the OP said, (2) may never happen. And since (4) is expensive, it is avoided until it is actually required. -- Gabriel Genellina From showell30 at yahoo.com Tue Jun 5 09:28:59 2007 From: showell30 at yahoo.com (Steve Howell) Date: Tue, 5 Jun 2007 06:28:59 -0700 (PDT) Subject: Refactoring test units after an extract method In-Reply-To: <1181042991.798143.166870@k79g2000hse.googlegroups.com> Message-ID: <522282.42969.qm@web33512.mail.mud.yahoo.com> --- Virgil Dupras wrote: > How to you handle the tests? Copy over the tests you > had for foo() and > apply them to bar()? I don't like copy and pasting > code. Move the B > related tests to baz()'s tests? Then your tests > wouldn't fail if you > stopped calling baz() in foo() and bar(). > I recently had an example where class A used class B, which used class C, which used class D, which used OS service E, etc. I had mock versions of B, C, D, and E. The overall design of the module was kind of like a network stack, where each module theoretically only depended on the services of the module beneath it in the stack. So many of the tests for A used a real B, but a mock C. Many of the tests for B used a real C, but a mock D. Many of the tests for C used a real D, but a mock E. But I also wanted to test that my abstractions weren't leaky, e.g. that there weren't some implementation details of C or lower that broke A. So certain loops in my test for A would also plug in a real C. Finally, some of the test for A would also use a mock B. I was able to mostly avoid copy-and-pasting of tests by taking advantage of Python's dynamic nature. Although this is oversimplifying things a bit, you can do things like this: for b_is_mocked, c_is_mocked, d_is_mocked in [ (True, True, True), (True, True, False), (False, False, False), # etc. ] # do setup test1() test2() test3() test4() ____________________________________________________________________________________ Sick sense of humor? Visit Yahoo! TV's Comedy with an Edge to see what's on, when. http://tv.yahoo.com/collections/222 From timr at probo.com Fri Jun 1 00:51:03 2007 From: timr at probo.com (Tim Roberts) Date: Fri, 01 Jun 2007 04:51:03 GMT Subject: Is PEP-8 a Code or More of a Guideline? References: <1180236987.850208.271410@u30g2000hsc.googlegroups.com> <1180575848.698433.289180@h2g2000hsg.googlegroups.com> Message-ID: Carl Banks wrote: > >Identifiers should just allow spaces. > >first element.get item(selected value) > >This is not a joke. I don't mean Python should necessarily do this >(though it could be done without any ambiguity or backward >incompatibility: there is currently nowhere in Python where two >identifiers can be separated by only a space), but new languages >should be designed to allow it. That's an interesting idea. It would, perhaps, allow you to write programs that read more like prose. However, it would certainly make the parser more complicated, because it could no longer be context-insensitive. For example, if I had identifiers called "mine" and "not mine", how would it parse this: if not mine: -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From nagle at animats.com Wed Jun 27 17:54:36 2007 From: nagle at animats.com (John Nagle) Date: Wed, 27 Jun 2007 14:54:36 -0700 Subject: Too many 'self' in python.That's a big flaw in this language. In-Reply-To: <4682cfde$0$22416$426a74cc@news.free.fr> References: <1182942154.185461.89620@e9g2000prf.googlegroups.com> <4682cfde$0$22416$426a74cc@news.free.fr> Message-ID: Bruno Desthuilliers wrote: > Jorgen Bodde a ?crit : > >> But, what about something in between like only >> using the dot (.) for a shorter notation? How about "Mavis Beacon Teaches Typing"? John Nagle From lesande at gmail.com Thu Jun 14 05:27:20 2007 From: lesande at gmail.com (Lee Sander) Date: Thu, 14 Jun 2007 02:27:20 -0700 Subject: mapping subintervals In-Reply-To: <46706dd0$0$90262$14726298@news.sunsite.dk> References: <1181763133.202079.265790@i38g2000prf.googlegroups.com> <1181768892.265238.100290@q19g2000prn.googlegroups.com> <46706dd0$0$90262$14726298@news.sunsite.dk> Message-ID: <1181813240.936416.265440@o11g2000prd.googlegroups.com> Dear Matteo and Nis, Thankyou very much for your help. I wasn't aware of the bisect library but it's really useful. thank you both once again Lee On 13 Jun, 23:21, Nis J?rgensen wrote: > Matteo skrev: > > > OK - I'm going to assume your intervals are inclusive (i.e. 34-51 > > contains both 34 and 51). > > > If your intervals are all really all non-overlapping, one thing you > > can try is to put all the endpoints in a single list, and sort it. > > Then, you can use the bisect module to search for intervals, which > > will give you a logarithmic time algorithm. > > > Here, I'm going to assume you just need the index of the containing > > interval. If you really need a name (i.e. 'a1' or 'a2'), you can use a > > list of names, and index into that. > > > I hope those assumptions are valid! if so, the following should work: > > I have taken the liberty of simplifying your code, using the fact that > tuples are sorted lexicographically. Note that this requires all > intervals to be tuples and not lists (since list(a) < tuple(b) is always > True). > > from bisect import bisect > > def test_interval(ivl,intervals): > > # Find where ivl would lie in the list > # i.e. the index of the first interval sorting as larger than ivl > idx=bisect(intervals,ivl) > # Left endpoints equal is a special case - a matching interval will be > # to the right of the insertion point > if idx < len(intervals) and intervals[idx][0] == ivl[0]: > if intervals[idx][1] >= ivl[1]: > return idx > else: > return None > # Otherwise, we need to check to the left of the insertion point > if idx > 0 and intervals[idx-1][1] >= ivl[1]: > return idx-1 > else: > return None > > >>> intervals =[(10, 21), (34, 51), (77, 101)] > >>> print test_interval((34,35),intervals) > 1 > >>> print test_interval((34,53),intervals) > None > >>> print test_interval((77,53),intervals) > 2 > >>> print test_interval((77,83),intervals) > 2 > >>> print test_interval((77,102),intervals) > None > >>> print test_interval((77,101),intervals) > > 2 > > u"Nis J\xf8rgensen" From myddrin at myddrin.com Mon Jun 11 08:34:01 2007 From: myddrin at myddrin.com (Rob Knapp) Date: Mon, 11 Jun 2007 08:34:01 -0400 Subject: Are there any python jobs worked at home from the internet? In-Reply-To: References: Message-ID: <466D4139.3010406@myddrin.com> boyeestudio wrote: > Hi,all buddies. > Are there any python jobs worked at home from the internet? > I want to find a part time job. > Please give a clue to this for me. > Thanks a lot! This is probably going to sound like I'm telling you something you already know, but keep a close eye on the Python Job Page (http://python.org/community/jobs/). By checking it daily, I was able to find 2 part-time jobs about 2 years back. One of which has morphed into a full time job recently. Also Feedster and UKLUG () both allow you to form an RSS feed of a custom job search. I found that quite useful when I was last looking. (Although, there are quite a few dupes....) Good luck! From vinay_sajip at yahoo.co.uk Thu Jun 7 14:21:55 2007 From: vinay_sajip at yahoo.co.uk (Vinay Sajip) Date: Thu, 07 Jun 2007 11:21:55 -0700 Subject: open function fail after running a day In-Reply-To: <1181226795.455934.177550@n15g2000prd.googlegroups.com> References: <1181226795.455934.177550@n15g2000prd.googlegroups.com> Message-ID: <1181240515.747121.205730@q75g2000hsh.googlegroups.com> Try the following: import logging t=open(filename,'rb') try: data=t.read() #processing data... except: logging.exception("Failed to process %r", filename) finally: t.close() From arorap at gmail.com Tue Jun 12 11:17:15 2007 From: arorap at gmail.com (arorap) Date: Tue, 12 Jun 2007 08:17:15 -0700 Subject: cgi.FieldStorage() not working on Windows Message-ID: <1181661435.258140.17800@x35g2000prf.googlegroups.com> I've mod_php installed with Apache 2.2. In one of my folders, I'm using the cgihandler as the PythonHandler as my target host runs python only as CGI. Here cgi.FieldStorage() doesn't seem to work. I can see the form data in sys.stdin but cgi.FieldStorage() returns an empty dictionary. Here's the code for the test script I am posting to - -- #!/usr/bin/python import os import cgi import sys print "Content Type: text/plain\n\n" print "Hello CGI World !\n" for key in os.environ: print key + "= " + os.environ[key] print cgi.FieldStorage() print sys.stdin.read() -- And here's the output I see .. -- Hello CGI World ! HTTP_REFERER= http://learnpython/form.htm SERVER_SOFTWARE= Apache/2.2.4 (Win32) mod_python/3.3.1 Python/2.5.1 SCRIPT_NAME= /mptest.py SERVER_SIGNATURE= REQUEST_METHOD= POST SERVER_PROTOCOL= HTTP/1.1 QUERY_STRING= abc=ayz PATH= C:\Program Files\Internet Explorer;;C:\WINDOWS\system32;C: \WINDOWS;C:\WINDOWS\System32\Wbem;q:\bin;m:\cm\clearcase\bin;M:\PERL\NT \EXEC\BIN;m:\cm\clearcase\bin\nt;M:\Perl\NT\EXEC\BIN;m:\perl\nt\exec \bin;m:\cm\clearcase\utils;q:\bin;m:\opus;m:\tvcs;C:\highc331\bin;C: \Program Files\Rational\ClearCase\bin;C:\Program Files\Rational\common CONTENT_LENGTH= 86 HTTP_USER_AGENT= Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727) HTTP_CONNECTION= Keep-Alive SERVER_NAME= learnpython REMOTE_ADDR= 127.0.0.1 PATHEXT= .COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH SERVER_PORT= 80 SERVER_ADDR= 127.0.0.1 DOCUMENT_ROOT= D:/Projects/LearnPython/www COMSPEC= C:\WINDOWS\system32\cmd.exe SCRIPT_FILENAME= D:/Projects/LearnPython/www/mptest.py SERVER_ADMIN= puneet.arora at tekelec.com HTTP_HOST= learnpython SystemRoot= C:\WINDOWS HTTP_CACHE_CONTROL= no-cache REQUEST_URI= /mptest.py?abc=ayz HTTP_ACCEPT= */* WINDIR= C:\WINDOWS GATEWAY_INTERFACE= Python-CGI/1.1 REMOTE_PORT= 1081 HTTP_ACCEPT_LANGUAGE= en-us CONTENT_TYPE= application/x-www-form-urlencoded HTTP_ACCEPT_ENCODING= gzip, deflate FieldStorage(None, None, []) firstName=puneet&address=hawaii -- I am posting to this script using a form with two text fields named firstName and address. any clue where am I going wrong ? thanks, regards, -Puneet. From moisadoru at gmail.com Tue Jun 26 11:16:23 2007 From: moisadoru at gmail.com (Doru Moisa) Date: Tue, 26 Jun 2007 15:16:23 -0000 Subject: popen and a long running process in a wx.python application Message-ID: <1182870983.001851.156960@q75g2000hsh.googlegroups.com> Hello, How can I capture the output of a long runnning process which I open with popen() ? I tried reading line by line, char by char, but the result always comes when the process finishes. (I am trying to make a wx.python program that opens some "make ..." with popen). How can I receive the output of the program immediatly, so that I can show a progressbar in my application ? I always get the program's output after it finished executing. Is this the right place, or should I post this to wx.python ? Thank you in advance. From sportsmanhere at mail.com Tue Jun 26 01:43:15 2007 From: sportsmanhere at mail.com (Brandon) Date: Mon, 25 Jun 2007 22:43:15 -0700 Subject: Python Info. Message-ID: <1182836595.006152.87320@j4g2000prf.googlegroups.com> Check it out: www.BrandonsMansion.com From gagsl-py2 at yahoo.com.ar Thu Jun 21 21:22:00 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 21 Jun 2007 22:22:00 -0300 Subject: import mysteries References: <87sl8laxcx.fsf@grogan.peloton> Message-ID: En Thu, 21 Jun 2007 17:03:42 -0300, David Abrahams escribi?: > Another example: I was recently working on some code that did an > import from inside a class method. That import was failing. I moved > the import to the top of the file (at module scope) and it succeeded. > I'm fairly sure that nobody was monkeying around with sys.path in that > case. Can anyone think of a likely explanation? The imported module and the main script both reside on the same directory, and it is executed from there. sys.path contains '' in this case (not the full path). The script changes the current directory (os.chdir) after doing other imports and initialization. From now on, importing a module from the original directory doesn't work anymore. -- Gabriel Genellina From kyosohma at gmail.com Tue Jun 12 09:46:25 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Tue, 12 Jun 2007 06:46:25 -0700 Subject: file open default location In-Reply-To: References: Message-ID: <1181655985.895174.116540@o11g2000prd.googlegroups.com> On Jun 12, 8:42 am, "T. Crane" wrote: > Hi, > > How is the default path chosen in this instance: > > myFile = file('test.txt','w') > > Here I'm opening/creating a file but I have not specified the exact path, so > how does Python determine where to 'put' this file? More to the point, how > do I change what the default path is? Right now it's a networked drive that > should not be getting my Python clutter. > > Interestingly, this network drive is also where I can find my _ipython > folder from my ipython install as well as my .matplotlib folder. Can anyone > tell me how to change where these folders and files go by default? > > thanks for any help, > trevis When you don't specify where you want to save a file, it saves the file to the directory the script itself is run from. As far as I know, you have to specify where you want the file saved if you don't want it with the script.py Mike From dingbat at codesmiths.com Fri Jun 8 10:47:07 2007 From: dingbat at codesmiths.com (Andy Dingley) Date: Fri, 08 Jun 2007 07:47:07 -0700 Subject: Using doctest with simple text files ? Message-ID: <1181314027.659065.211070@n4g2000hsb.googlegroups.com> I have a problem involving lots of simple text files (Java properties files), for which I'm building Python tools to manage their contents. I'm also writing lots of Python modules and using doctest to embed unit tests within them. Maintenance and shhared code ownership is an issue here. What's the best way to test my file modification operations, within the context of doctest-like testing? I like the simple immediacy of doctest and it's working well for my "in-Python" testing, but I can't seem to find a simple way of integrating it with the resultant text files (e.g. something like diff) Thanks From esj at harvee.org Sun Jun 10 11:14:33 2007 From: esj at harvee.org (Eric S. Johansson) Date: Sun, 10 Jun 2007 11:14:33 -0400 Subject: Python editors again (it's not the same old request) In-Reply-To: <4866bea60706100743n39d4165fwd591ee6f2573aa61@mail.gmail.com> References: <4866bea60706100743n39d4165fwd591ee6f2573aa61@mail.gmail.com> Message-ID: <466C1559.5030004@harvee.org> Chris Mellon wrote: > wx does (in large part), but most likely the problem is that the "rich > text" control used in most editors is not the win32 rich text control, > but instead Scintilla, which is designed for source editing and is > much easier to use. Very few editors, of any kind, use the native > win32 text control for source highlighting. > > wx does have (some) support for the accessibility features in win32, > you might post a feature request on the wx bug tracker to add them to > the wx platform bindings for Scintilla. > > The main reason editors don't use the standard control is for syntax > highlighting and perhaps folding and margins, though, which I'm not > sure are especially valuable to you. What kind of features makes a > Python editor 'smart' for someone who's coding with a screen reader? what you said makes wonderful scents. Thank you for explaining. Now, if you read the application note, after the list of rich text objects they expect, they described a fuzzy in between state where if you tweak the configuration, you get Select-and-Say but you know a whole bunch of things about the objects etc. would you be so kind as to read over that part of the application note and tell me if it applies to any of the Scintilla objects for text display? I'm glad to hear you have some of the extensibility features. Some are better than none. There is an event coming up in the next few weeks that will trigger a need for accessibility interfaces on the Linux side. Well, I'm not sure about a screen reader but I'm using speech to text. My apologies if I wasn't clear (reading back, I see a couple dropouts that I didn't catch and change the meaning significantly. As a brief aside, one of the classic problems is can versus can't. Which leaves you very much in doubt if someone writes "I can go to bed with you." Is it a misrecognition or an expression of desire? only your natural language processing will know for sure:-) there's a whole hierarchy of needs. The voice coder project has done some nice work in that domain. For me, the fundamental level is the ability to correct and replace without error. I should be up to select a phrase or set of words and have that region highlighted properly so I can operate on it. I should be able to delete the last utterance and not have it count wrong. the next level (that the voice coder project handles) is the ability to dictate a word and depending on the context or its knowledge of symbols, generate a code symbol be a bumpy cap or joined with underscores or some combination thereof. Additionally, David Fox, primary developer, did some absolutely gorgeous worked with correction mechanisms. The next level up would be contextual awareness of variables within your scope so that when you dictate something, you don't have to have a big collection of static symbols. You create them dynamically based on where you are located in your code, which file, and what modules you include. This last one is going to be difficult. May not show up for a few years. But all I'm asking for right now is simple Select-and-Say as outlined in that application note from nuance. I can say "_" with English words on either side and the code will work. From scott.daniels at acm.org Sun Jun 24 22:52:26 2007 From: scott.daniels at acm.org (Scott David Daniels) Date: Sun, 24 Jun 2007 19:52:26 -0700 Subject: Inferring initial locals() In-Reply-To: <1182461716.016181.18730@k79g2000hse.googlegroups.com> References: <1182451904.703471.141000@n60g2000hse.googlegroups.com> <1182458574.630461.121290@o61g2000hsh.googlegroups.com> <1182461716.016181.18730@k79g2000hse.googlegroups.com> Message-ID: <137ube28i1f0o9d@corp.supernews.com> George Sakkis wrote: > On Jun 21, 4:42 pm, "bruno.desthuilli... at gmail.com" > wrote: >> On Jun 21, 8:51 pm, George Sakkis wrote: >> >>> I wonder if there is a (preferably not too-hackish) solution to the >>> following introspection problem: given a callable and a number of >>> positional and/or keyword arguments, infer what would be the frame's >>> locals() right after the function is called.... > > Turns out it wasn't that hard after all; I came up with the following: > .... So, what should your code do about this: def someFunction(a, b, c=43, d=14, f=12): print locals() import functools a_funct = functools.partial(someFunction, d=13, c=5) b_funct = functools.partial(a_funct, 14, d=12) localsProber(b_funct) My point is simply: Introspection code is often written with a fixed idea of what other programmers write. The others don't use introspection, the others don't use higher order functions to build functions, .... --Scott David Daniels scott.daniels at acm.org From tijs_news at bluescraper.nl Fri Jun 1 07:14:01 2007 From: tijs_news at bluescraper.nl (Tijs) Date: Fri, 01 Jun 2007 13:14:01 +0200 Subject: subexpressions References: Message-ID: <465fff79$0$325$e4fe514c@news.xs4all.nl> Steve Howell wrote: > FWIW there's the possibility that even without a > subexpression syntax, some Python implementations > would detect the duplication of x*x and optimize that > for you. It would have to know that x*x had no side > effects, which I think is a safe assumption even in a > dynamic language like Python. No, x may be an object that has the __mul__ special method, and it may have side effects. -- Regards, Tijs From gagsl-py2 at yahoo.com.ar Wed Jun 20 14:15:19 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 20 Jun 2007 15:15:19 -0300 Subject: caseless dictionary howto ? References: <4dc64$46782a84$d443bb3a$4629@news.speedlinq.nl> <4678E021.9040709@web.de> <99773$467935a8$83aef404$2584@news1.tudelft.nl> Message-ID: En Wed, 20 Jun 2007 11:11:52 -0300, stef escribi?: > Carsten Haese wrote: >> On Wed, 2007-06-20 at 11:14 +0200, stef wrote: >>> Stefan Behnel wrote: >>> Serial_HW_Read = the name of a function >>> "F" = the type of that function (procedure / function / pseudo variable >>> / interrupt /..) >>> "++" = the direction of each parameters, (input / output / >>> input+output ) >>> T = a tupple, containing the type of each of the parameters (bit / >>> byte/ >>> sbyte / word / ...) >>> >>>> maybe a class to hold them would look better), >>>> >>> maybe, but no human is looking at it ;-) >> >> But humans might look at the code that looks at the thing. >> thing.func_type is self-documenting, thing[0] is not. >> > I think you might be right, > but for a one-time/one-programmer program, > I think the documentation will be good enough. The best way would be to mix both things, using a NamedTuple (available on Python 2.6 or from http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/500261) -- Gabriel Genellina From dak at gnu.org Wed Jun 20 17:37:14 2007 From: dak at gnu.org (David Kastrup) Date: Wed, 20 Jun 2007 23:37:14 +0200 Subject: The Modernization of Emacs: terminology buffer and keybinding References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182272495.990807.99110@a26g2000pre.googlegroups.com> <87tzt3ihev.fsf@kobe.laptop> <1182370216.961241.6960@n60g2000hse.googlegroups.com> <85zm2ufjpb.fsf@lola.goethe.zz> <1182372592.803332.288260@u2g2000hsc.googlegroups.com> <1182373419.522607.14500@g4g2000hsf.googlegroups.com> <1182374902.920671.171900@k79g2000hse.googlegroups.com> Message-ID: <85ir9ifgtx.fsf@lola.goethe.zz> Twisted writes: > On Jun 20, 5:03 pm, Kaldrenon wrote: >> I still have a good deal to learn, even of the basics, but I've toyed >> with it casually for a little bit (a total of two hours at most, but >> almost certainly less) and I already know enough that finding out how >> to do anything else IS trivial. It's not a program whose controls >> throw themselves at you, exactly, but with a touch of patience and a >> genuine interest in learning, it's not too bad. > > I don't know what software you're describing, but it's obviously not > emacs, unless there have been some HUGE changes to (at minimum) the > help and pane-navigation (er, excuse me, "window"-navigation) > controls... So what version are you babbling about? -- David Kastrup, Kriemhildstr. 15, 44793 Bochum From saint at spammer.impiccati.it Wed Jun 27 04:18:14 2007 From: saint at spammer.impiccati.it (Gian Uberto Lauri) Date: Wed, 27 Jun 2007 10:18:14 +0200 Subject: The Modernization of Emacs: terminology buffer and keybinding References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182272495.990807.99110@a26g2000pre.googlegroups.com> <87tzt3ihev.fsf@kobe.laptop> <1182370216.961241.6960@n60g2000hse.googlegroups.com> <85zm2ufjpb.fsf@lola.goethe.zz> <1182372592.803332.288260@u2g2000hsc.googlegroups.com> <1182549094.366282.286740@m37g2000prh.googlegroups.com> <87bqf7fwmg.fsf@telesippa.clsnet.nl> <1182553682.197778.138500@g37g2000prf.googlegroups.com> <87r6nzc9nu.fsf@mail.eng.it> <1182904631.083783.170640@o61g2000hsh.googlegroups.com> Message-ID: <87ir9924l5.fsf@mail.eng.it> >>>>> Long count = 12.19.14.7.16; tzolkin = 2 Cib; haab = 4 Tzec. >>>>> I get words from the Allmighty Great Gnus that >>>>> "T" == Twisted writes: T> On Jun 26, 6:06 am, Gian Uberto Lauri T> wrote: >> >> > HOW IN THE BLOODY HELL IS IT SUPPOSED TO OCCUR TO SOMEONE TO >> >> ENTER > THEM, GIVEN THAT THEY HAVE TO DO SO TO REACH THE HELP >> THAT >> WOULD TELL > THEM THOSE ARE THE KEYS TO REACH THE HELP?! >> >> >> What's your problem ? >> >> >> Ofcourse a mere program-consumer would not look what was being >> >> installed on his/her system in the first place ... So after >> some >> trivial perusing what was installed and where : WOW Look, >> MA ! >> .... it's all there! >> >> >> lpr /usr/local/share/emacs/21.3/etc/refcard.ps or your >> >> install-dir........^ ^ or your >> >> version.............................^ >> n> So now we're expected to go on a filesystem fishing expedition n> instead of just hit F1? One small step (backwards) for a man; one n> giant leap (backwards) for mankind. :P T> [snipping some thinly-veiled insults and irrelevancies throughout] >> There's a program called find, not this intuitive but worth >> learning >> >> It could solve the problem from the root with something like >> >> find / -name refcard.ps -exec lpr {} \; 2> /dev/null T> Let me get this straight. T> In this corner, we have just about every Windows application ever T> developed. When a user needs help, a click on the "help" menu or T> tap of the F1 key is all it takes to obtain some. Sometimes the T> help is not of the greatest quality, but that is another issue we T> won't concern ourselves with here. Hmmm. I just activated the help hitting F1... WOHA, it says that if I press k after F1 I get the description of what that key does... T> In the other corner, we have just about every Unix application ever T> developed. When a user needs help, they may do such things as T> manually explore the directories where the application was T> installed Ever heard about the man command ? Is the first thing you learn to do... T> Or alternatively T> it can just magically come to them as a divinely inspired insight, If they are Windows user, I pity them, their brain could have been damaged beyond repair. They'll never be blessed by the idea that programs can do work for them, and will bash restlessy their keyboard in antiquate sequences of pre-automatic-controls tasks (as a reference, take a look to the Metropolis movie) T> or in a dream or a burning bush or stone tablets from heaven or T> something, that something useful might happen if the unlikely T> combination of symbols "find / -name refcard.ps -exec lpr {} \; 2> T> /dev/null" Nothing this divine. Just someone a bit more experienced than you are. On the other hand I never seen such thing like a refcard, that's not in the standard documentation system for such a modern toxic waste like Word. T> obviously never occur to them. Even if they knew the find tool and T> its syntax, it would still have to somehow occur to them that T> "refcard.ps" might be a useful search target. Strange. I am *NOT* a native english speaker and I think my Q.I. tends toward average from below, but refcard sound very useful to me, maybe is short for "reference card" ? T> came to shove, clicking Start->Search and putting in ".hlp" and T> "C:\Program Files\Appname" would quickly find any help files. I admit. find is less intuitive. But the stuff Windows comes with does just that and nothing more. It will never suggest you that the long boring task expecting you can be solved in a completely automatic way with a little creative job. T> most usually the help files would be named to end with T> .hlp. All, or that impaired of a O.S. could not understand they are help files. T> Moreover, once found, a quick double click and they're in a T> hypertext browser viewing the help. Emacs help was hypertextual when Dr. Watson plagued Windowd 3.11 users... T> Unless I miss my guess, T> refcard.ps would require mucking about installing and configuring T> Ghostscript and GSView, Splash, large miss. You usually fire it to the local printer. Uh, I understand. A Windows user could never have shared its HP720c printer... Windows printer driver aren't known to be smart. Not an Emacs flaw. T> enough. Trying to read anything serious and navigate in GSView is T> no picnic either. A refcard, my dear, is something that goes on an A4/Letter sheet and NEEDS NOT to be hypertextual. T> Reader *might* be able to do more with a .ps file With a PS file you can do just one thing, execute it. It's a program, did you know ? Ah, I never use Acroread. Xpdf does all the things really needed. Uh, I forget. For Windows users getting a PDF out of a PS or HTML or ASCII is not this easy unless they get some extra software (someone ported CUPS to Windows ?). Again, not an Emacs fault. T> On a Unix box, if you don't know exactly how to get T> some app viewing a .ps file and how to navigate in it I'm guessing T> you're SOL. Stop guessing or all will know that all you know about Unix is that is a 4 letter word, the first a capital U, the last an x. On a Unix system either YOU are the sysadmin and know about all the stuff you need to view, concot, print and bit-recycle PS files or there's a sysadmin that did this for you. All with free (as in freedom) stuff. Most Unix users thinks that Word is a typewriter on steroids not worth using due its poor output on paper, and are used to a typesetting system that deals effortlessy with PS, PDF and so on. Uh, oh, Emacs hypertextual manuals can be turned into a PS or PDF ready for a fine professional printer... T> The original suggestion with "lpr" implies printing it T> rather than viewing it online, which a) costs money and b) requires T> configuring a printer and a Postscript interpreter, given that T> unless the printer cost more than the computer's CPU it surely T> won't natively grok Postscript. I will call you if I need some advice about cars. Maybe. But not at all for computers. refcard.ps is something you print and keep on a side when you start using Emacs, as a REFERENCE for the key sequence, in the case you forget some of them. All the computer screen is devoted to your work, the sheet provides some extra "real estate" for the help information, a sort of double heading display. All you need to do is turn your eyes from the monitor, maybe your eyes and read the informations. It coudl happen that you need to flip the sheet. But you can keep both your work and the help text "ready at your fingertips", and this is useful indeed: you read the command keybinding, turn your eyes, type it and see the result and/or continue your work. Online viewing. Great deal. Flip windows until you reach refcard. Read the command. Flip again windows until you reach Emacs. Use the command (but you could have forgot the key sequence - redo from start. About money. Indeed ink/toner and paper costs. Electricity grows on the spark tree so aboundant in our forests... Configuring a printer. Yes you need to configure a printer. You need it with Windows too. But if your Windows printer driver does not handle PostScript (or if it does not let you share your printer) *now* you are SOL. PostScript printing on a Windows system that does not support PS is a pain in the ass. But PostScript printing on my '80 Epson printwriter or my HP720c with a Unix system with CUP is as easy as opening a browser, telling the system I have a HP720c plugged to the parallel port and voil?. And I can even share my HP720c. P> We're back to configuring T> Ghostscript, only this time on the Unix box where I have no doubt T> it's even more painful than it is on a Windoze box, as well as T> configuring a printer on a Unix box, itself a recurring nightmare T> of mine for years now since one night in the nineties when I got T> caught in the crossfire between someone's Epson inkjet and their T> Mandrake 7.somethingorother Linux. O poor boy. It was a job for someone else indeed. In the same time I got an HP720c and it come with no other drivers than Mac and Windows ones. I feared I was SOL when I readed of some guy that wrote a small program that was able to convert certain gs output to byte sequences good to pilot the HP720c. It was *easy* to put this program in the pipeline in the "printer driver" script. And was *easy* insert a2ps to shoot plain text directly to the printer. Before, I used an Epson pinwriter (24 pin head). Again, never had problems (unless it was dead slow). On the other hand printing directly some plain text under Windwos... T> Reexamining that "find" line it looks like it tries to T> automatically "lpr" the file(s) found. Looks like ???? Hey, it doesn't look like, it's wat it's mean to do! T> That is cause for concern, T> since I can easily see something like this going into Sorceror's T> Apprentice mode and costing you a fortune in ink and paper if T> there's either a misspelling or other mistake (easy enough to make T> in a complex arcane command line like that one) or more T> "refcard.ps" matches than you expected there'd be in the target T> directory and its descendants. You are not one good for the computers, I see. The good thing in bash is that I can use the history to recall a command line. So you can first see what find finds, and then rerun the program (search results get cached, so there's an incredible boost of speed). Second. When you learn how useful *is* find used that way, you *don't* do the mispelling or other mistakes (as a smart person, you first do the dryrun). Ah, you'll start thinking that those who find find syntax arcane are jackass... You need a little to realize it was not this easy in the beginning. The dark side of power. -- /\ ___ /___/\_|_|\_|__|___Gian Uberto Lauri_____ //--\| | \| | Integralista GNUslamico \/ e coltivatore diretto di Software A Cesare avrei detto di scrivermi a fnvag at rat.vg From jadestar at idiom.com Tue Jun 12 21:29:43 2007 From: jadestar at idiom.com (James T. Dennis) Date: Wed, 13 Jun 2007 01:29:43 -0000 Subject: how to kill a process References: <1181664061.381917.41270@a26g2000pre.googlegroups.com> Message-ID: <1181698183.818248@smirk> Richard Rossel wrote: > Hi Fellows, > I have a problem with process termination. I have a python code that > apache runs through a django interface. > The code is very simple, first, it creates a process with the > subprocess.Popen call, and afterwards, (using a web request) the > python code uses the PID of the previously created process(stored in a > db) and kills it with an os.kill call using the SIGKILL signal. > The creation of the process is ok, apache calls the python code, this > code creates the process and exits leaving the process up and > running :) > But when the python code is called to kill the created process, the > process is left in a zombie state. A zombie is an entry in the process table that stores the exit value of a deceased process. (The word is a bit of a misnomer ... and the better term would be "death certificate"). You want to do an os.wait() to clear that entry. (The process is well and truly dead after this sort of os.kill() but the system still wants the parent process to be able to retrieve the exit value and this is the Unix/Linux mechanism for storing that). > The kill code that I'm using is: > os.kill(pid, signal.SIGKILL) > and I also tried: > kill_proc = Popen("kill -9 " + pid, shell=true) > but with no success. The misunderstanding here is that you *were* successful. You have killed the process. It's dead. Nothing's left but a death certificate (or "gravestone" or "corpse" or whatever you want to call it). All that remains is for the parent to drop by the morgue (the process table) and pick up the remains. > I suppose that the reason maybe that the python code exits before the > kill call has finished, > so I tried with a while loop until kill_proc.poll() != None, but > without success too :( > do you know what is what I'm doing wrong? You are fundamentally misunderstanding the nature of the process table and the meaning of "zombie." Don't feel bad. It's a very common misunderstanding which has sadly been very poorly addressed by books on Unix systems administration and programming. > thanks very much.- Glad to help. Try this: os.kill(pid, signal.SIGKILL) killedpid, stat = os.waitpid(pid, os.WNOHANG) if killedpid == 0: print >> sys.stderr, "ACK! PROCESS NOT KILLED?" ... I'm using the "WNOHANG" flag here so that the os.waitpid() function will return a tuple of (0,0) if the process isn't dead yet. (Shouldn't be possible under these circumstances, but understanding how to do this in non-blocking mode is better than using the same code pattern in some other case and then being surprised, probably unpleasantly, when your process is blocked by the call). -- Jim Dennis, Starshine: Signed, Sealed, Delivered From steven.bethard at gmail.com Tue Jun 12 19:09:23 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 12 Jun 2007 17:09:23 -0600 Subject: SimplePrograms challenge In-Reply-To: References: Message-ID: <466F27A3.8000106@gmail.com> Steve Howell wrote: > --- George Sakkis wrote: >> from itertools import count, ifilter >> def sieve(): >> seq = count(2) >> while True: >> p = seq.next() >> seq = ifilter(p.__rmod__, seq) >> yield p [snip] > Is there a way to broaden the problem somehow, so that > it can be a longer solution and further down on the > page, and so that I can continue to enforce my > somewhat arbitrary rule of ordering examples by how > long they are? How about we just comment it better? import itertools def iter_primes(): # an iterator of all numbers between 2 and +infinity numbers = itertools.count(2) # generate primes forever while True # generate the first number from the iterator, # which should always be a prime prime = numbers.next() yield prime # lazily remove all numbers from the iterator that # are divisible by prime we just selected numbers = itertools.ifilter(prime.__rmod__, numbers) I think that's 17-ish, though you could shrink it down by removing some of the spaces. STeVe From duncan.booth at invalid.invalid Mon Jun 18 03:53:52 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 18 Jun 2007 07:53:52 GMT Subject: Trivial string substitution/parser References: Message-ID: Josiah Carlson wrote: > Samuel wrote: >> On Sun, 17 Jun 2007 11:00:58 +0000, Duncan Booth wrote: >> >>> The elegant and lazy way would be to change your specification so >>> that $ characters are escaped by $$ not by backslashes. Then you can >>> write: >>> >>>>>> from string import Template >>>>>> ... >> >> Thanks, however, turns out my specification of the problem was >> incomplete: In addition, the variable names are not known at >> compilation time. > > You mean at edit-time. > > >>> t.substitute(variable1="hello", variable2="world") > > Can be replaced by... > > >>> t.substitute(**vars) > > ...as per the standard **kwargs passing semantics. You don't even need to do that. substitute will accept a dictionary as a positional argument: t.substitute(vars) If you use both forms then the keyword arguments take priority. Also, of course, vars just needs to be something which quacks like a dict: it can do whatever it needs to do such as looking up a database or querying a server to generate the value only when it needs it, or even evaluating the name as an expression; in the OP's case it could call get_variable. Anyway, the question seems to be moot since the OP's definition of 'elegant and lazy' includes regular expressions and reinvented wheels. ... and in another message Graham Breed wrote: > def get_variable(varname): > return globals()[varname] Doesn't the mere thought of creating global variables with unknown names make you shudder? From josiah.carlson at sbcglobal.net Tue Jun 5 03:28:47 2007 From: josiah.carlson at sbcglobal.net (Josiah Carlson) Date: Tue, 05 Jun 2007 00:28:47 -0700 Subject: another thread on Python threading In-Reply-To: <1180996273.092039.91890@p47g2000hsd.googlegroups.com> References: <1180906374.041535.296410@k79g2000hse.googlegroups.com> <1180956762.091381.274750@p47g2000hsd.googlegroups.com> <1180996273.092039.91890@p47g2000hsd.googlegroups.com> Message-ID: sturlamolden wrote: > On Jun 4, 10:11 pm, Josiah Carlson > wrote: > >> However, locking isn't just for refcounts, it's to make sure that thread >> A isn't mangling your object while thread B is traversing it. > > >> With >> object locking (course via the GIL, or fine via object-specific locks), >> you get the same guarantees, with the problem being that fine-grained >> locking is about a bazillion times more difficult to verify the lack of >> deadlocks than a GIL-based approach. > > I think this is just as much a question of what the runtime should > guarantee. One don't need a guarantee that two threads are not > mangling the same object simultaneously. Instead, the runtime could > leave it to the programmer to use explicit locks on the object or > synchronized blocks to guarantee this for himself. Why? Right now we have a language where the only thing that doing silly things with threads can get you now is perhaps a deadlock, perhaps incorrect execution, or maybe some data corruption if you are working with files. If we forced all thread users to synchronize everything themselves, we get an uglier language, and incorrectly written code could potentially cause crashes (though all of the earlier drawbacks still apply). In the "safety vs. speed" or "easy vs. fast" arenas, Python has already chosen safe and easy rather than fast. I doubt it is going to change any time soon. >> It was done a while ago. The results? On a single-processor machine, >> Python code ran like 1/4-1/3 the speed of the original runtime. When >> using 4+ processors, there were some gains in threaded code, but not >> substantial at that point. > > I am not surprised. Reference counts are quite efficient, contrary to > common belief. The problem with reference counts is cyclic references > involving objects that define a __del__ method. As these objects are > not eligible for cyclic garbage collection, this can produce resource > leaks. There was a discussion about removing __del__ within the last couple weeks. I didn't pay much attention to it (having learned never to use __del__), but I believe it involved some sort of weakref-based cleanup. - Josiah From exarkun at divmod.com Sun Jun 17 11:31:43 2007 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Sun, 17 Jun 2007 11:31:43 -0400 Subject: Embedding unit tests in source files? In-Reply-To: <1182093346.170792.109970@p77g2000hsh.googlegroups.com> Message-ID: <20070617153143.4947.1352972369.divmod.quotient.2211@ohm> On Sun, 17 Jun 2007 08:15:46 -0700, Roy Smith wrote: >I'm starting a new project and am thinking of embedding my unit tests >right in the source files. I've used unittest before, and I'm happy >with it, but I've always used it with the source code in one file and >the unit tests in another. I figure if I just put a > >if __name__ == '__main__": > import unittest > blah, blah, blah > >block at the end of each source file, I'll end up with a cleaner >project structure. I can run the unit tests just by executing each >source file. Any comments from people who have organized their Python >projects this way? Did it work out well? > >It seems like what you give up is the ability to aggregate tests in a >hierarchy of test suites. In theory, that sounds like something you >might want to do, but in practice, I've never found it that useful, so >I don't think I'll miss it. > >I know about doctest, but I'm happy with unittest and don't see any >reason to change. If you do this, then all of your code will be defined one way for the test suite (in a module named __main__ - and defined twice if it happens to import anything else which tries to import it) and another way when it's actually being used in an application. This will probably have various "interesting" consequences which you'd be better off avoiding. You might be able to find a way to avoid this import behavior if you get a little creative, but I doubt it's worth the effort or the trickery. Jean-Paul From nick at craig-wood.com Fri Jun 22 05:30:05 2007 From: nick at craig-wood.com (Nick Craig-Wood) Date: Fri, 22 Jun 2007 04:30:05 -0500 Subject: configparser shuffles all sections ? References: Message-ID: stef wrote: > I just used configparser for the first time and discovered that it > shuffled all my sections, > and the contents of the sections too. > > This makes human manipulation of the file impossible. > > Is there a way to prevent this shuffling, You could try getting yourself an ordered dictionary implmentation, say http://www.voidspace.org.uk/python/odict.html Then doing something like this (untested) class MyConfigParser(SafeConfigParser): def __init__(self, defaults=None): SafeConfigParser.__init__(defaults) self._sections = odict() self._defaults = odict() -- Nick Craig-Wood -- http://www.craig-wood.com/nick From doug at alum.mit.edu Fri Jun 22 14:09:55 2007 From: doug at alum.mit.edu (Douglas Alan) Date: Fri, 22 Jun 2007 14:09:55 -0400 Subject: Python's "only one way to do it" philosophy isn't good? References: <1181368143.874341.273140@r19g2000prf.googlegroups.com> <7x3b0nmkk6.fsf@ruckus.brouhaha.com> Message-ID: "Terry Reedy" writes: > | But why is the ability to abstract syntax good? > I think this points to where Sussman went wrong in his footnote and > Alan in his defense thereof. Flexibility of function -- being able > to do many different things -- is quite different from flexibility > of syntax I think you are setting up a false dichotomy. One that is related to the false unification that annoying people used to always make when they would perpetually argue that it wasn't important which programming language you programmed in, as they are all Turing equivalent anyway. Well, I sure as hell don't want to write all my programs for a Turning machine, and a Turing machine is certainly Turing equivalent! Functionality is no good if it's too cumbersome to use. For instance, Scheme gives you first class continuations, which Python doesn't. Continuations let you do *all sorts* of interesting things that you just cannot do in Python. Like backtracking, for instance. (Well maybe you could do backtracking in Python with lots of putting code into strings and liberal use of eval, for all I know, but the results would almost certainly be too much of a bear to actually use.) Now, continuations, by themselves, in Scheme actually don't buy you very much, because although they let you do some crazy powerful things, making use of them to do so, is too confusing and verbose. In order to actually use this very cool functionality, you need macros so that you can wrap a pretty and easy-to-use face on top of all the delicious continuation goodness. You'll, just have to trust me on this one. I've written code with continuations, and I just couldn't make heads or tails out of the code a few hours later. But when prettied-up with a nice macro layer, they can be a joy to behold. |>oug From gagsl-py2 at yahoo.com.ar Wed Jun 13 21:38:35 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 13 Jun 2007 22:38:35 -0300 Subject: How can I capture all exceptions especially when os.system() fail? Thanks References: <1181782036.646379.28510@g37g2000prf.googlegroups.com> Message-ID: En Wed, 13 Jun 2007 21:47:16 -0300, mike escribi?: > Following piece of code can capture IOError when the file doesn't > exist, also, other unknown exceptions can be captured when I press > Ctrl-C while the program is sleeping(time.sleep). Now the question is: > when I run the non-exist command, the exception cannot be captured. > So far so good, then I changed the code to run a non-exist command > "wrong_command_test"(commented the open and sleep lines), then the > script printed: > sh: wrong_command_test: command not found > well Done That's because it is not an exception, it is an error message coming from your shell, not from Python. You can extract the exit status from what os.system returns (see the details on the docs for os.system); in particular, usually "command not found" is error 127 This is a list of more-or-less standard exit codes: http://www.faqs.org/docs/abs/HTML/exitcodes.html -- Gabriel Genellina From ping.nsr.yeh at gmail.com Fri Jun 15 13:55:11 2007 From: ping.nsr.yeh at gmail.com (Ping) Date: Fri, 15 Jun 2007 17:55:11 -0000 Subject: a_list.count(a_callable) ? In-Reply-To: References: <1181850818.567840.251090@x35g2000prf.googlegroups.com> <1181853479.914070.217270@i13g2000prf.googlegroups.com> <1181855184.511137.100870@z28g2000prd.googlegroups.com> <1181916937.648267.163070@z28g2000prd.googlegroups.com> Message-ID: <1181930111.491700.133290@x35g2000prf.googlegroups.com> On 6 16 , 12 33 , Carsten Haese wrote: > On Fri, 2007-06-15 at 14:15 +0000, Ping wrote: > > using sum(1 ...) to mean count() isn't very intuitive > > I find it very intuitive, but then again, my years of studying Math may > have skewed my intuition. > > > I would still prefer an expression like a_list.count(a_callable), > > which is short, clean, and easy to understand. > > Did you see my alternative example on this thread? It allows you to use > list.count in almost exactly that way, except that instead of passing > the callable directly, you pass an object that defers to your callable > in its __eq__ method. > > HTH, > > -- > Carsten Haesehttp://informixdb.sourceforge.net Yes, I read it. This works, but it may make lots of dummy classes with the special __eq__ method if I have many criteria to use for counting. I find the function design mentioned by Dustan most attractive. :) cheers, Ping From __peter__ at web.de Thu Jun 28 13:59:08 2007 From: __peter__ at web.de (Peter Otten) Date: Thu, 28 Jun 2007 19:59:08 +0200 Subject: try/except/else/finally problem References: <1387teta99gajc4@corp.supernews.com> Message-ID: Ed Jensen wrote: > I'm using: > > Python 2.3.2 (#1, Oct 17 2003, 19:06:15) [C] on sunos5 > > > And I'm trying to execute: > > #! /usr/bin/env python > > try: > f = file('test.txt', 'r') > except IOError: > print 'except' > else: > print 'else' > finally: > print 'finally' > > > And the results are: > > File "./test.py", line 9 > finally: > ^ > SyntaxError: invalid syntax > > > What am I doing wrong? You need Python 2.5 for that to work. In older Python versions you have to nest try...except...else and try...finally. Peter From no at spam.com Sun Jun 10 07:39:31 2007 From: no at spam.com (Chris) Date: Sun, 10 Jun 2007 13:39:31 +0200 Subject: userinteraction for a webspider Message-ID: <1492f$466be2e9$58422645$19939@news.usenext.de> hi guys, i would like to to write a little spider, where, occasionally, the user has to interact. For example show a log-in page or something similar (since everyone has those verification letter/number pics), or send a message by hand. I had the idea of the script relaying the page to localhost but i thought there might be an easier way... Thanks for your help Chris From jo at durchholz.org Mon Jun 11 02:42:55 2007 From: jo at durchholz.org (Joachim Durchholz) Date: Mon, 11 Jun 2007 08:42:55 +0200 Subject: The Concepts and Confusions of Prefix, Infix, Postfix and Fully Functional Notations In-Reply-To: <1181525392.369255.138460@h2g2000hsg.googlegroups.com> References: <1179936917.652372.24780@q69g2000hsb.googlegroups.com> <1180508453.226022.44230@q19g2000prn.googlegroups.com> <1181335574.107472.229370@x35g2000prf.googlegroups.com> <1181358616.792797.97720@k79g2000hse.googlegroups.com> <1181414625.121073.203940@g4g2000hsf.googlegroups.com> <0uHai.176367$nh4.13819@newsfe20.lga> <1181448558.120521.63250@g4g2000hsf.googlegroups.com> <0G_ai.1970$xg4.809@trnddc08> <1181525392.369255.138460@h2g2000hsg.googlegroups.com> Message-ID: Twisted schrieb: > After all, you can't really take a language seriously if > it's either impossible to write unmaintainable code in it That's true for any language. Substitute "not straightforward" for "impossible", and you have a condition that actually distinguishes languages. > OR impossible to write maintainable code in it. It is possible to write maintainable Perl. It's just too easy to write unmaintainable Perl. Also, a Perl "golfer" and an intermediate Perl programmer will have quite different ideas about what idioms should be considered maintainable. (I consider Perl's mantra of "many ways to express it" to be a weakness, not a strength, since it lengthens the learning curve considerably and doesn't buy much. YMMV.) Regards, Jo From vedrandekovic at v-programs.com Tue Jun 26 04:10:17 2007 From: vedrandekovic at v-programs.com (vedrandekovic at v-programs.com) Date: Tue, 26 Jun 2007 01:10:17 -0700 Subject: Installing python under the linux In-Reply-To: References: <1182800785.231113.199750@n2g2000hse.googlegroups.com> <1182802267.969628.156960@o61g2000hsh.googlegroups.com> Message-ID: <1182845417.526433.59690@c77g2000hse.googlegroups.com> Danyelle Gragsone je napisao/la: > Hi, > > Yeah .. if its ubuntu then you have python already installed. I would > suggest that you start reading the documentation on your distro. How > did you get your distro if you don't know what it is? That concerns > me a bit. Ubuntu has alot of documentation as well as a help channel > on irc. irc.freenode.net #ubuntu. You can pull up alot of > documentation by just typing "ubuntu documentation" or "ubuntu guides" > in google. > > good luck! > Danyelle > > On 6/25/07, vedrandekovic at v-programs.com wrote: > > > > Danyelle Gragsone je napisao/la: > > > Greetings, > > > > > > Python is usally already installed on most distros. In a terminal > > > window type "python" to see if something happens. Also please provide > > > what distro you are running. > > > > > > Danyelle > > > > > > On 6/25/07, vedrandekovic at v-programs.com wrote: > > > > Hello, > > > > > > > > I have problem with installing Python on the Linux platform.Can you > > > > tell me step by step how can I install > > > > python on linux ( please detailed ) , because I don't know anything > > > > about linux and I really don't understand > > > > python documentation about installing python on linux. > > > > > > > > > > > > > > > > Thanks!!! > > > > > > > > -- > > > > http://mail.python.org/mailman/listinfo/python-list > > > > > > > > Helo, > > > > Probably my distro is "ubuntu" <--- I don't what is it, and ' want > > install/build python from source > > > > -- > > http://mail.python.org/mailman/listinfo/python-list > > Hi again, This previously was very useful THANKS. I just want ask you is there, is there any folder with that basic Python on ubuntu linux where can I find file "Grammar" and change the names of python keywords. THANKS AGAIN!!!!!!!!!!!!! From lukefrancomusic at gmail.com Sun Jun 3 23:32:03 2007 From: lukefrancomusic at gmail.com (lukefrancomusic at gmail.com) Date: Mon, 04 Jun 2007 03:32:03 -0000 Subject: Error message if there is a space in the source directory In-Reply-To: References: <1180807933.269404.208750@m36g2000hse.googlegroups.com> Message-ID: <1180927923.779342.239000@q69g2000hsb.googlegroups.com> Wow, great!! That worked like a charm. Sorry about the excessive commenting, when looking it over I could see how that would be annoying. Thank you Peter! Luke From steve at laniels.org Mon Jun 25 16:20:39 2007 From: steve at laniels.org (Stephen R Laniel) Date: Mon, 25 Jun 2007 16:20:39 -0400 Subject: finding an element in a string In-Reply-To: References: Message-ID: <20070625202038.GA18906@slaniel-laptop.itasoftware.com> On Mon, Jun 25, 2007 at 04:09:50PM -0400, Miguel Oliveira wrote: > But that, obviously, will only respond "good" when one writes "fine". I was > looking for a way for the program to respond "good" to any sentence that would > contain the word "fine" in it. What you want is a regular-expression match. Are you familiar with regexes? The relevant Python documentation is here (for the module 're'): http://docs.python.org/lib/module-re.html though I find it's not particularly easy reading. The Friedl book recommended in there is the canonical source about regexes, and it is indeed a great book. You should read some manpages first, though. Just google for 'regular expressions' and you'll find all that you need. In the meantime, what you want is something like if re.search( r'fine', x ): # things one does if the user said 'fine' Alternately, you could just use rfind(): http://docs.python.org/lib/string-methods.html but regexes are a good tool to get to know. They're overused (particularly in Perl), but this is just the sort of task they're good for. -- Stephen R. Laniel steve at laniels.org Cell: +(617) 308-5571 http://laniels.org/ PGP key: http://laniels.org/slaniel.key From steven.bethard at gmail.com Wed Jun 13 02:48:09 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 13 Jun 2007 00:48:09 -0600 Subject: SimplePrograms challenge In-Reply-To: <466F8DF8.6030707@web.de> References: <1181649968.097585.131780@g37g2000prf.googlegroups.com> <87vedsua4o.fsf@merkury.smsnet.pl> <466F8DF8.6030707@web.de> Message-ID: <466F9329.2020306@gmail.com> Stefan Behnel wrote: > Steven Bethard wrote: >> If you want to parse invalid HTML, I strongly encourage you to look into >> BeautifulSoup. Here's the updated code: >> >> import ElementSoup # http://effbot.org/zone/element-soup.htm >> import cStringIO >> >> tree = ElementSoup.parse(cStringIO.StringIO(page2)) >> for a_node in tree.getiterator('a'): >> url = a_node.get('href') >> if url is not None: >> print url >> [snip] > > Here's an lxml version: > > from lxml import etree as et # http://codespeak.net/lxml > html = et.HTML(page2) > for href in html.xpath("//a/@href[string()]"): > print href > > Doesn't count as a 15-liner, though, even if you add the above HTML code to it. Definitely better than the HTMLParser code. =) Personally, I still prefer the xpath-less version, but that's only because I can never remember what all the line noise characters in xpath mean. ;-) STeVe From basilisk96 at gmail.com Sat Jun 16 23:53:26 2007 From: basilisk96 at gmail.com (Basilisk96) Date: Sun, 17 Jun 2007 03:53:26 -0000 Subject: Newbie question: how to get started? In-Reply-To: <1182049832.287814.310110@a26g2000pre.googlegroups.com> References: <2007061622483250073-user@superhoostcom> <1182049832.287814.310110@a26g2000pre.googlegroups.com> Message-ID: <1182052406.388042.179840@u2g2000hsc.googlegroups.com> On Jun 16, 11:10 pm, walterbyrd wrote: > Here are two very well regarded online books - both free: > > http://www.diveintopython.org/ > > http://www.ibiblio.org/obp/thinkCSpy/ I second that advice, especially the latter text. It's an excellent resource for any beginner in Python, whether he/she has previous programming background or not. -Basilisk96 From doug at alum.mit.edu Wed Jun 20 15:59:43 2007 From: doug at alum.mit.edu (Douglas Alan) Date: Wed, 20 Jun 2007 15:59:43 -0400 Subject: Python's "only one way to do it" philosophy isn't good? References: <1181368143.874341.273140@r19g2000prf.googlegroups.com> Message-ID: "Terry Reedy" writes: > | I think you are missing the point. Sussman is making a broad > | criticism software engineering in general, as it is understood > | today. > On the contrary, I understood exactly that and said so. *My* point > is that in doing so, he made one jab at one specific language in a > herky-jerky footnote (a sentence on systems design philosopy, one on > Python, one on physics) that I consider to be at least misleading. > And so I feel the essay would be better without that wart. The footnote is only misleading if you read it out of the context of the essay. And Sussman clearly only picked on Python, in specific, because Python is the only language for which this facet of current engineering "best practices" has been actually been eloquently committed to paper. There is nothing in the essay to suggest that Python is any worse than any other popular production programming language with respect to the issues that Sussman is addressing. > | > So Python seems to have the sort of flexibility that he implicitly > | > claims it does not. > | For instance, one of the things that he talks about exploring for > | more robust software systems is predicate dispatching, which is an > | extension of multiple dispatch. > Which I obviously read and responded to by noting "And 3.0 may add a new > generic function module to dispatch on multiple arguments and possibly > predicates." So, that's great. Python will once again adopt a wonderful feature that has been usable in Lisp implementations for 20 years now. (This is a good thing, not a bad thing. I just don't like so much the having to wait 20 years.) The problem with Python's model is that you have to wait for a rather centralized process to agree on and implement such a feature. In the Lisp community, *anyone* can easily implement such features in order to experiment with them. This allows much more experimentation to take place, which is one of the reasons why Gerry Sussman brought the scientific community into the discussion. The ability for people to readily conduct such experiments benefits me, even if I personally never want to write a macro or implement a language feature myself. Related to this is the fact that it's much harder to be able to get new language features right, unless you can get them wrong a few times first. It's no accident that when Python adds features from Lisp and Haskell, etc., that it does a pretty decent job with them, and that's because it was able to learn from the mistakes and triumphs of others who tried out various good and not-so-good language features in other languages first. The downside of Python's approach is that it makes Python not such a very good language for exploring these potentially useful features within Python in the first place. The Python community has to watch what is going on in other programming language communities and then raid these communities for their good ideas. Perhaps this is not a bad thing if people just want Python to be a programming language for getting real work done. But, personally, I would prefer to have a language that works well for *both* production work *and* for exploration. At the moment, neither Python nor Scheme fits my bill, which is why I would like to see a programming language that combines the best of both worlds. > | Although you might be able to cobble something like this together > | in Python, it would end up being very cumbersome to use. > Well, talk about shooting down innovations before they happen. > Perhaps you could wait and see what Eby and others come up with in > the next year. I was referring to implementing these sorts of features within Python (i.e., by writing Python modules in Python to support them) -- not waiting for Python 3000, which may or may not have the features that I want. > [from your other post] > | A good multimethod system, e.g., would make Python a significantly > | nicer language for my purposes, for instance. > Or better yet, read http://www.python.org/dev/peps/pep-3124/ > (tentatively approved by Guido, pending actual code) and perhaps > some of the discussion thereof on the Python-3000 dev list and help > design and code something that would be at least usable if not > 'good'. Thanks for the pointer -- I will eagerly check it out. > | You didn't read the paper very carefully. > Because I don't agree with you? No, because he clearly is not criticizing Python, in specific, and the mention of Python is due *solely* to the fact that Python just happens to mention, in one of its manifestos, a principle that would be generally held to be true as a current best engineering practice. I feel that a careful reading of the paper would have made this apparent. Also, I think it a bit counterproductive to get all up in arms about such minor jabs. Python is strong enough to withstand all sorts of valid criticism, as is Scheme. Even things that are excellent can be made better, and also the time always eventually comes, as long as human knowledge progresses, for even the greatest of artifacts to be replaced with something better. |>oug From wildemar at freakmail.de Sun Jun 3 19:16:44 2007 From: wildemar at freakmail.de (Wildemar Wildenburger) Date: Mon, 04 Jun 2007 01:16:44 +0200 Subject: subexpressions (OT: math) In-Reply-To: <4662FDC8.9080407@islandtraining.com> References: <4662675b$1_5@news.bluewin.ch> <1180890214.317409.85100@w5g2000hsg.googlegroups.com> <4662FDC8.9080407@islandtraining.com> Message-ID: <46634BDC.7090104@freakmail.de> Gary Herron wrote: > Of course not! Angles have units, commonly either degrees or radians. > > However, sines and cosines, being ratios of two lengths, are unit-less. > >> To understand it: sin() can't have dimensioned argument. It is can't >> to be - sin(meters) >> >> > No it's sin(radians) or sin(degrees). > NO! The radian is defined as the ratio of an arc of circumfence of a circle to the radius of the circle and is therefore *dimensionless*. End of story. http://en.wikipedia.org/wiki/Radian and esp. http://en.wikipedia.org/wiki/Radian#Dimensional_analysis *grunt* From millerdev at gmail.com Thu Jun 14 22:57:44 2007 From: millerdev at gmail.com (Daniel) Date: Thu, 14 Jun 2007 19:57:44 -0700 Subject: using Mac OS X CoreGraphics via ctypes Message-ID: <1181876264.097017.283110@n15g2000prd.googlegroups.com> I'm trying to implement a routine that converts a PDF document to image files using ctypes and the Apple CoreGraphics library as per the 'Splitting a PDF File' example on Apple's web site [0]. Unfortunately I cannot use the CoreGraphics module used in that example because I'm using Python 2.5 (AFAIK that module is only available in the system default Python 2.3.5). There are three questions in the code snippet below. Each problem area has been commented out in the example so it runs through to the end. The code is obviously not complete, but it's enough do demonstrate my problems so far. BTW, this is the only way I have found to convert a PDF (generated by ReportLab) to an image that can be fed into a PyQt (v3) QPrinter object. If anyone knows another way to gain access to the system print services on Mac OS X using Python please do tell. Oh yes, I'd rather not include PyObjC because I'm already packaging PyQt, and that would make the resulting app a lot bigger. # BEGIN CODE from ctypes import cdll, c_void_p from ctypes.util import find_library cglib = cdll.LoadLibrary(find_library('ApplicationServices')) # the next line causes a segfault - what's the right way to do this? #GCS_RGB = cglib.kCGColorSpaceGenericRGB() #cs = cglib.CGColorSpaceCreateWithName(GCS_RGB) # the next line causes the following error: #CGPDFDocumentRef = cglib.CGPDFDocumentRef # AttributeError: dlsym(0x1018c0, CGPDFDocumentRef): symbol not found CGPDFDocumentCreateWithProvider = cglib.CGPDFDocumentCreateWithProvider CGPDFDocumentCreateWithProvider.restype = c_void_p #CGPDFDocumentRef provider = cglib.CGDataProviderCreateWithFilename("sample.pdf") pdf = CGPDFDocumentCreateWithProvider(provider) #for page in xrange(1, pdf.getNumberOfPages() + 1): # print page # pdf.getNumberOfPages caues the following error: # AttributeError: 'int' object has no attribute 'getNumberOfPages' # I presume the 'pdf' object is a pointer. How do I get a real # CGPDFDocuemnt instance that has a getNumberOfPages method? cglib.CGPDFDocumentRelease(pdf) # END CODE [0] Splitting a PDF File Thanks in advance for any hints you can provide. ~ Daniel From steve at laniels.org Fri Jun 15 10:24:25 2007 From: steve at laniels.org (Stephen R Laniel) Date: Fri, 15 Jun 2007 10:24:25 -0400 Subject: Html parser In-Reply-To: <1181916716.258484.74070@p77g2000hsh.googlegroups.com> References: <1181916716.258484.74070@p77g2000hsh.googlegroups.com> Message-ID: <20070615142425.GC12084@slaniel-laptop.itasoftware.com> On Fri, Jun 15, 2007 at 07:11:56AM -0700, HMS Surprise wrote: > Could you recommend an html parser that works with python (jython > 2.2)? I'm new here, but I believe BeautifulSoup is the canonical answer: http://www.crummy.com/software/BeautifulSoup/ -- Stephen R. Laniel steve at laniels.org Cell: +(617) 308-5571 http://laniels.org/ PGP key: http://laniels.org/slaniel.key From doug at alum.mit.edu Sat Jun 23 12:39:51 2007 From: doug at alum.mit.edu (Douglas Alan) Date: Sat, 23 Jun 2007 12:39:51 -0400 Subject: Python's "only one way to do it" philosophy isn't good? References: <1181368143.874341.273140@r19g2000prf.googlegroups.com> <7x3b0nmkk6.fsf@ruckus.brouhaha.com> Message-ID: Steven D'Aprano writes: > Nevertheless, in Python 1+2 always equals 3. You can't say the same thing > about Lisp. Well, I can't say much of *anything* about "1 + 2" in Lisp, since that's not the syntax for adding numbers in Lisp. In Lisp, numbers are typically added using the "+" function, which might be invoked like so: (+ 1 2 3) This would return 6. It's true that some dialects of Lisp will let you redefine the "+" function, which would typically be a bad idea. Other dialects would give you an error or a warning if you tried to redefine "+". I would fall more into the latter camp. (Though sometimes you might want a way to escape such restrictions with some sort of "yes, I really want to shoot myself in the head" declaration, as you may want to experiment, not with changing the meaning of "(+ 1 2"), but rather with adding some additional useful capability to the "+" function that it doesn't already have. Back on the Python front, although "1 + 2" might always equal 3 in Python, this is really rather cold comfort, since no useful code would ever do that. Useful code might include "a + 1", but since you can overload operators in Python, you can say little about what "a + 1" might do or mean on the basis of the syntax alone. Furthermore, in Python you can redefine the "int" data type so that int.__add__ does a subtraction instead. Then you end up with such weirdness as >>> int(1.0) + int(2.0) -1 Also, you can redefine the sum() function in Python. So, we see that Python offers you a multitude of ways to shoot yourself in the head. One of the things that annoys me when coding in Python (and this is a flaw that even lowly Perl has a good solution for), is that if you do something like longVarableName = foo(longVariableName) You end up with a bug that can be very hard to track down. So one use for macros would be so that I can define "let" and "set" statements so that I might code like this: let longVariableName = 0 set longVarableName = foo(longVariableName) Then if longVarableName didn't already exist, an error would be raised, rather than a new variable being automatically created for me. The last time I mentioned this, Alex Martelli basically accused me of being an idiot for having such trivial concerns. But, ya know -- it isn't really a trivial concern, despite Martelli's obviously high intellect. A woman I work with who is bringing up a CMS using Drupal was complaining to me bitterly that this very same issue in PHP was causing her bugs that were hard to track down. Unfortunately, I could not gloat over her with my Python superiority, because if Drupal were written in Python, rather than PHP, she'd have the very same problem -- at least in this regard. |>oug From matt-python at theory.org Tue Jun 19 16:00:21 2007 From: matt-python at theory.org (Matt Chisholm) Date: Tue, 19 Jun 2007 13:00:21 -0700 Subject: labeled break/continue In-Reply-To: References: Message-ID: <20070619200021.GG26884@theory.org> On Mon, 18 Jun 2007 05:28, faulkner wrote: >On Jun 18, 12:35 am, Matt Chisholm wrote: >> Hi. I was wondering if there had ever been an official decision on >> the idea of adding labeled break and continue functionality to Python. > >python-dev just mentioned that the BDFL vetoed it a while ago. >they're writing a PEP just to document why it was vetoed. > Really? I can't find anything in the python-dev archives, or in the list of PEPs. Does anyone know the PEP number (if one has been assigned)? Or maybe someone could send me a link to the discussion or forward the discussion to me off list? That would be much appreciated. -matt From bignose+hates-spam at benfinney.id.au Tue Jun 19 20:40:00 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 20 Jun 2007 10:40:00 +1000 Subject: Using a switch-like if/else construct versus a dictionary? References: <1182282008.522677.269730@g4g2000hsf.googlegroups.com> Message-ID: <87645jzcf3.fsf@benfinney.id.au> asincero writes: > def foo(): > def doCase1(): > pass > def doCase2(): > pass > def doCase3(): > pass > def doCase4(): > pass > def doCase5(): > pass > > handle_case = {} > handle_case[1] = doCase1() > handle_case[2] = doCase2() > handle_case[3] = doCase3() > handle_case[4] = doCase4() > handle_case[5] = doCase5() > handle_case[c]() (The above code is wrong. You want the dictionary to map to functions, not to the result of calling those functions; the call to the function comes later.) Why not construct the dictionary in one step? :: handle_case = { 1: do_case_1, 2: do_case_2, 3: do_case_3, 4: do_case_4, 5: do_case_5, } handle_case[c]() You could even perform the lookup and function call in the same statement as creating the dictionary, but I prefer the above form for its readability. > Note that in this situation using OO polymorphism instead of a switch- > like construct wouldn't be applicable, or at least I can't see how it > could be. I'm not sure what you mean. What would you apply polymorphism to, and what would be the desired result? -- \ "I used to work in a fire hydrant factory. You couldn't park | `\ anywhere near the place." -- Steven Wright | _o__) | Ben Finney From ask at me Sat Jun 9 13:04:09 2007 From: ask at me (alf) Date: Sat, 09 Jun 2007 12:04:09 -0500 Subject: launching default browser In-Reply-To: <466987dc$0$27396$ba4acef3@news.orange.fr> References: <466987dc$0$27396$ba4acef3@news.orange.fr> Message-ID: Laurent Pointal wrote: > > Via webbrowser module > > http://docs.python.org/lib/module-webbrowser.html > thx a lot. Just again Python positively surprises me. > (note: its in top five in google search for Python + launch + browser...) so now it will be in top four :-). From tjollans at googlemail.com Sun Jun 3 17:11:24 2007 From: tjollans at googlemail.com (tjollans@g-NOSPAM-mail.com) Date: Sun, 03 Jun 2007 21:11:24 -0000 Subject: WSGI/wsgiref: modifying output on windows ? Message-ID: <1180905084.438849.326640@m36g2000hse.googlegroups.com> Hi, I am currently trying to port my web software AFoC to Windows and have hit a strange problem: it seams that binary files (PNG images in this case) get distorted by wsgiref. (I have tried both the CGIHandler with both Xitami and Apache2 and WSGIServer). My application is returning a list of one item (the image as a string). The image is intact at that point. (tested by writing it to disk and comparing); The client gets a version with a few added \r characters and something missing at the end, but of the same overall length. Here are specific examples: >>> f1 = file('afoc_bak', 'rb') >>> f2 = file('box_top.png', 'rb') >>> s1 = f1.read() >>> s2 = f2.read() >>> s1 == s2 False >>> s1 "\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR \x00\x00\x00\x96\x00\x00\x00\x14\x08\x06\x00 \x00\x00oy\xc41\x00\x00\x00\x04sBIT\x08\x08\x08\x08|\x08d \x88\x00\x00\x00\x19tEX tSoftware\x00www.inkscape.org\x9b\xee<\x1a\x00\x00\x01\x95IDATh\x81\xed \xd9?K#A\ x18\xc7\xf1\xef\xecnv\xb3FQA\x8b\xf3@\xc1?\xe0)*\xda\xd9(v\xd7+r \xb6\x82\xef\xc3 \xce\x17\xe1\xab\xb0\x15k\x0b\x1b\x1b\xe1@\x8eK\xa1\x85\x044F \x8d1\x9a8\x16\x93\ x80\xc4F]u\x89\xfc>\xcd\xb0\x0fS<\xc5\x8fyfw\x8d\xb5\x16\x91\x8f \xe6\xa5\xdd\x80 |O\n\x96|\n\x05K>\x85\x01\x06\xd2nB\xda\xc6\xe3\xb3\xb5\x06<\x00Uk\xed} \xeb\xc6\ x00\xf8\xf1\x85\x8dI{\xab7\xd6f\xb0\xee\x81\xaa1\xa6\x02\x94\xad \xb5\x95\xe6\xc6 \x00\x9dX\xf2zU\xc0\xc7\x05\xac\xd6x\xbe\x03n\x81\xd8\x18s\x03\\Yk\xeb: \xb1\xe4- n\x80\x08\x17\xac\x07\\\xb0n\x812\x90\x05B\xc07\xc6\x94\x82\xf9\xa5\xad \xb5\xd4\ xda\x94\xb6\xe0y\xbe\x0fP*\xfe?>\xc9\xef\x15J\xc5\x7f\x97\xb81x \x87\x0bUL#T\xb8{ \xbb5\xab\xeb\x07\xfaB*oR)\x17\xce\x8f\x0e\xb7w\xf3\xc7;\x7f\x81k \xe0\n(\x01\x97 @\x11\xb8\xf0'g76S\xecQ\xdaP&\xccu\xfc\x1c\\\x98\n\xa3n\xef\xect\xbf \xd0([\xdc\x a5\xbe\x0e\xd4\xf4\x1dK\xdem\xf4\xd7\xca\xc2\xc8\xf8\xf24\xd0\x05t \x02\x1d\xb8\x b1\x18+X\xf2n\xc6xfbf}\x11\x17\xa8,\xeeb\x1f\x01\xa1\x82% \x89\xc4\xb9\xfe\x9e\xb 1\xc9?\x11\xee2_\xc7\x8dC\xab`IbC\xc3\xbf\xe7p\xa3\xb0\xf9f\xa8\x7f \x85\x92\\\x9 4\xed\xedk\xad)X\x92X&\xcc\xf5\xb6\xd6\x14,I,\x08\xe2\x9e\xd6\x9a\x82% \x89y~&\xf b\xa2\x96F#\xf2\xfd=\x01\x19c^\xe3KN&\x89\x00\x00\x00\x00IEND\xaeB` \x82" >>> s2 "\x89PNG\r\r\n\x1a\r\n\x00\x00\x00\rIHDR \x00\x00\x00\x96\x00\x00\x00\x14\x08\x06 \x00\x00\x00oy\xc41\x00\x00\x00\x04sBIT\x08\x08\x08\x08|\x08d \x88\x00\x00\x00\x1 9tEXtSoftware\x00www.inkscape.org\x9b\xee<\x1a\x00\x00\x01\x95IDATh \x81\xed\xd9? K#A\x18\xc7\xf1\xef\xecnv\xb3FQA\x8b\xf3@\xc1?\xe0)*\xda\xd9(v\xd7+r \xb6\x82\xef \xc3\xce\x17\xe1\xab\xb0\x15k\x0b\x1b\x1b\xe1@\x8eK\xa1\x85\x044F \x8d1\x9a8\x16\ x93\x80\xc4F]u\x89\xfc>\xcd\xb0\x0fS<\xc5\x8fyfw\x8d\xb5\x16\x91\x8f \xe6\xa5\xdd \x80|O\r\n\x96|\r\n\x05K>\x85\x01\x06\xd2nB\xda\xc6\xe3\xb3\xb5\x06< \x00Uk\xed}\ xeb\xc6\x00\xf8\xf1\x85\x8dI{\xab7\xd6f\xb0\xee \x81\xaa1\xa6\x02\x94\xad\xb5\x95 \xe6\xc6\x00\x9dX\xf2zU\xc0\xc7\x05\xac\xd6x\xbe\x03n\x81\xd8\x18s\x03\ \Yk\xeb:\ xb1\xe4-n\x80\x08\x17\xac\x07\\\xb0n\x812\x90\x05B \xc07\xc6\x94\x82\xf9\xa5\xad\ xb5\xd4\xda\x94\xb6\xe0y\xbe\x0fP*\xfe?>\xc9\xef\x15J\xc5\x7f\x97\xb81x \x87\x0bU L#T\xb8{\xbb5\xab\xeb\x07\xfaB*oR)\x17\xce\x8f\x0e\xb7w\xf3\xc7;\x7f \x81k\xe0\r\ n(\x01\x97@\x11\xb8\xf0'g76S\xecQ\xdaP&\xccu\xfc\x1c\\\x98\r\n\xa3n\xef \xect\xbf \xd0([\xdc\xa5\xbe\x0e\xd4\xf4\x1dK\xdem\xf4\xd7\xca \xc2\xc8\xf8\xf24\xd0\x05t\x 02\x1d\xb8\xb1\x18+X\xf2n\xc6xfbf}\x11\x17\xa8,\xeeb\x1f\x01\xa1\x82% \x89\xc4\xb 9\xfe\x9e\xb1\xc9?\x11\xee2_\xc7\x8dC\xab`IbC\xc3\xbf\xe7p\xa3\xb0\xf9f \xa8\x7f\ x85\x92\\\x94\xed\xedk\xad)X\x92X&\xcc\xf5\xb6\xd6\x14,I,\x08\xe2\x9e \xd6\x9a\x8 2%\x89y~&\xfb\xa2\x96F#\xf2\xfd=\x01\x19c^\xe3KN& \x89\x00\x00\x00\x00IE" >>> a thought that springs to mind is that this may be related to the barmy DOS relic of binary/ASCII file destinction; however, this should not be a problem if I understand PEP 333 correctly: """The server or gateway should treat the yielded strings as binary byte sequences: in particular, it should ensure that line endings are not altered.""" Might this be a bug in wsgiref ? I will hopefully be able to do some more testing, e.g. with the FLUP FastCGI back-end, in the next few days. Kind regards, Thomas Jollans From evan at yelp.com Thu Jun 21 00:20:29 2007 From: evan at yelp.com (Evan Klitzke) Date: Wed, 20 Jun 2007 21:20:29 -0700 Subject: Downloading from a clean url In-Reply-To: <1182392457.751054.173500@n60g2000hse.googlegroups.com> References: <1182392457.751054.173500@n60g2000hse.googlegroups.com> Message-ID: On 6/20/07, D.Hering wrote: > General: > How do I download a page's data from a clean url. > > Specific: > I'm using PyQt's QHttp and QUrl classes for requests and acquiring the > response, but I can't figure out how to access a page's data without > knowing the file of the url's path. For instance http://kde.org If the page is omitted, as in your example of http://kde.org, the page is / -- Evan Klitzke From http Fri Jun 29 11:59:16 2007 From: http (Paul Rubin) Date: 29 Jun 2007 08:59:16 -0700 Subject: 16bit hash References: <46833DC0.3050503@v.loewis.de> Message-ID: <7xlke23g6j.fsf@ruckus.brouhaha.com> Robin Becker writes: > whether it's any better than using the lowest bits I have no real > idea. I suppose (sha being flavour of the month) I should really use I think if you have more than a few fonts you really have to assign the id's uniquely instead of using hashes, to avoid collisions. From wicijowski at gmail.com Thu Jun 7 06:26:07 2007 From: wicijowski at gmail.com (janislaw) Date: Thu, 07 Jun 2007 03:26:07 -0700 Subject: Beginning Python In-Reply-To: <1181053786.724436.132900@n15g2000prd.googlegroups.com> References: <1181053786.724436.132900@n15g2000prd.googlegroups.com> Message-ID: <1181211967.846904.312950@q69g2000hsb.googlegroups.com> On Jun 5, 4:29 pm, abhiee wrote: > Hello , I have just begun learning python...and I'm loving it...Just > wanted to ask you that how much time would it take me to learn python > completely and which languages should i learn alongwith python to be a > good professional programmer?...Now i only know C.... > thanx in advance! Then Lisp is a must-know to you. From gagsl-py2 at yahoo.com.ar Sun Jun 10 02:47:25 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 10 Jun 2007 03:47:25 -0300 Subject: urllib2 - iteration over non-sequence References: <1181427526.996101.75230@m36g2000hse.googlegroups.com> <466B2AA7.3040704@websafe.com> <1181429903.533207.105730@p77g2000hsh.googlegroups.com> <7x3b10pnwq.fsf@ruckus.brouhaha.com> Message-ID: En Sun, 10 Jun 2007 02:54:47 -0300, Erik Max Francis escribi?: > Gary Herron wrote: > >> Certainly there's are cases where xreadlines or read(bytecount) are >> reasonable, but only if the total pages size is *very* large. But for >> most web pages, you guys are just nit-picking (or showing off) to >> suggest that the full read implemented by readlines is wasteful. >> Moreover, the original problem was with sockets -- which don't have >> xreadlines. That seems to be a method on regular file objects. >> > There is absolutely no reason to read the entire file into memory (which > is what you're doing) before processing it. This is a good example of > the principle of there is one obvious right way to do it -- and it isn't > to read the whole thing in first for no reason whatsoever other than to > avoid an `x`. The problem is -and you appear not to have noticed that- that the object returned by urlopen does NOT have a xreadlines() method; and even if it had, a lot of pages don't contain any '\n' so using xreadlines would read the whole page in memory anyway. Python 2.2 (the version that the OP is using) did include a xreadlines module (now defunct) but on this case it is painfully slooooooooooooow - perhaps it tries to read the source one character at a time. So the best way would be to use (as Paul Rubin already said): for line in iter(lambda: f.read(4096), ''): print line -- Gabriel Genellina From fdu.xiaojf at gmail.com Wed Jun 13 03:28:17 2007 From: fdu.xiaojf at gmail.com (fdu.xiaojf at gmail.com) Date: Wed, 13 Jun 2007 15:28:17 +0800 Subject: questions about solving equations in scipy In-Reply-To: References: <466ED410.2010507@gmail.com> Message-ID: <466F9C91.6000009@gmail.com> Hi Robert, Thanks a lot for your kindness. Robert Kern wrote: > fdu.xiaojf at gmail.com wrote: >> Hi all, >> >> I have two questions about scipy. > > You're likely to get a better response from the scipy mailing list. Here, you'll > primarily get me, and I have to rush out right now. > > http://www.scipy.org/Mailing_Lists In fact, I have tried to subscribe to the list, but got no response. I will try again. > >> 1) When I was trying to solve a single variable equations using scipy, I >> found two methods: scipy.optimize.fsolve, which is designated to find the >> roots of a polynomial, > > No, it finds the roots of a non-linear system of N functions in N variables. The > documentation makes no mention of polynomials. > >> and scipy.optimize.newton, which is used for Scalar >> function root finding according to the help(). > > There's also brentq, brenth, ridder, and bisect for this problem. > >> I have tried both, and it seemed that both worked well, and fsolve ran >> faster. >> >> My questions is, which is the right choose ? > > Whichever one works faster and more robustly for your problem. fsolve is > implemented in FORTRAN, which sometimes helps. I do recommend looking at the > brentq and brenth if you can provide bounds rather than just an initial guess. "brentq" or "brenth" are used to find a zero of the function f between the argument a and b. It demanded that f(a) and f(b) can not have the same signs. I think it is very convenient to provide valid a and b before I've got the solution of the function. > >> 2) I have to solve a linear equation, with the constraint that all >> variables should be positive. Currently I can solve this problem by >> manually adjusting the solution in each iteration after get the solution >> bu using scipy.linalg.solve(). >> >> Is there a smart way ? > > I don't think that's a well-defined problem. Either the (unique) solution is I found a web page about optimization solver in openoffice( http://wiki.services.openoffice.org/wiki/Optimization_Solver#Non-Linear_Programming). Openoffice has an option of "Allow only positive values", so I think that's a well-defined problem. Sorry for my ignorance if I was wrong. > within the constraint or it's not. Are you sure you don't want to find the > minimum-error solution that obeys the constrain, instead? Yes, I do want to find the minimum-error solution that obeys the constrain. Please tell me more ! Regards, Xiaojf From jjl at pobox.com Thu Jun 21 19:39:50 2007 From: jjl at pobox.com (John J. Lee) Date: Thu, 21 Jun 2007 23:39:50 GMT Subject: Indenting in Emacs References: <1182415666.423187.274240@u2g2000hsc.googlegroups.com> Message-ID: <87bqf8nagp.fsf@pobox.com> Eugene Morozov writes: > Steven W. Orr ?????: > > Ok. I'm not stupid but I do not see a 4.78 anywhere even though I > see refs >> from google. I have 4.75 The SVN tree doesn't seem to even have >> that. >> >> I checked the latest copy out from sourceforge and that was 4.75 too. >> >> Can someone please tell me where to find the latest? >> > > It's from Emacs 22. Note that's a different python-mode to the old one that lives on SF. Yes, there are now two of them. John From nospam at nowhere.com Tue Jun 26 17:56:38 2007 From: nospam at nowhere.com (DavidM) Date: 27 Jun 2007 09:56:38 +1200 Subject: simplifying algebraic expressions References: <46805dae$1@news.orcon.net.nz> <4680f325@news.orcon.net.nz> <1182856943.974861.10070@q75g2000hsh.googlegroups.com> Message-ID: <46818b96$1@news.orcon.net.nz> On Tue, 26 Jun 2007 04:22:23 -0700, Mark Westwood wrote: > I'm with Robin Becker on this one, if GP is good enough for your > problem, then the answers it produces should be good enough. Set the > fitness criteria in favour of shorter rather than longer expressions > and let you system run a little longer. Thanks for your comments. I tried this and came up with some very interesting results. In the fitness function, I added a multiplier: badness *= numnodes Where 'badness' is the calculated fitness (always >0, lower is better), and 'numnodes' is the number of nodes in the program tree. Result? The population never evolved past a certain point, and problem never got solved. So I tried to make the multiplier more gentle: badness *= math.log(1 + numnodes) Same result. Tried even more gentle: badness *= math.pow(numnodes, 1.0/12) That is, multiply badness by the twelfth root of the number of nodes. Population evolved better, but still didn't breed a winning organism. Finally, I set a threshold, and only punished organisms if they exceeded this complexity threshold: if numnodes > threshold: badness *= math.pow(numnodes - threshold, 1.0/12) That worked. Seems that I have to allow a 'punishment free' threshold of complexity, otherwise the population stagnates. Cheers David From saint.infidel at gmail.com Wed Jun 13 17:34:57 2007 From: saint.infidel at gmail.com (infidel) Date: Wed, 13 Jun 2007 14:34:57 -0700 Subject: SimplePrograms challenge In-Reply-To: References: <1181602284.131343.145200@i38g2000prf.googlegroups.com> Message-ID: <1181770497.413156.139170@j4g2000prf.googlegroups.com> # writing/reading CSV files, tuple-unpacking, cmp() built-in import csv writer = csv.writer(open('stocks.csv', 'wb')) writer.writerows([ ('GOOG', 'Google, Inc.', 505.24, 0.47, 0.09), ('YHOO', 'Yahoo! Inc.', 27.38, 0.33, 1.22), ('CNET', 'CNET Networks, Inc.', 8.62, -0.13, -1.49) ]) stocks = csv.reader(open('stocks.csv', 'rb')) for ticker, name, price, change, pct in stocks: print '%s is %s (%s%%)' % ( name, {-1: 'down', 0: 'unchanged', 1: 'up'}[cmp(float(change), 0.0)], pct ) From Hrusikesa.Patro at aricent.com Thu Jun 7 09:22:20 2007 From: Hrusikesa.Patro at aricent.com (Hrusikesa Patro) Date: Thu, 7 Jun 2007 18:52:20 +0530 Subject: FTPLIB fails to retreive the remote file Message-ID: Hi All, I'm trying to download a remote file through FTP. Here's the script: ############################################################### #!/usr/bin/env python import ftplib import os import time ddir="C:\\ftp" os.chdir(ddir) f=ftplib.FTP("10.2.2.1", "user", "user123") f.cwd("/home/protocol/cccdb/dumps/") # define filename day=time.strftime("%Y.%d.%m") file2="mq20-%s-cdbdump.xml.md5" % (day) #To debug pwd = f.pwd() print pwd print file2 # get the remote file to the local directory f.retrbinary('RETR %s' % file2, open(file2,"wb").write) f.close() ############################################################### *Output:* >>> execfile("ftp.py") /home/protocol/cccdb/dumps mq20-2007.07.06-cdbdump.xml.md5 Traceback (most recent call last): File "", line 1, in ? File "ftp.py", line 44, in ? f.retrbinary('RETR %s' % file2, open(file2,"wb").write) File "t:\Python23\lib\ftplib.py", line 379, in retrbinary conn = self.transfercmd(cmd, rest) File "t:\Python23\lib\ftplib.py", line 345, in transfercmd return self.ntransfercmd(cmd, rest)[0] File "t:\Python23\lib\ftplib.py", line 324, in ntransfercmd conn.connect(sa) File "", line 1, in connect socket.error: (10060, 'Operation timed out') >>> What's gone wrong? Rgs, Hrusi *********************** Aricent-Unclassified *********************** "DISCLAIMER: This message is proprietary to Aricent and is intended solely for the use of the individual to whom it is addressed. It may contain privileged or confidential information and should not be circulated or used for any purpose other than for what it is intended. If you have received this message in error, please notify the originator immediately. If you are not the intended recipient, you are notified that you are strictly prohibited from using, copying, altering, or disclosing the contents of this message. Aricent accepts no responsibility for loss or damage arising from the use of the information transmitted by this email including damage from virus." -------------- next part -------------- An HTML attachment was scrubbed... URL: From nospam at nowhere.com Mon Jun 25 06:51:13 2007 From: nospam at nowhere.com (DavidM) Date: 25 Jun 2007 22:51:13 +1200 Subject: ANN: YahooQuote 0.1.0 Message-ID: <467f9e21$1@news.orcon.net.nz> Hi, After a 3-year break from working with it, I've just released version 0.1.0 (the first formally packaged release) of YahooQuote. As the name implies, it's a stockmarket prices fetcher. Features: - easily fetch stock price quotes and histories - fetch bulk histories across one or more of the major stockmarket indexes - fast efficient automatic caching via a MetaKit database - pleasant object-oriented interface - thorough epydoc-generated API doco - simple examples This supersedes the unpackaged YahooQuote module of 2004, and brings YahooQuote up to date with the present Yahoo Finance web interface. http://www.freenet.org.nz/python/yahooquote License: LGPL Enjoy Cheers David From jadestar at idiom.com Sun Jun 10 15:54:59 2007 From: jadestar at idiom.com (James T. Dennis) Date: Sun, 10 Jun 2007 19:54:59 -0000 Subject: need help with python References: <1178934447.719778.197150@h2g2000hsg.googlegroups.com> <1178937249.263856.191460@p77g2000hsh.googlegroups.com> <1178937707.004412.22360@q75g2000hsh.googlegroups.com> <1178939773.253366.79710@h2g2000hsg.googlegroups.com> <1178941040.442541.61840@n59g2000hsh.googlegroups.com> Message-ID: <1181505299.706812@smirk> adamurbas at hotmail.com wrote: > On May 11, 10:16 pm, Paul McGuire wrote: >> On May 11, 9:41 pm, adamur... at hotmail.com wrote: [... much ellided ...] ["ellided" is a fancy word for "left out" or "replaced with ellipses."] > I was looking around in my Python folder and saw something to do with > that IDLE thing you were talking about. When I right clicked on a .py > file, it said edit with IDLE. I opened it and it was my code but each > line was a different color. It looked confusing so I decide to save > it for later. I knew that I could get the run thing to do the command > thing, but I had forgotten how to get the black window to come up. Idle is an "IDE" (integrated development environment). It's sort of like an editor and a "terminal window" ("command shell") combined. The different colors are the result of a feature called "syntax highlighting" which is available in most of the modern IDEs and better text editors. To "get the black window to come up" use the [Start] menu, choose the "Run" option and type in the name of the program: "cmd" (then hit [Enter]). You can can also find it if you chase far enough down the various sub-menus off the [Start] menu. > Ok. Well, I tried to us the cmd window. It says python: can't open > file 'area.py' I'm guessing that's not good. It won't open any of > my .py files. It's because of where I saved them. I can see how this > i going to work now. Ok so I'll just move them to the place that the > command line says. Now it still won't run my other program: Yes it's because of where you saved them and because of where the command prompt (The C:\> thing that you see inside the "terminal window"). Rather than moving your .py files to wherever your prompt is pointing, it's generally better to change your prompt to point to the right place. For example if you've been saving you .py files to "C:\My Documents" then type: cd "\My Documents" ... (with the quotes around it). Then try to run your files from there. > # Area calculation program > print "Welcome to the Area calculation program" > print "-------------" > print > # Print out the menu: > print "Please select a shape:" > print "1 Rectangle" > print "2 Circle" > # Get the user's choice: > shape = input("> ") > # Calculate the area: > if shape == 1: > height = input("Please enter the height: ") > width = input("Please enter the width: ") > area = height*width > print "The area is", area > else: > radius = input("Please enter the radius: ") > area = 3.14*(radius**2) > print "The area is", area > Perhaps it isn't written correctly. I don't think it likes the pound > signs. I'm not sure. But, I did go to that mailing list you > recommended. Thanks for that. The pound signs are used by Python to mark "comments" (stuff the Python interpreter ignores; that's there just as hints and reminders to humans who are reading the source code). So, from the first # sign on a line until the end of the line Python is ignoring everything. The only exceptions to this rule are when the # is inside quotes: print "This is technically called an octothorpe: #. See?" ... in that line the octothorpe (#) is part of a quoted string so it and the text following it are NOT ignored. Incidentally, I would use the raw_input() function in place of the input() function that these examples have been using. The problem with the Python input() function is that it parses the input as if it were Python code. So it will raise an exception for any input you enter which is NOT valid, legal Python code. (So far you've been lucky in that you've only been using it to enter simple numbers, which are, of course, valid Python expressions. You can actually get away with inserting one line: input = raw_input ... near the beginning of any of your code examples to alleviate this issue. The raw_input() function will accept any string you can enter up to the first [Enter] key. (Actually on my platform, Linux, it's possible to embed newline and/or carriage return characters --- the ASCII characters which are normally generated by the [Enter] key on various computing platforms --- into a raw_input() value by preceding each of them with a Ctrl-V key. Just off hand I don't know if that works under Windows using a command prompt window. Just pointing that out for other readers to make the observation that Python's raw_input() might not be as "raw" as you might expect). -- Jim Dennis, Starshine: Signed, Sealed, Delivered From jeremiah.foster at gmail.com Tue Jun 12 12:51:36 2007 From: jeremiah.foster at gmail.com (miah_gbg) Date: Tue, 12 Jun 2007 16:51:36 -0000 Subject: Article on wxPython ToolKit for Mac OS X In-Reply-To: References: <1178204986.383057.264690@y80g2000hsf.googlegroups.com> Message-ID: <1181667096.795272.219480@z28g2000prd.googlegroups.com> On May 3, 9:46 pm, James Stroud wrote: > miah_gbg wrote: > > Hi there! > > > Just wanted to let people know in this group that I have recently > > (April 24th) published an introductory article on wxPython and Mac OS > > X. It is available here:http://www.macdevcenter.com/ > > > Hope someone finds it useful. > > > Regards, > > > Jeremiah > > Nice article, but it has an inaccuracy: > > "The first thing we need to do is download wxPython so we can begin > creating applications." > > This is not entirely correct. The stock 10.4 that came in a G5 bought in > June has wx built-in: > > cabin % /usr/bin/python > Python 2.3.5 (#1, Oct 5 2005, 11:07:27) > [GCC 3.3 20030304 (Apple Computer, Inc. build 1809)] on darwin > Type "help", "copyright", "credits" or "license" for more information. > >>> import wx > >>> > > Of course the stock python is 2.3, but its very cool that one can depend > on wx being present on 10.4+ machines. So there is no need to bundle > python/wx with your app when developing for Macs. (Yes, I noticed the > author is running OS X 10.3.) > > James Wow. That is cool. I didn't know that. Jeremiah From jon+usenet at unequivocal.co.uk Wed Jun 27 18:19:05 2007 From: jon+usenet at unequivocal.co.uk (Jon Ribbens) Date: 27 Jun 2007 22:19:05 GMT Subject: 16bit hash References: Message-ID: On 2007-06-27, Robin Becker wrote: > Is the any way to get an efficient 16bit hash in python? int(md5.new(s).hexdigest()[:4], 16) ? From hat at se-162.se.wtb.tue.nl Wed Jun 27 10:37:50 2007 From: hat at se-162.se.wtb.tue.nl (A.T.Hofkamp) Date: Wed, 27 Jun 2007 16:37:50 +0200 Subject: Too many 'self' in python.That's a big flaw in this language. References: <1182942154.185461.89620@e9g2000prf.googlegroups.com> Message-ID: On 2007-06-27, hide1713 at gmail.com wrote: > HI > I'm currently using Python. I find that a instance variable must > confined with self, > for example: > class a: > def __init__(self): > self.aa=10 > def bb(self): > print self.aa # See .if in c++,I could use aa to change that > variable c++ is a much more static language (for example, you cannot create new fields in your class at run time), so it can decide in advance what you mean. In other words, it is a cost you pay for the increased flexibility. You may not be using that flexibility, but it is there, and people use it. > That's a big inconvenience in coding ,especially when you have lot of > variable I have switched from c++ to Python several years ago, and was surprised about having to explicitly write 'self' each time. However, I never considered it "a big inconvenience". As years went by I have come to like the explicit notation in Python. > Or any way to make programmer's life easier? Others have already pointed out that leaving out 'self' is more bad than good. I think they are right. In the past I also thought that Python was badly designed, and until now, in the end it appeared that I was always in error. [off-topic: I think that again now with the default implementation of the object.__eq__ and object.__hash__ methods. I believe these methods should not exist until the programmer explicitly defines them with a suitable notion of equivalence. Anybody have a good argument against that? :-) ] Another suggestion may be to look at your code again, and check whether all self's are really needed. In other words, can you improve your code by reducing use of instance variables? In Python, The "a=b" statement is extremely cheap, because you don't copy data. Exploit that feature. An alternative may be to copy a self variable into a local variable one and use the local variable in the method. Another option may be to collect results in a local variable first and then assign it to a self.X variable. If you really have a lot of variables, are you sure that they should all be seperate (flat) variables in one class, ie would it be possible to merge some of them together in another object and have more structure in the variables? (classes are much cheaper in Python than in c++ w.r.t. amount of code) Sincerely, Albert From pete.forman at westerngeco.com Wed Jun 20 10:54:24 2007 From: pete.forman at westerngeco.com (Pete Forman) Date: Wed, 20 Jun 2007 15:54:24 +0100 Subject: SimplePrograms challenge References: Message-ID: Steve Howell writes: > Feel free to change the page as you see fit, although thanks for > discussing it here first. Done. I've moved classes up as unittest depends on it. The changes that I made to classes were: 1) Use new style class. 2) Demonstrate Pythonic use of attribute (no get/set). 3) Pare some lines. -- Pete Forman -./\.- Disclaimer: This post is originated WesternGeco -./\.- by myself and does not represent pete.forman at westerngeco.com -./\.- the opinion of Schlumberger or http://petef.port5.com -./\.- WesternGeco. From kyosohma at gmail.com Mon Jun 4 15:47:00 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Mon, 04 Jun 2007 12:47:00 -0700 Subject: Who uses Python? In-Reply-To: <1180985830.288414.208850@q69g2000hsb.googlegroups.com> References: <1180985830.288414.208850@q69g2000hsb.googlegroups.com> Message-ID: <1180986420.499273.61400@w5g2000hsg.googlegroups.com> On Jun 4, 2:37 pm, walterbyrd wrote: > I mean other than sysadmins, programmers, and web-site developers? > > I have heard of some DBAs who use a lot of python. > > I suppose some scientists. I think python is used in bioinformatics. I > think some math and physics people use python. > > I suppose some people use python to learn "programming" in general. > Python would do well as a teaching language. > > I would think that python would be a good language for data analysis. > > Anything else? Finance? Web-analytics? SEO? Digital art? We use it for login scripts, locking down PCs, automating backups, GIS, and more. Mike From bignose+hates-spam at benfinney.id.au Sat Jun 30 04:16:47 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sat, 30 Jun 2007 18:16:47 +1000 Subject: ORM layer References: Message-ID: <871wftrh5c.fsf@benfinney.id.au> David writes: > I am looking for an ORM for Python that fulfills a few simple needs. > > - ability to support a number of backends (probably mysql and sqlite ? > at present, csv a bonus) > - ability to be used easily from console python scripts, a bonus if I ? > can add a simple web GUI later using some framework > - decent documentation a definite plus I second the recommendation for SQLAlchemy. I've not used Elixir, but that's a way to abstract SQLAlchemy further, if you want to work at an even higher level of abstraction. The documentation for SQLAlchemy is very good, in my experience. The library allows one to work entirely with the object system (using it as an ORM), or dynamically build SQL statements, or combine the two methods. -- \ "I think there is a world market for maybe five computers." -- | `\ Thomas Watson, chairman of IBM, 1943 | _o__) | Ben Finney From max at alcyone.com Mon Jun 4 06:16:38 2007 From: max at alcyone.com (Erik Max Francis) Date: Mon, 04 Jun 2007 03:16:38 -0700 Subject: c[:]() In-Reply-To: References: <1180504190.055427.173610@h2g2000hsg.googlegroups.com><1180504773.374529.161740@q66g2000hsg.googlegroups.com><1180878080.630213.258230@q75g2000hsh.googlegroups.com><1180886141.096451.68060@k79g2000hse.googlegroups.com> Message-ID: Warren Stringer wrote: > demo4: demo.stop() > ball.smooth() > video.live() > preset.video.straight() > view.front3d() > luma.real() > seq[:]lock(1) You're way off in la-la land, now. > It sounds like list comprehension may be slower because it builds a list > that never gets used. I'm curious if eval statements are faster than def > statements? Any bytecode experts? Are you serious? Something that builds a list that never gets used is exactly what you were proposing this whole time. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM, Y!M erikmaxfrancis Get there first with the most men. -- Gen. Nathan Bedford Forrest, 1821-1877 From showell30 at yahoo.com Fri Jun 1 06:48:09 2007 From: showell30 at yahoo.com (Steve Howell) Date: Fri, 1 Jun 2007 03:48:09 -0700 (PDT) Subject: execute a function after each source code line ? In-Reply-To: <5caak5F2un8tqU1@mid.uni-berlin.de> Message-ID: <762425.28511.qm@web33515.mail.mud.yahoo.com> --- "Diez B. Roggisch" wrote: > > Are there any other (simple) ways of achieving > this ? > > (btw the whole program is running as an graphical > (wxPython) application) > > use the python trace facilities. > > http://docs.python.org/lib/module-trace.html > I'm not sure how much that will help in a GUI event-driven environment like wxPython. Since the OP is generating his own Python code, he can insert his own tracing statements. I think the essential problem is how do you run the intrepreted Python program in a mode that you can have the GUI get an event, let the intrepreted program run the next instruction, have the GUI get another event, have the intrepreted program run to the next instruction, etc. There are probably ways to achieve this, such as running the intrepreted Python program in a thread, but my own experience in this in wxPython, with Guido van Robot, led me to believe that it's ultimately easier to create a virtual machine for your intepreted language. But I may be missing your point. ____________________________________________________________________________________ Don't get soaked. Take a quick peak at the forecast with the Yahoo! Search weather shortcut. http://tools.search.yahoo.com/shortcuts/#loc_weather From bj_666 at gmx.net Fri Jun 8 09:19:29 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Fri, 08 Jun 2007 15:19:29 +0200 Subject: how to do reading of binary files? References: <1181304192.406529.135190@n4g2000hsb.googlegroups.com> <5csv4gF30to8lU1@mid.uni-berlin.de> <1181304990.863669.94020@m36g2000hse.googlegroups.com> <5ct0evF31n730U1@mid.uni-berlin.de> Message-ID: In <5ct0evF31n730U1 at mid.uni-berlin.de>, Diez B. Roggisch wrote: > jvdb schrieb: >> True. But there is another issue attached to the one i wrote. >> When i know how much this occurs, i know the amount of pages in the >> file. After that i would like to be able to extract a given amount of >> data: >> file x contains 20 <0C>. then for example i would like to extract from >> instance 5 to instance 12 from the file. >> The reason why i want to do this: The 0C stands for a pagebreak in PCL >> language. This way i would be absle to extract a certain amount of >> pages from the file. > > And? Finding the respective indices by using > > last_needle_position = 0 > positions = [] > while last_needle_position != -1: > last_needle_position = contents.find(needle, last_needle_position+1) > if last_needle_position != -1: > positions.append(last_needle_position) > > > will find all the pagepbreaks. then just slice contents appropriatly. > Did you read the python tutorial? Maybe splitting at '\x0c', selecting/slicing the wanted pages and joining them again is enough, depending of the size of the files and memory of course. One problem I see is that '\x0c' may not always be the page end. It may occur in "rastered image" data too I guess. Ciao, Marc 'BlackJack' Rintsch From notbob at nothome.com Thu Jun 21 11:39:48 2007 From: notbob at nothome.com (notbob) Date: Thu, 21 Jun 2007 10:39:48 -0500 Subject: The Modernization of Emacs References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182344981.372713.298580@w5g2000hsg.googlegroups.com> <86y7ieoiv7.fsf@lola.quinscape.zz> <1182347061.347199.133480@g4g2000hsf.googlegroups.com> <874pl2eg2j.fsf@W0053328.mgh.harvard.edu> <1182370016.986915.202150@u2g2000hsc.googlegroups.com> <87k5tx7444.fsf@W0053328.mgh.harvard.edu> <2cOdnRv-NoXmBOfbnZ2dnUVZ_t2dnZ2d@comcast.com> <24qdnSXDI78UB-fbnZ2dnUVZ_o7inZ2d@comcast.com> Message-ID: <2cOdnRX-NoVZBufbnZ2dnUVZ_t2dnZ2d@comcast.com> On 2007-06-21, Lew wrote: > Your comment reads like you've missed most of this thread. This may be due to the fact I've missed most of this thread. nb From evan at yelp.com Wed Jun 20 04:07:33 2007 From: evan at yelp.com (Evan Klitzke) Date: Wed, 20 Jun 2007 01:07:33 -0700 Subject: Python and (n)curses In-Reply-To: <1182325869.237652.157800@c77g2000hse.googlegroups.com> References: <1182211133.956524.160020@g4g2000hsf.googlegroups.com> <87y7igzapo.fsf@benfinney.id.au> <1182246189.210723.16280@w5g2000hsg.googlegroups.com> <1182325869.237652.157800@c77g2000hse.googlegroups.com> Message-ID: On 6/20/07, peter wrote: > > > > For me, introducing similar commands in Python would be by far the biggest single improvement that could be made to the language. > > > If it should be done, it should be done as a compatible subset of > > curses, IMHO. It has such a long history as the standard "GUI toolkit" > > But curses doesn't run under Windows - thats the whole point! I know of at least one curses implementation that runs on Windows -- PDCurses. You can find its home page at http://pdcurses.sourceforge.net/. I have the fortune not to have a need to do Windows curses programming ;-) so I'm not sure how good the Python support is, but a quick Google search showed a number of ad hoc Python wrappers for it. -- Evan Klitzke From torriem at chem.byu.edu Sat Jun 16 18:53:24 2007 From: torriem at chem.byu.edu (Michael Torrie) Date: Sat, 16 Jun 2007 16:53:24 -0600 Subject: How do I write to a CD? In-Reply-To: <51190.69.183.26.157.1182009013.squirrel@www.kearfott.com> References: <51190.69.183.26.157.1182009013.squirrel@www.kearfott.com> Message-ID: <1182034404.32256.4.camel@enterprise> On Sat, 2007-06-16 at 11:50 -0400, k47867 at kearfott.com wrote: > Hello: > > I am looking for Python code to open, read, write, close, > and make bootable the following: > CD > DVD > USB Drive There will be no cross-platform way to do this. Certainly no python libraries. The closest thing you can get to cross-platform is to popen various, ported utilities to do the dirty work for you, such as mkisofs. This is the recommended way, actually. > > Can I just use open(), read(), write(), and close() for > these? And how do I make something bootable? > Is there a portable way to do this that works for both > windows XP/Vista and Linux? Nope. You have to build a file system and copy it to the DVD, CD or USB drive. This is absolutely OS-specific. Of course, from Linux you should be able to build a fat32 file system and make it boot-able (using OS tools like mkfs.vfat). But making a boot-able ext3 partition from Windows is impossible since the tools needed to make an ext3 file system do not exist on Windows. If you are sticking to ISO file systems like UDF or ISO9660, you can use various programs like mkisofs, dvd+rw-tools, and friends (which have been ported to Windows). This is the approach used by *all* Linux cd-writing applications, like k3b. > > Thanks in advance: > Michael Yanowitz > > From gagsl-py2 at yahoo.com.ar Tue Jun 12 05:30:49 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 12 Jun 2007 06:30:49 -0300 Subject: Floating Number format problem References: <1181632259.217684.144180@d30g2000prg.googlegroups.com> <1181632572.643572.154690@n15g2000prd.googlegroups.com> <1181637985.191649.280250@x35g2000prf.googlegroups.com> Message-ID: En Tue, 12 Jun 2007 05:46:25 -0300, escribi?: > On 6 12 , 3 16 , ici wrote: >> On Jun 12, 10:10 am, wrote: >> >> > How could I format the float number like this: (keep 2 digit >> > precision) >> > 1.002 => 1 >> > 1.12 => 1.12 >> >>> print "%.02f" % (2324.012) >> 2324.01 >> > But in these case: > >>>> print '%.02f'%1.002 > 1.00 >>>> print '%.02f'%1.00 > 1.00 > > I just expect it to output "1" , but these way will output 1.00 def my_formatter_ommitting_trailing_zeroes(value): result = '%.2f' % value if result[-3:]=='.00': result = result[:-3] return result for f in [1.0, 1.002, 1.12, 1.567, 2324.012]: print "%g -> %s" % (f, my_formatter_ommitting_trailing_zeroes(f)) -- Gabriel Genellina From chowroc.z at gmail.com Thu Jun 21 23:26:29 2007 From: chowroc.z at gmail.com (Roc Zhou) Date: Fri, 22 Jun 2007 03:26:29 -0000 Subject: why __repr__ affected after __getattr__ overloaded? Message-ID: <1182482789.403770.92920@i38g2000prf.googlegroups.com> Now I have to design a class that overload __getattr__, but after that, I found the __repr__ have been affected. This is a simple example model: #!/usr/bin/env python class test: def __init__(self): self.x = 1 def __getattr__(self, attr_name): try: return self.__dict__[attr_name] except KeyError: self.__dict__[attr_name] = 'inexistent' return self.__dict__[attr_name] t = test() print t.x print t.y print type(t) T = t print T.x print t So far, I want the operation "print t" still return "", but the reuslt is: sh$ python test.py 1 inexistent 1 Traceback (most recent call last): File "testtree.py", line 23, in ? print t TypeError: 'str' object is not callable I also tried to overload __repr__ itself: #!/usr/bin/env python class test: def __init__(self): self.x = 1 def __getattr__(self, attr_name): try: return self.__dict__[attr_name] except KeyError: self.__dict__[attr_name] = 'inexistent' return self.__dict__[attr_name] def __repr__(self): return 'test.__repr__' t = test() print t.x print t.y print type(t) T = t print T.x print t But the result remains: Traceback (most recent call last): File "testtree.py", line 23, in ? print t TypeError: 'str' object is not callable So why? What is the principles? From wildemar at freakmail.de Sat Jun 2 11:44:30 2007 From: wildemar at freakmail.de (Wildemar Wildenburger) Date: Sat, 02 Jun 2007 17:44:30 +0200 Subject: Observer-Pattern by (simple) decorator In-Reply-To: References: <1180781727.519949.172580@q75g2000hsh.googlegroups.com> Message-ID: <4661905E.4000509@freakmail.de> Peter Otten wrote: > Then you have modified the code posted by Steven Bethard. > > Oops. Indeed I did. I changed this >>> class Observable(object): ... def __init__(self, func, instance=None, observers=None): ... if observers is None: ... observers = [] ... self.func = func ... self.instance = instance ... self.observers = observers to this >>> class Observable(object): ... def __init__(self, func, instance=None, observers=None): ... self.func = func ... self.instance = instance ... self.observers = observers or [] >> I don't see how your behaviour should come about ... a new observer-list >> is created for every decorated method, so there is no problem. >> > > Yes, but that list is shared across instances of SomeActor. > Oh! I thought a new Observable-object is created for every *instance* of SomeActor, where there is actually only one Observable per method that decorates *all* methods (all meth() methods, that is). Am I right? And I seem to have accidentally "solved" this by rewriting the __init__() method the way I did. Now it creates a new list even when it gets passed an empty list. How very smart of me ... ;) Looking at the way it is going to be used, I don't see a problem with this. Or am I missing something that could stab me in the back here? Thanks for the thorough explanation. But you *did* mock me with that "SomeActor.meth is SomeActor.meth"-line, right? ;) > > If you want per-instance callbacks you have to store the observers list (or > the bound method) in the instance: > > >>>> class SomeActor(object): >>>> > ... def __init__(self): > ... self.meth = Observable(self.meth, self) > ... def meth(self, foo): print foo > Seems good, but I'm trying to take as much hassle out of the programmer (probably me, mostly) as possible in order to watch method calls. Simply sticking a decorator in front of a methos, with no arguments, no nothing, seems less prone to errors. Also, reading "self.meth = Observable(self.meth, self)" kinda makes sense now, but I *know* I'd be scratching my head about this in no less than a few weeks. BTW, that might be my single favorite line of python code so far ... :) /W From gregpinero at gmail.com Mon Jun 25 01:21:32 2007 From: gregpinero at gmail.com (gregpinero at gmail.com) Date: Mon, 25 Jun 2007 05:21:32 -0000 Subject: Chroot Jail Not Secure for Sandboxing Python? Message-ID: <1182748892.916068.146780@p77g2000hsh.googlegroups.com> This wiki page suggests using a chroot jail to sandbox Python, but wouldn't running something like this in your sandboxed Python instance still break you out of the chroot jail: os.execle ('/usr/bin/python','-c','import os; os.execlp("/bin/sh")', {}) or maybe: del os.environ['LD_PRELOAD'] os.execl ('/usr/bin/python','-c','import os; os.execlp("/bin/sh")') My ISP suggested these as counter-examples to my request for a chroot jail. (I couldn't even get Python running in chroot to test this, nor could I run these commands locally in Python on Ubuntu, though maybe they opened sh?) So is a chroot jail not adequate for sandboxing Python? -Greg From evan at yelp.com Tue Jun 19 16:34:30 2007 From: evan at yelp.com (Evan Klitzke) Date: Tue, 19 Jun 2007 13:34:30 -0700 Subject: caseless dictionary howto ? In-Reply-To: <4dc64$46782a84$d443bb3a$4629@news.speedlinq.nl> References: <4dc64$46782a84$d443bb3a$4629@news.speedlinq.nl> Message-ID: On 6/19/07, Stef Mientki wrote: > hello, > > I need to search a piece of text and make all words that are equal > (except their case) also equal in their case, based on the first occurrence. > So I'm using a dictionary to store names and attributes of objects. > As as I need to search on the caseless name (so I've choosen lowercase), > My dictionairy looks like this: > > self.procs [ "serial_hw_read" ] = ( "Serial_HW_Read", "F", "++", T) > > Is this really a good solution, > or are there better ways ? Since you want an almost dictionary, you should create a new class that inherits from dict and overloads the methods that you want to change. -- Evan Klitzke From vijayendra.bapte at gmail.com Wed Jun 6 00:17:27 2007 From: vijayendra.bapte at gmail.com (Vijayendra Bapte) Date: Tue, 05 Jun 2007 21:17:27 -0700 Subject: Who uses Python? In-Reply-To: <1180985830.288414.208850@q69g2000hsb.googlegroups.com> References: <1180985830.288414.208850@q69g2000hsb.googlegroups.com> Message-ID: <1181103447.194971.78840@o11g2000prd.googlegroups.com> On Jun 5, 12:37 am, walterbyrd wrote: > I mean other than sysadmins, programmers, and web-site developers? > > I have heard of some DBAs who use a lot of python. > > I suppose some scientists. I think python is used in bioinformatics. I > think some math and physics people use python. > > I suppose some people use python to learn "programming" in general. > Python would do well as a teaching language. > > I would think that python would be a good language for data analysis. > > Anything else? Finance? Web-analytics? SEO? Digital art? Python is a rapid application development language..we uses it every where.. in web application development..GUI development..Automation/Regression test-suite development..Text/XML processing..website Scrapping/ Scrawling..Gaming..etc.. From Squzer at gmail.com Sun Jun 17 23:51:34 2007 From: Squzer at gmail.com (Squzer Crawler) Date: Mon, 18 Jun 2007 03:51:34 -0000 Subject: Memory problem with Python Message-ID: <1182138694.632692.17590@x35g2000prf.googlegroups.com> i am developing distributed environment in my college using Python. I am using therads in client for downloading wepages. Even though i am reusing the thread, memory usage get increased. I don know why.? I am using BerkelyDB for URLQueue, BeautifulShop for Parsing the webpages. Any idea of redusing the memory usage.. please tell me.... I want my program to run in bouded Memory.. Please.......... From joe at incomps.com Fri Jun 8 11:39:24 2007 From: joe at incomps.com (Joe) Date: Fri, 8 Jun 2007 09:39:24 -0600 Subject: Case-Insensitive Sorting of Multi-Dimensional Lists In-Reply-To: <8c7f10c60706080618m2fabe683i5cf4d9659471c1e1@mail.gmail.com> References: <020e01c7a94c$a7970750$0f01a8c0@desktop9> <8c7f10c60706080618m2fabe683i5cf4d9659471c1e1@mail.gmail.com> Message-ID: <02ac01c7a9e3$319b4c40$0f01a8c0@desktop9> > Try: > > list.sort(key=lambda el: el[0].lower()) Thanks! Worked like a charm :) > BUT - it's not a good idea to use list as a name, 'cos list is a > built-in, and you're obscuring it. Oh, don't worry. That was strictly my portrayal of the problem. Thanks again! Jough From kenicheema at gmail.com Wed Jun 13 12:47:48 2007 From: kenicheema at gmail.com (kenicheema at gmail.com) Date: Wed, 13 Jun 2007 16:47:48 -0000 Subject: MS Word parser In-Reply-To: References: <1181693045.105981.169500@q19g2000prn.googlegroups.com> Message-ID: <1181753268.002789.138000@i38g2000prf.googlegroups.com> On Jun 13, 1:28 am, Tim Golden wrote: > keniche... at gmail.com wrote: > > Hi all, > > I'm currently using antiword to extract content from MS Word files. > > Is there another way to do this without relying on any command prompt > > application? > > Well you haven't given your environment, but is there > anything to stop you from controlling Word itself via > COM? I'm no Word expert, but looking around, this > seems to work: > > > import win32com.client > word = win32com.client.Dispatch ("Word.Application") > doc = word.Documents.Open ("c:/temp/temp.doc") > text = doc.Range ().Text > > open ("c:/temp/temp.txt", "w").write (text.encode ("UTF-8")) > > > TJG Tim, I'm on Linux (RedHat) so using Word is not an option for me. Any other suggestions? From josiah.carlson at sbcglobal.net Tue Jun 26 23:50:22 2007 From: josiah.carlson at sbcglobal.net (Josiah Carlson) Date: Wed, 27 Jun 2007 03:50:22 GMT Subject: guidance needed: best practice for script packaging In-Reply-To: References: Message-ID: <28lgi.16052$2v1.7938@newssvr14.news.prodigy.net> Alan Isaac wrote: > This is a simple question about actual practice. > I just want to know how you (yes you) are > approaching this problem. > The problem: > What is the recommended packaging of > demo scripts or test scripts for a package > to be distributed to others to "play with". > (I.e., without "installing".) > > Example: > Suppose I have the package structure: > > package/ > __init__.py > subpackage1/ > __init__.py > moduleXX.py > subpackage2/ > __init__.py > moduleYY.py > > Important detail: > moduleXX uses a relative import to access moduleYY. > > The goal: > I have a script test.py that I want to > distribute with the package. This script will import > moduleXX to illustrate or test the module's use. > > Is it the case that this script cannot reasonably be > bundled with `package`? (I.e., within its directory > structure.) > > Note: > If I put it in the `subpackage1` directory and > just import moduleXX, I will get > ValueError: Attempted relative import in non-package > > Note: > If I put it in the `package` directory and > import subpackage1.moduleXX, I will get > ValueError: Attempted relative import beyond toplevel package > > Here is one hack, based on a suggestion of Alex Martelli > http://mail.python.org/pipermail/python-list/2007-May/438250.html > and others. > - add a `scripts` subdirectory to `package` > - use path manipulation to find the directory holding `package` > - insert this directory in sys.path > > This hack "works". > However it has also been claimed that this approach is an > insane for any shared code. Is it? If so, what is best practice? I have used this method more than once to get around the fact that relative imports don't work the way I want them to in this situation. Alternatively, you could use... package/ __init__.py #for 'import package' test.py shared/ __init__.py subpackage1/ __init__.py moduleXX.py subpackage2/ __init__.py moduleYY.py And always run scripts from the package/... path or from something that is able to 'import package'. It does force a layer of useless namespace, but it works. - Josiah From __peter__ at web.de Sun Jun 17 06:12:03 2007 From: __peter__ at web.de (Peter Otten) Date: Sun, 17 Jun 2007 12:12:03 +0200 Subject: Function that returns a tuple References: <1182043826.790070.4420@u2g2000hsc.googlegroups.com> <1182071765.760451.298490@u2g2000hsc.googlegroups.com> <1182073753.544045.256670@g4g2000hsf.googlegroups.com> Message-ID: Baltimore wrote: > On 17 juin, 11:16, Marcpp wrote: >> On 17 jun, 03:53, Dan Hipschman wrote:> On Sat, Jun >> 16, 2007 at 06:30:26PM -0700, Marcpp wrote: >> > > Hi, I need to returns a tuple from a function (reads a database) >> > > Any idea?. >> >> > Like this? >> >> > def foo(): >> > return 1, 2, 3, 4 >> >> Hi, I need to return a tupla like this function: >> >> def BDllids(a): >> a = () >> conn = sqlite.connect('tasques.db') >> cursor = conn.cursor() >> cursor.execute('SELECT * FROM tasques') >> for row in cursor: >> a.append (row[0]) >> return a() >> >> I'm doing the correct, method? > > Why is 'a' used as argument of the function ? > You don't need to put it in argument. > > def BDllids(): a = [] # must be a list; tuples don't have an # append() method > conn = sqlite.connect('tasques.db') > cursor = conn.cursor() > cursor.execute('SELECT * FROM tasques') Make that "SELECT yadda FROM tasques", assuming that 'yadda' is the first column in the table. > for row in cursor: > a.append (row[0]) > return a > > But that's the correct method ! Note that the result is now a list, and that is probably the appropriate data structure; if you needed a tuple you'd have to convert it: return tuple(a) # easy, obvious, but probably superfluous Peter From http Mon Jun 25 21:50:50 2007 From: http (Paul Rubin) Date: 25 Jun 2007 18:50:50 -0700 Subject: Looking for an interpreter that does not request internet access References: Message-ID: <7x3b0flc05.fsf@ruckus.brouhaha.com> James Alan Farrell writes: > I recently installed new anti-virus software and was surprised the > next time I brought up IDLE, that it was accessing the internet. See the message it displays when you start it. It's not really accessing the internet, it's opening a socket to another process running on the same machine. Try unplugging your network cable and running idle and you'll see the socket connection still succeeds. From philipp.leitner at gmx.at Sun Jun 17 18:46:09 2007 From: philipp.leitner at gmx.at (Philipp Leitner) Date: Sun, 17 Jun 2007 15:46:09 -0700 Subject: The Modernization of Emacs In-Reply-To: <1182093200.598418.218620@e9g2000prf.googlegroups.com> References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> Message-ID: <1182120369.111379.87740@o61g2000hsh.googlegroups.com> Ever came to your mind that there are people (programmers and others) who will not use emacs for their day-to-day work simply because they have tools that suit them better for the work they have to do (Eclipse for me, as an example)? Except from that: I personally don't feel that your rantings are interesting enough to qualify for a 4 groups X-post ... this sort of article goes well into a blog, but not so much on programmers newsgroups (which are used for Q&A imho). From larry.bates at websafe.com Wed Jun 20 10:57:08 2007 From: larry.bates at websafe.com (Larry Bates) Date: Wed, 20 Jun 2007 09:57:08 -0500 Subject: Transfer file name input from one .py to another In-Reply-To: <1182299624.594164.145430@n2g2000hse.googlegroups.com> References: <1182299624.594164.145430@n2g2000hse.googlegroups.com> Message-ID: mark.martinez2 at gmail.com wrote: > How do I transfer the file name which is input in one .py (an MDI > parent frame in wxPython) to another .py (an MDI child frame)? The > parent gets the file name from the user via a file select dialog, but > the child frame is the one that needs to know what file it is working > with. > > Thanks > Normally I do something like: class childFrame: def __init__(self, parent, *args): self.parent=parent # # Now you can refer to the filename by accessing # self.parent.filenamefromdialog class main: def getfilefromdialog(self): self.filenamefromdialog=... -Larry From moishyyehuda at gmail.com Sun Jun 10 12:38:17 2007 From: moishyyehuda at gmail.com (moishyyehuda at gmail.com) Date: Sun, 10 Jun 2007 16:38:17 -0000 Subject: load data infile problem Message-ID: <1181493497.990230.254220@n4g2000hsb.googlegroups.com> does any one know why when I execute this mysql statement with python api LOAD DATA INFILE 'data.txt' INTO TABLE merchandise; I get this error and how can I fix it #1045 - Access denied for user: 'papermen@%' (Using password: YES) From k47867 at kearfott.com Sat Jun 2 14:24:09 2007 From: k47867 at kearfott.com (k47867 at kearfott.com) Date: Sat, 2 Jun 2007 14:24:09 -0400 (EDT) Subject: Python Pop Quiz In-Reply-To: <1180751587.951837.191480@h2g2000hsg.googlegroups.com> References: <1180751587.951837.191480@h2g2000hsg.googlegroups.com> Message-ID: <60371.69.183.26.157.1180808649.squirrel@www.kearfott.com> > 1. Do you like Python? > Yes, or I wouldn't still be subscribed to the python-list. > 2. Do you think Python is good? s Yes. Well it is a good Language. I can code in python at-least twice as fast as I could in C or C++. > > 3. Do you think Python is real good? > Yeah, if you meant 'very' instead of real. It has alot of nice features. Combining the best features of many other languages. > 4. What is your favorite version of Python? > Have only used 2.4, though I am sure 2.5, once I upgrade will become my new favorite, assuming it is backwards compatible. > 5. Because of Python, do you think it will be easier to take over the > world? If so, when? If not, when? > No, those who wish to take over the world will do so with mass weapons of destruction. Though a little computer virus (perhaps written in Python though probably not), that can't be detected by a Window's Antivirus may come close. > 7. How many Z80 assembly language programmers does it take to equal > one Python guru? > Is 0 * Infinity = 0? Well really that is different, that is more like comparing Apples and Orange-PCs. Assembly Lanugage programmers will probably be coding at a much lower and more efficient manner than Python programmers who will program at a higher level and get alot more done in much fewer lines of code. However, the assembly code can probably do things that Python can't > Essay: "C++ is better than C", agree or disagree? (four word maximum) > Yes - classes, inheritance, abstraction. > Bonus: A rabbi walks into a bar while nursing a baby goat. He is > closely followed by a priest, and a Perl hacker. Explain. A rabbi enters a bar. At the same time he (or she) is giving milk to a newly born goat. Shortly after he arrives, a priest and Perl hacker also enter at the same bar. > > -- > http://mail.python.org/mailman/listinfo/python-list > From gagsl-py2 at yahoo.com.ar Mon Jun 4 19:46:08 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 04 Jun 2007 20:46:08 -0300 Subject: how to print out each single char from a string in HEX format? References: <1180998219.005688.323200@r19g2000prf.googlegroups.com> Message-ID: En Mon, 04 Jun 2007 20:03:39 -0300, mike escribi?: > I've researched python pretty much but still have no idea how to print > out each single character from a string in HEX format? Hope someone > can give me some hints. Thanks a lot. > > e.g. ###here is a string > > a='01234' > > ###how to print out it out in this way > > 0x31 0x31 0x32 0x33 0x34 py> a='01234' py> for c in a: ... print "%#x" % ord(c), ... 0x30 0x31 0x32 0x33 0x34 py> See for the ord() function and for the "%#x" format -- Gabriel Genellina From eopadoan at altavix.com Sat Jun 16 17:00:49 2007 From: eopadoan at altavix.com (Eduardo "EdCrypt" O. Padoan) Date: Sat, 16 Jun 2007 18:00:49 -0300 Subject: Should: "for k,v in **dictionary_instance" work? In-Reply-To: <1181978437.793818.92300@n2g2000hse.googlegroups.com> References: <1181935045.323196.287810@n2g2000hse.googlegroups.com> <1181978437.793818.92300@n2g2000hse.googlegroups.com> Message-ID: > Actually since you asked, I had to try this out > > x = range(10) > a, *b = x PEP 3132: Extended Iterable Unpacking http://www.python.org/dev/peps/pep-3132/ -- EduardoOPadoan (eopadoan->altavix::com) Bookmarks: http://del.icio.us/edcrypt From jayanthanc at yahoo.com Mon Jun 11 23:32:12 2007 From: jayanthanc at yahoo.com (Chico Jayanthan) Date: Mon, 11 Jun 2007 20:32:12 -0700 (PDT) Subject: Set timeout and kill external windows program Message-ID: <274113.73720.qm@web50104.mail.re2.yahoo.com> Hi, I call an external windows program (.exe) from a python script. Something like os.system('test.exe'). I want to set a timeout for the external windows program to return. If no results are produced by the external windows program (test.ext) within this timeout limit, I want to terminate the external windows program and continue with the python script. How do I set the timeout and terminiate the external windows program from within the Python script? Thanks. Suganthan. ____________________________________________________________________________________ Be a better Heartthrob. Get better relationship answers from someone who knows. Yahoo! Answers - Check it out. http://answers.yahoo.com/dir/?link=list&sid=396545433 From mail at microcorp.co.za Sun Jun 3 04:13:24 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Sun, 3 Jun 2007 10:13:24 +0200 Subject: Python rocks References: <4661adda$0$19256$da0feed9@news.zen.co.uk> <4661da4f$0$19227$fa0fcedb@news.zen.co.uk> Message-ID: <00e101c7a5b8$f8d93b20$03000080@hendrik> "Mark Carter" wrote: > Josiah Carlson wrote: > > What kind of scoping did you desire? > > Well, I had in mind so that if you defined a function, but wanted to > access a global var, that you didn't have to use the global keyword. Not > much of a biggie, I guess. You can access them without the global keyword - for "reading" . You only need global if you are assigning to it - else you get a new function local: >>> x = 7 >>> def rubbish(): print x >>> rubbish() 7 >>> def more_rubbish(): x = x+1 print x >>> more_rubbish() Traceback (most recent call last): File "", line 1, in ? more_rubbish() File "", line 2, in more_rubbish x = x+1 UnboundLocalError: local variable 'x' referenced before assignment >>>def other_rubbish(): y = x+1 print y >>> other_rubbish() 8 >>> x 7 >>> def global_rubbish(): global x x = x + 1 print x >>> global_rubbish() 8 >>> print x 8 >>> - Hendrik From jkrukoff at ltgc.com Thu Jun 14 17:53:40 2007 From: jkrukoff at ltgc.com (John Krukoff) Date: Thu, 14 Jun 2007 15:53:40 -0600 Subject: Questions about mathematical and statistical functionality in Python In-Reply-To: Message-ID: <00a601c7aece$78ae3fd0$0301a8c0@naomi> On Jun 14, 4:02 pm, "Talbot Katz" wrote: > Greetings Pythoners! > > I hope you'll indulge an ignorant outsider. I work at a financial > software > firm, and the tool I currently use for my research is R, a software > environment for statistical computing and graphics. R is designed with > matrix manipulation in mind, and it's very easy to do regression and time > series modeling, and to plot the results and test hypotheses. The kinds > of > functionality we rely on the most are standard and robust versions of > regression and principal component / factor analysis, bayesian methods > such > as Gibbs sampling and shrinkage, and optimization by linear, quadratic, > newtonian / nonlinear, and genetic programming; frequently used graphics > include QQ plots and histograms. In R, these procedures are all available > as functions (some of them are in auxiliary libraries that don't come with > the standard distribution, but are easily downloaded from a central > repository). > > For a variety of reasons, the research group is considering adopting > Python. > Naturally, I am curious about the mathematical, statistical, and > graphical > functionality available in Python. Do any of you out there use Python in > financial research, or other intense mathematical/statistical computation? > Can you compare working in Python with working in a package like R or S- > Plus > or Matlab, etc.? Which of the procedures I mentioned above are available > in > Python? I appreciate any insight you can provide. Thanks! > > -- TMK -- > 212-460-5430 home > 917-656-5351 cell > > > -- > http://mail.python.org/mailman/listinfo/python-list It is worth noting that there's a bridge available to allow python to integrate cleanly with R, the Rpy project: http://rpy.sourceforge.net/ Which should allow you to use python for whatever it is you need without abandoning R for your mathematical/statistical work. --------- John Krukoff jkrukoff at ltgc.com From mail at microcorp.co.za Fri Jun 8 02:18:37 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Fri, 8 Jun 2007 08:18:37 +0200 Subject: Determinant of Large Matrix References: <5coopoF2vt25kU1@mid.individual.net> Message-ID: <007201c7a994$daa2ba20$03000080@hendrik> "James Stroud" wrote: > James Stroud wrote: > [pointless stuff] > > OK. Nevermind. I'm rebinding encodings and so taking a sample from the > sample and thus getting the sample back. Terribly sorry. There is truly nothing to be sorry about. It takes guts to come right out and say that you made a mistake. Well done! One of my pet peeves are people who pretend that they never make mistakes. Strangely enough, when you ask them to walk on water, they never quite manage it. This sort of thing should be cause for rejoicing, - when you think about it, its a proof that the body of knowledge that has to do with sampling is solid and reliable, independently of the experimenter - these days that is quite a comforting thought. The sanitised stuff you read in the scientific journals does not represent the true course of the progress of science - in reality, progress is the incidental by-product of a progressive series of blunders. But nobody involved will acknowledge this, for fear of their precious reputations... - Hendrik From danb_83 at yahoo.com Tue Jun 12 21:20:50 2007 From: danb_83 at yahoo.com (Dan Bishop) Date: Tue, 12 Jun 2007 18:20:50 -0700 Subject: matrix class In-Reply-To: <1181694695.015143.72390@g37g2000prf.googlegroups.com> References: <1181694695.015143.72390@g37g2000prf.googlegroups.com> Message-ID: <1181697650.621928.91050@z28g2000prd.googlegroups.com> On Jun 12, 7:31 pm, DarrenWeber wrote: > Below is a module (matrix.py) with a class to implement some basic > matrix operations on a 2D list. Some things puzzle me about the best > way to do this (please don't refer to scipy, numpy and numeric because > this is a personal programming exercise for me in creating an > operational class in pure python for some *basic* matrix operations). > > 1. Please take a look at the __init__ function and comment on the > initialization of the list data with respect to unique memory > allocation. > > 2. In the operator overloading of __add__, __sub__, etc., the > statement isinstance(q, Matrix) raises exceptions every time. This > statement works fine outside of the class definition, but not during > the operator evaluation. What is going here? ... > > def __add__(self, q): > 'matrix addition: m3 = m1 + m2' > # if isinstance(q, Matrix): > # arg = ("q is not a matrix instance", q) > # raise TypeError, arg Wouldn't it make more sense to raise an exception if q is NOT an instance of Matrix? From gherron at islandtraining.com Sun Jun 3 19:54:40 2007 From: gherron at islandtraining.com (Gary Herron) Date: Sun, 03 Jun 2007 16:54:40 -0700 Subject: subexpressions (OT: math) In-Reply-To: <46634BDC.7090104@freakmail.de> References: <4662675b$1_5@news.bluewin.ch> <1180890214.317409.85100@w5g2000hsg.googlegroups.com> <4662FDC8.9080407@islandtraining.com> <46634BDC.7090104@freakmail.de> Message-ID: <466354C0.4010700@islandtraining.com> Wildemar Wildenburger wrote: > Gary Herron wrote: > >> Of course not! Angles have units, commonly either degrees or radians. >> >> However, sines and cosines, being ratios of two lengths, are unit-less. >> >> >>> To understand it: sin() can't have dimensioned argument. It is can't >>> to be - sin(meters) >>> >>> >>> >> No it's sin(radians) or sin(degrees). >> >> > > NO! > The radian is defined as the ratio of an arc of circumfence of a circle > to the radius of the circle and is therefore *dimensionless*. End of story. > http://en.wikipedia.org/wiki/Radian and esp. > http://en.wikipedia.org/wiki/Radian#Dimensional_analysis > > *grunt* > No, not end-of-story. Neither of us are being precise enough here. To quote from your second link: "Although the radian is a unit of measure, it is a dimensionless quantity." But NOTE: Radians and degrees *are* units of measure., however those units are dimensionless quantities , i.e., not a length or a time etc. The arguments to sine and cosine must have an associated unit so you know whether to interpret sin(1.2) as sine of an angle measured in degrees or radians (or whatever else). Gary Herron From dwahler at gmail.com Fri Jun 22 01:52:42 2007 From: dwahler at gmail.com (David Wahler) Date: Fri, 22 Jun 2007 06:52:42 +0100 Subject: Problem with using ConfigParser.py In-Reply-To: References: <8816A57AF3B542A8AC3B12F4E56DB6B0@persistent.co.in> Message-ID: On 6/22/07, shridhar kurhade wrote: > Hi, > Thanks for your reply. I tried changing the ownership and it looks as below: > # ls -l /home/ast/ast-linux.conf > -rw-r--r-- 1 ast ast 7936 Jun 21 11:11 /home/ast/ast-linux.conf > > But when I try to read through browser, it gives permission denied error: > > [Errno 13] Permission denied: '/home/ast/ast-linux.conf' target sandbox > > Also other files in the /home/ast/ have ast:ast as ownership. > Can you please tell me if there any other problem with this? That looks OK, but as I said before, you need to check the permissions on the /home/ast directory. What's the output of "ls -ld /home/ast"? It needs to grant execute permissions to the user or group that the script is running as. If that looks OK, you might want to try calling os.getuid() and os.getgid() from your script, to make sure it's running under the same UID/GID you think it is. -- David P.S. When using Gmail, it's better to use "Reply to All" instead of "Reply"; that way your messages continue to go to the mailing list, and other people can help you. From aisaac at american.edu Thu Jun 21 23:30:29 2007 From: aisaac at american.edu (Alan Isaac) Date: Fri, 22 Jun 2007 03:30:29 GMT Subject: cannot have test scripts in packages? Message-ID: This is really a repackaging of an earlier question, probably illustrating that I still do not understand relative imports. Suppose I have the package structure (taken from the example at http://www.python.org/dev/peps/pep-0328/) package/ __init__.py subpackage1/ __init__.py moduleY.py subpackage2/ __init__.py moduleZ.py Important detail: moduleZ uses a relative import to access moduleY. The problem: I have a script test.py that I want to distribute with the package. It will import moduleZ to illustrate or test the module's use. Is it the case that this script cannot reasonably be bundled with `package`? (I.e., within its directory structure.) I cannot put it in the `subpackage2` directory and just import moduleZ, because then I will get ValueError: Attempted relative import in non-package I cannot put it in the `package` directory and import subpackage2.moduleZ, because then I will get ValueError: Attempted relative import beyond toplevel package The script could then use path manipulation to find `package`, as suggested by Alex Martelli http://mail.python.org/pipermail/python-list/2007-May/438250.html and others. However it has also been claimed that this approach is an insane for any shared code. Btw, I do not want to assume the package will be installed: a user should be able to play with it without installing it. So if the package is not installed, is the only "sane" thing to do is require any user to take the step of inserting the package location into sys.path and have test.py rely on the user having done this? What is the recommended handling of demo or test scripts for a package? Thank you, Alan Isaac From hat at se-162.se.wtb.tue.nl Fri Jun 29 11:14:32 2007 From: hat at se-162.se.wtb.tue.nl (A.T.Hofkamp) Date: Fri, 29 Jun 2007 17:14:32 +0200 Subject: How to close a program I execute with subprocess.Popen? References: <1183124181.318726.200620@m36g2000hse.googlegroups.com> Message-ID: On 2007-06-29, revenant81 at hotmail.com wrote: > I want to end the execution of the command when the user closes my > application. > > Right now I'm using an object my_child of type subprocess.Popen to > execute the command, inside a thread with an infinite loop where we > constantly ask for its output. > > To end the program when the user closes the application, I send a > SIGTERM to the process with pid my_child.pid using os.kill. But I also > have to send a SIGTERM to my_child.pid + 1 because my_child.pid is the Maybe that holds for a system recently started and mostly idle, but it need not be the case. If you have more users active, and each user is forking processes, (or one user is forking several processes concurrently), the order of assigning process IDs is not defined. For systems that run for a longer time, unused process IDs are re-used, skipping over process IDs that are still living. > pid of /bin/sh -c which is the one which calls the command, because > when I try to run Popen with shell=False, it sends an exception and > says the file or directory doesn't exist. The shell performs a search over PATH to find the command executable (ie it maps 'ls' to '/bin/ls'). If you provide a full path to the command you are starting, you don't need the shell. > Anyone knows of a better way to close the command than using a > SIGTERM? I just can't help myself thinking this is an ugly dirty hack. In principle, you should only kill your own child processes, your child process should handle its own childs (your grant child processes). SIGTERM is one way. Another solution often adopted is to close the stdin of the child. This notifies the child that no more data will arrive, and many commands react on that message by terminating. Try running command < /dev/null /dev/null is the empty input stream. Last but not least, many commands do something special when sent -HUP. Look in the manual page of the command for clean ways to close the command down. Albert From steven.bethard at gmail.com Mon Jun 11 17:55:58 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Mon, 11 Jun 2007 15:55:58 -0600 Subject: Properties for modules? In-Reply-To: References: Message-ID: Ed Leafe wrote: > I have a simple module that reads in values from disk when imported, > and stores them in attributes, allowing for code like: > > >>> import moduleFoo > >>> print moduleFoo.someSetting > 'the value' > > What I'd like to do is have a more property-like behavior, so that > if they try to set the value of moduleFoo.someSetting, it also persists > it to disk. But properties are really only useful in instances of > classes; if I define 'someSetting' as a property at the module level, I > get: > > >>> import moduleFoo > >>> print moduleFoo.someSetting > > > Does anyone know any good tricks for getting property-like behavior > here? I typically define a module wrapping class like:: class GiveThisModuleProperties(object): def __init__(self, module_name): self._module = sys.modules[module_name] sys.modules[module_name] = self # now define whatever behavior you need def __getattr__(...): ... def __setattr__(...): ... Then, in the module you want wrapped, you write:: GiveThisModuleProperties(__name__) The trick here is basically that we replace the module object in sys.modules with a class instance that wraps the module with whatever extra behavior is necessary. It's not beautiful, but it does seem to work. ;-) STeVe From gnewsg at gmail.com Wed Jun 27 18:06:40 2007 From: gnewsg at gmail.com (billiejoex) Date: Wed, 27 Jun 2007 15:06:40 -0700 Subject: glob.glob standardization Message-ID: <1182982000.940609.201250@k79g2000hse.googlegroups.com> os.listdir(path) return a list of file names independently if the path- argument used is absolute or relative: >>> os.getcwd() '/home/user' >>> os.listdir('Desktop') ['file.py'] >>> os.listdir('/home/user/Desktop') ['file.py'] glob.glob, instead, return file names only if given path is relative: >>> os.chdir('Desktop') >>> os.getcwd() '/home/user/Desktop >>> glob.glob("*") ['file.py'] ...and absolute file names if given path is absolute: >>> glob.glob('/home/user/Desktop/*') ['/home/user/Desktop/file.py'] Don't you think it would be more convenient for glob.glob to return file names only in any case, like os.listdir do? From JoeSalmeri at hotmail.com Sun Jun 3 21:49:13 2007 From: JoeSalmeri at hotmail.com (Joe Salmeri) Date: Sun, 3 Jun 2007 21:49:13 -0400 Subject: Python 2.5.1 broken os.stat module References: <466140A6.1090100@v.loewis.de> <-aOdnbFdroD_gP_bnZ2dnUVZ_uKknZ2d@comcast.com> <4662750b$0$29898$9b622d9e@news.freenet.de> <4662F98C.8070709@v.loewis.de> Message-ID: > Please understand that it is *extremely* tedious to follow your > messages. It would have been much better if they had been short and > to the point. Sometimes it seems that it is impossible to please people. When messages are short then people complain that they did not get sufficient details, or examples. I provide details and tests so that anyone could easily attempt to duplicate exactly what I said was happening and you complain that they are too long. Baring any typo mistakes on my part, performing the tests should produce the exact results that I stated were happening. > That is very hard to believe. CVS and backup programs use the UTC time > stamp, and completely ignore the timezone. So when you agree that the > UTC time stamp did not change, CVS and the backup programs will work > just fine. The CVS problems were mentioned in the article I linked to and were discussed by people involved in CVS development. Whether you choose to believe all those people or not is up to you. See my reply to Terry, from the end user perspective, the Windows behavior does not make sense. Short enough? From steve at holdenweb.com Mon Jun 18 13:23:50 2007 From: steve at holdenweb.com (Steve Holden) Date: Mon, 18 Jun 2007 13:23:50 -0400 Subject: Thunderbird access to this newsgroup In-Reply-To: <87d501w9v2.fsf@benfinney.id.au> References: <1181640420.561878.224690@x35g2000prf.googlegroups.com> <87d501w9v2.fsf@benfinney.id.au> Message-ID: Ben Finney wrote: > Rostfrei writes: > >> What is the news server for this >> newsgroup. > > Usenet newsgroups are redistributed over many servers worldwide. > > > >> If I ping comp.lang.python it is not resolved. > > That's right. It's the name of a Usenet newsgroup, not a host name. > > > >> For instance I had no problem configuring Eclipse news server. I >> just entered news.eclipse.org as a news server address and after it >> I can browse available groups. > > You can browse the groups available on that server, yes. To browse > this group, you need to find a server that carries comp.lang.python. > > > You might find, as many others do, that it's convenient to read this group using the Gmane service - it's group gmane.comp.python.general on server news.gmane.org. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From carsten at uniqsys.com Thu Jun 21 11:11:34 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Thu, 21 Jun 2007 11:11:34 -0400 Subject: PEP 3107 and stronger typing (note: probably a newbie question) In-Reply-To: References: <1182369568.941307.316260@p77g2000hsh.googlegroups.com> <5dveb4F360un0U1@mid.individual.net> Message-ID: <1182438694.3376.58.camel@dot.uniqsys.com> On Thu, 2007-06-21 at 10:14 -0400, Peter Decker wrote: > On 6/21/07, Bjoern Schliessmann > wrote: > > Stephen R Laniel wrote: > > > On Wed, Jun 20, 2007 at 12:59:28PM -0700, > > > bruno.desthuilliers at gmail.com wrote: > > > > >> Then you should use another language. > > > > > > This is what I meant about knowing how Internet discussions > > > go. > > > > I agree. I also notice that (rather newbie-) OPs with not-so-simple > > questions are easily offended by technical answers. I'd love to > > know why. > > Oh, c'mon. The OP was asking for an explanation, and got an indignant > response. Actually, no, Bruno gave a tongue-in-cheek response accompanying a technical answer. The OP chose to turn it into an indignant response by taking one sentence out of context and snipping the pertinent technical part of Bruno's response. -- Carsten Haese http://informixdb.sourceforge.net From lobais at gmail.com Tue Jun 5 17:15:30 2007 From: lobais at gmail.com (Thomas Dybdahl Ahle) Date: Tue, 05 Jun 2007 23:15:30 +0200 Subject: subprocess leaves child living References: <1181052375.551083.117390@p47g2000hsd.googlegroups.com> <874plmgogn.fsf@merkury.smsnet.pl> Message-ID: Den Tue, 05 Jun 2007 22:01:44 +0200 skrev Rob Wolfe: > Thomas Dybdahl Ahle writes: > >> But you can't ever catch sigkill. > > There is no protection against sigkill. > >> Isn't there a way to make sure the os kills the childprocess when the >> parrent dies? > > If the parent dies suddenly without any notification childprocesses > become zombies and there is no way to avoid that. If I call "kill -9 pythonpid" on the python code you posted earlier, the terminal running the script will continue pinging forever. If it was a harder program like a chessengine or such, it would continue consuming 100% cpu time. Zombies would be fine to me. From michael at jedimindworks.com Fri Jun 1 09:35:37 2007 From: michael at jedimindworks.com (Michael Bentley) Date: Fri, 1 Jun 2007 08:35:37 -0500 Subject: unknown host In-Reply-To: <1180703347.753746.17070@o5g2000hsb.googlegroups.com> References: <1180703347.753746.17070@o5g2000hsb.googlegroups.com> Message-ID: <977569D5-EE3F-4E26-B804-EBE92017D1A7@jedimindworks.com> On Jun 1, 2007, at 8:09 AM, abcd wrote: > I have a linux machine (ip = 10.10.10.8), which can ping other > machines on the same subnet...such as > > 10.10.10.1 > 10.10.10.2 > 10.10.10.5 > 10.10.10.6 > 10.10.10.254 > > If I use socket.gethostbyaddr() I get back results when ip is > 10.10.10.1 and 10.10.10.254 but for the other IP addresses > (10.10.10.5, .6, etc) I get back "unknown host". In fact I get > "unknown host" for the linux machine that I run the gethostbyaddr > from. > > If perform the same operation from a windows machine (ip = 10.10.10.5) > it returns data for the other IP addresses as expected. > > any ideas? socket.gethostbyaddr() is trying to use a name server to look up the address. It may be that you haven't specified a valid name server in /etc/resolv.conf, or maybe /etc/nsswitch.conf is misconfigured, or maybe your name server doesn't want to play. The fact that you were able to ping addresses have nothing to do with resolving their hostnames. hope this helps, Michael --- A clever person solves a problem. A wise person avoids it. --Albert Einstein From http Fri Jun 8 23:24:45 2007 From: http (Paul Rubin) Date: 08 Jun 2007 20:24:45 -0700 Subject: Gzip - gunzip using zlib References: <1181358947.291489.85950@q19g2000prn.googlegroups.com> Message-ID: <7xvedxolmq.fsf@ruckus.brouhaha.com> flebber writes: > Hi Can anyone show me a working example of how to use gzip to > decompress a file. I have read the docs at python.org and had many > goes at it but just can't get it to work. Untested in this instance, but this is how I usually do it: import gzip z = gzip.open('parrot.gz') for line in z: ... From chowroc.z at gmail.com Fri Jun 22 02:43:26 2007 From: chowroc.z at gmail.com (Roc Zhou) Date: Fri, 22 Jun 2007 06:43:26 -0000 Subject: why __repr__ affected after __getattr__ overloaded? In-Reply-To: <1182491802.112209.322440@e9g2000prf.googlegroups.com> References: <1182483043.850101.110890@i13g2000prf.googlegroups.com> <1182491330.343267.122010@q19g2000prn.googlegroups.com> <1182491802.112209.322440@e9g2000prf.googlegroups.com> Message-ID: <1182494606.966742.63710@e9g2000prf.googlegroups.com> I'm sorry but I still have a question, look at this example: >>> class test: ... def __init__(self): ... self.x = 1 ... def __getattr__(self, attr_name): ... print attr_name ... if attr_name == 'y': ... return 2 ... else: ... raise AttributeError, attr_name ... >>> t = test() >>> t.x 1 >>> t.y y 2 >>> print t.x 1 >>> print t __str__ __repr__ <__main__.test instance at 0xb7f6d6cc> Since __str__ and __repr__ does not exist because their names was printed, why not the "AttributeError" be raised? From showell30 at yahoo.com Sun Jun 3 22:52:13 2007 From: showell30 at yahoo.com (Steve Howell) Date: Sun, 3 Jun 2007 19:52:13 -0700 (PDT) Subject: subexpressions (OT: math) In-Reply-To: <1hz4ui1.q7kmiz1thea3rN%aleax@mac.com> Message-ID: <81105.36196.qm@web33512.mail.mud.yahoo.com> --- Alex Martelli wrote: > > I blame the > Babylonians for that > confusion just as much as for the clunky base-60 > that intrudes in our > ordinary time reckoning...! > I apologize for helping to start this whole ridiculous thread, although I hope some people have been entertained by it. I have been! ____________________________________________________________________________________ Park yourself in front of a world of choices in alternative vehicles. Visit the Yahoo! Auto Green Center. http://autos.yahoo.com/green_center/ From Allen.Chenal at gmail.com Tue Jun 12 09:01:47 2007 From: Allen.Chenal at gmail.com (Allen) Date: Tue, 12 Jun 2007 06:01:47 -0700 Subject: In C extension .pyd, sizeof INT64 = 4? In-Reply-To: References: <1181642594.963433.132750@g37g2000prf.googlegroups.com> <1181648383.882895.57710@g37g2000prf.googlegroups.com> Message-ID: <1181653307.604247.285650@g37g2000prf.googlegroups.com> On 6 12 , 8 08 , "Gabriel Genellina" wrote: > En Tue, 12 Jun 2007 08:39:43 -0300, Allen > escribi?: > > > PyObject* method(PyObject* self, PyObject *args) > > { > > INT64 nValue; /* LINE_HERE */ > > INT32 nRet; > > nRet = DoSomeCOperations(nValue); > > return PyBuildValue("i", nRet); > > } > > > If I changed INT64 nValue to be static INT64 nValue at LINE_HERE, it > > is ok. > > Why? > > I don't know, but I don't see either where Python is involved... you don't > use any argument and the returned Python object is not an INT64... > > -- > Gabriel Genellina The problem is obviously compiler involved. But I don't know why the sizeof INT64 is changed to be 4. From lycka at carmen.se Mon Jun 18 10:44:24 2007 From: lycka at carmen.se (Magnus Lycka) Date: Mon, 18 Jun 2007 16:44:24 +0200 Subject: Python's "only one way to do it" philosophy isn't good? In-Reply-To: <1hzt8l3.1npcm8u1jroax1N%aleax@mac.com> References: <1181368143.874341.273140@r19g2000prf.googlegroups.com> <1hzrsp4.7vjuav1aegg0tN%aleax@mac.com> <1hzsdrr.wxcx771jwicv5N%aleax@mac.com> <1182007539_10897@sp12lax.superfeed.net> <1hzt8l3.1npcm8u1jroax1N%aleax@mac.com> Message-ID: Alex Martelli wrote: > PL/1 is basically gone, but its legacy of "take what you need and leave > the rest" is unfortunately alive in other languages that are blind to > the enormous advantages of simplicity and uniformity. Reminds me of RUP... No wonder Ivar Jacobson gave up and started all over. From sjmachin at lexicon.net Sat Jun 2 23:21:31 2007 From: sjmachin at lexicon.net (John Machin) Date: Sat, 02 Jun 2007 20:21:31 -0700 Subject: pythonwin closes unexpectedlyI In-Reply-To: <1180831832.591780.203780@q66g2000hsg.googlegroups.com> References: <1180831832.591780.203780@q66g2000hsg.googlegroups.com> Message-ID: <1180840891.765666.42000@j4g2000prf.googlegroups.com> On Jun 3, 10:50 am, leegold wrote: > Hi, > > I run a script in PythonWin and obviously some sort of an error occurs > in the script and PythonWin closes. No warning, no error message just > closes. I definitely know the line of code that causes the problem and > will cite the code below. > > Note: I'm using ArcGIS 9.1 (Python 2.1 is bundled with it) and > trying:p to write a script. I know this works OK at work but on my > home system the problem occurs. I'm suspicious that maybe file sharing > permission problems are the cause. But I can't get any error messages > to even start figuring it out. Using WinXP. > > When the 2nd raw_input box opens ( GP.workspace = raw_input('workspace > path: ') and I enter the path and click Ok that's when PythonWin > closes. Here's code: > > import win32com.client, sys, os > > GP = win32com.client.Dispatch("esriGeoprocessing.GpDispatch.1") > > print 'I am in the program' # this works OK > > test001 = raw_input('workspace path: ') > > print test001 # this works OK > > try: > > GP.workspace = raw_input('workspace path: ') > > except: > > GP.AddMessage(GP.GetMessages(2)) > > print GP.GetMessages(2) Steps to try: 1. Add raise after the print statement. 2. Get pythonwin out of the equation; run your script from the command line. 3. If that doesn't give you a clue what the error is, remove the try/ accept/GP.AddMessage.../print lines and run it again from the command line. HTH, John From steven.bethard at gmail.com Tue Jun 12 19:09:23 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 12 Jun 2007 17:09:23 -0600 Subject: SimplePrograms challenge In-Reply-To: References: Message-ID: <466F27A3.8000106@gmail.com> Steve Howell wrote: > --- George Sakkis wrote: >> from itertools import count, ifilter >> def sieve(): >> seq = count(2) >> while True: >> p = seq.next() >> seq = ifilter(p.__rmod__, seq) >> yield p [snip] > Is there a way to broaden the problem somehow, so that > it can be a longer solution and further down on the > page, and so that I can continue to enforce my > somewhat arbitrary rule of ordering examples by how > long they are? How about we just comment it better? import itertools def iter_primes(): # an iterator of all numbers between 2 and +infinity numbers = itertools.count(2) # generate primes forever while True # generate the first number from the iterator, # which should always be a prime prime = numbers.next() yield prime # lazily remove all numbers from the iterator that # are divisible by prime we just selected numbers = itertools.ifilter(prime.__rmod__, numbers) I think that's 17-ish, though you could shrink it down by removing some of the spaces. STeVe From flyzone at technologist.com Tue Jun 12 08:54:55 2007 From: flyzone at technologist.com (Flyzone) Date: Tue, 12 Jun 2007 05:54:55 -0700 Subject: popen e pclose on python 2.3 question In-Reply-To: <1181650582.696577.259380@q19g2000prn.googlegroups.com> References: <1181650582.696577.259380@q19g2000prn.googlegroups.com> Message-ID: <1181652895.298327.168390@a26g2000pre.googlegroups.com> > i need to kill the child if the program take more than 300 ms, but i > need also to wait this 300 ms to have the reply. I reply by myself: from popen2 import Popen3 cmd = Popen3('command','r') waiting=0 while (cmd.poll()==-1): time.sleep(0.1) waiting+=1 if (waiting>3): os.kill(RESULT.pid,0) From doug at alum.mit.edu Wed Jun 27 13:47:06 2007 From: doug at alum.mit.edu (Douglas Alan) Date: Wed, 27 Jun 2007 13:47:06 -0400 Subject: Python's "only one way to do it" philosophy isn't good? References: <7x3b0nmkk6.fsf@ruckus.brouhaha.com> <7xejjzmk7u.fsf@ruckus.brouhaha.com> <7xy7i7xjl5.fsf@ruckus.brouhaha.com> <1182872972.417776.78650@o11g2000prd.googlegroups.com> <7xtzsuy7fe.fsf@ruckus.brouhaha.com> <1182955743.076746.114790@i38g2000prf.googlegroups.com> Message-ID: "Chris Mellon" writes: > Is this where I get to call Lispers Blub programmers, because they > can't see the clear benefit to a generic iteration interface? I think you overstate your case. Lispers understand iteration interfaces perfectly well, but tend to prefer mapping fuctions to iteration because mapping functions are both easier to code (they are basically equivalent to coding generators) and efficient (like non-generator-implemented iterators). The downside is that they are not quite as flexible as iterators (which can be hard to code) and generators, which are slow. Lispers have long since understood how to write mapping function to iterator converters using stack groups or continuations, but Common Lisp never mandated stack groups or continuations for conforming implementations. Scheme, of course, has continuations, and there are implementations of Common Lisp with stack groups. >> The difference is that lisp users can easily define python-like for >> while python folks have to wait for the implementation. > Yes, but Python already has it (so the wait time is 0), and the Lisp > user doesn't. So do Lispers, provided that they use an implementation of Lisp that has the aforementioned extensions to the standard. If they don't, they are the unfortunately prisoners of the standardizing committees. And, I guarantee you, that if Python were specified by a standardizing committee, it would suffer this very same fate. Regarding there being way too many good but incompatible implementations of Lisp -- I understand. The very same thing has caused Ruby to incredibly rapidly close the lead that Python has traditionally had over Ruby. There reason for this is that there are too many good but incompatible Python web dev frameworks, and only one good one for Ruby. So, we see that while Lisp suffers from too much of a good thing, so does Python, and that may be the death of it if Ruby on Rails keeps barreling down on Python like a runaway train. |>oug From SMERSH009X at gmail.com Thu Jun 21 22:37:07 2007 From: SMERSH009X at gmail.com (SMERSH009X at gmail.com) Date: Thu, 21 Jun 2007 19:37:07 -0700 Subject: How to Encode Parameters into an HTML Parsing Script Message-ID: <1182479827.076831.210260@z28g2000prd.googlegroups.com> I've written a Script that navigates various urls on a website, and fetches the contents. The Url's are being fed from a list "urlList". Everything seems to work splendidly, until I introduce the concept of encoding parameters for a certain url. So for example if I wanted to navigate to an encoded url http://online.investools.com/landing.iedu?signedin=true rather than just http://online.investools.com/landing.iedu How would I do this? How can I modify the script to urlencode these parameters: {signedin:true} and to associate them with a specific url from the urlList Thank you! import datetime, time, re, os, sys, traceback, smtplib, string, urllib2, urllib, inspect from urllib2 import build_opener, HTTPCookieProcessor, Request opener = build_opener(HTTPCookieProcessor) from urllib import urlencode def urlopen2(url, data=None, user_agent='urlopen2'): """Opens Our URLS """ if hasattr(data, "__iter__"): data = urlencode(data) headers = {'User-Agent' : user_agent} # User-Agent for Unspecified Browser return opener.open(Request(url, data, headers)) def badCharCheck(host,url): try: page = urlopen2("http://"+host+".investools.com/"+url+"", ()) pageRead= page.read() print "Loading:",url #print pageRead except: print "Failed: ", traceback.format_tb(sys.exc_info()[2]),'\n' if __name__ == '__main__': host= "online" urlList = ["landing.iedu","sitemap.iedu"] print "\n","***** Begin BadCharCheck for", host for url in urlList: badCharCheck(host,url) print'***** TEST FINISHED! Total Runs:' sys.exit() OUTPUT: ***** Begin BadCharCheck for online Loading: landing.iedu Loading: sitemap.iedu ***** TEST FINISHED! Total Runs: From horpner at yahoo.com Fri Jun 22 13:09:25 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Fri, 22 Jun 2007 17:09:25 GMT Subject: I need some cleanings tips and advice. References: <1182528064.446459.49420@n2g2000hse.googlegroups.com> <467bf4c9@news.nucleus.com> Message-ID: ["Followup-To:" header set to comp.lang.python.] On 2007-06-22, Colin B. wrote: > In comp.lang.perl.misc CleaningTips at gmail.com wrote: >> Me and my buddy made a website called www.stupidpinheads.com, its >> basically a free forum and free blog driven web site dedicated as a >> source people can goto to find out how to clean and remove stains from >> pretty much anything. Problem is, as of yet, you couldn't find out how >> to clean anything right now cause the site is new and no one has found >> it yet. > > Let's see if I get this right. > > You create a website for a subject that you know nothing about. Then you > try to solicit content in a bunch of programming language newsgroups. > > Wow, that's pretty pathetic, even for a google-groups poster! Maybe they lost the business plan. It's not surprising, since it was probably written on a napkin. -- Neil Cerutti Ask about our plans for owning your home --sign at mortgage company From sjmachin at lexicon.net Tue Jun 12 06:08:14 2007 From: sjmachin at lexicon.net (John Machin) Date: Tue, 12 Jun 2007 03:08:14 -0700 Subject: pyExcelerator and multiple worksheets In-Reply-To: <1181609885.434543.194560@i13g2000prf.googlegroups.com> References: <1181609885.434543.194560@i13g2000prf.googlegroups.com> Message-ID: <1181642894.207956.111170@z28g2000prd.googlegroups.com> On Jun 12, 10:58 am, aneesh.goel.r... at gmail.com wrote: > I'm using pyExcelerator to take a folder of CSV files and create Excel > workbooks for all of them, then generate an Excel workbook with the > data from all of them. > > Everything up until here works great; next, I make a second worksheet > on the last workbook which has summary details regarding the previous > worksheet. Here I run into a problem. The Excel form > > AVERAGE(Data!E5:E3053) > > where Data is the name of the worksheet being referenced (Summary is > the name of the worksheet where the formula is entered) isn't > recognized when I call Formula(). See my reply to your post on http://groups.google.com/group/python-excel Cheers, John From radamand at gmail.com Mon Jun 11 16:11:23 2007 From: radamand at gmail.com (Radamand) Date: Mon, 11 Jun 2007 20:11:23 -0000 Subject: REALLY need help with iterating a list. In-Reply-To: References: <1181586648.614514.228900@m36g2000hse.googlegroups.com> <1181588376.426556.46530@j4g2000prf.googlegroups.com> Message-ID: <1181592683.009076.24300@p77g2000hsh.googlegroups.com> On Jun 11, 1:23 pm, Fredrik Lundh wrote: > infidel wrote: > > How about something like this? > > > while serverlist: > > server = serverlist.pop(0) > > pinger = ping[server] > > if pinger.returncode==None: > > pinger.poll() > > serverlist.append(server) > > else: > > pingresult[server] = pinger.stdout.read() > > pingreturncode[server] = pinger.returncode > > > Basic idea: as long as there are servers in the list, pop the first > > one out of the list, see if it's done, and if it isn't, put it back on > > the end of the list. > > here's a simple variation of that, which is a bit more efficient, and > perhaps also a bit easier to use in the general case: > > while serverlist: > still_active = [] > for server in serverlist: > pinger = ping[server] > if pinger.returncode is None: > pinger.poll() > still_active.append(server) > else: > pingresult[server] = pinger.stdout.read() > pingreturncode[server] = pinger.returncode > serverlist = still_active > > Thats an interesting approach but, if the returncode for a given server is None say, 20 times in a row you will have append'ed that server to the list 20 times, i suppose you could check the list to see if its already there but thats a bit kludgey... also, the line "pinger = ping[server]" would have to be extracted from this loop otherwise your going to ping the same server repeatedly until it answers... From gagsl-py2 at yahoo.com.ar Tue Jun 19 11:42:49 2007 From: gagsl-py2 at yahoo.com.ar (gagsl-py2 at yahoo.com.ar) Date: Tue, 19 Jun 2007 12:42:49 -0300 (ART) Subject: Set timeout and kill external windows Message-ID: <952873.47388.qm@web32813.mail.mud.yahoo.com> At Saturday 16/06/2007 02:24, you wrote: > Thanks for your reply. I am new to Python and I cannot > seem to figure this out. I searched for examples based > on your recommendation below but couldn't do it. I am > not familiar with subprocess and WaitForSingleObject. > And I want to do this in Windows. Could you please > write me the few lines I need to do this? (Please keep posting on the list - other people may help too, and I don't read this email too often). Try this. (I had to use a private Popen attribute, _handle). import subprocess from win32event import WaitForSingleObject, WAIT_TIMEOUT from win32api import TerminateProcess def execute_and_wait(args, timeout=None): """Execute a command and wait until termination. If timeout elapses and still not finished, kill it. args: list containing program and arguments, or a single string. timeout: maximum time to wait, in ms, or None. """ p = subprocess.Popen(args) if timeout: ret = WaitForSingleObject(p._handle, timeout) if ret==WAIT_TIMEOUT: TerminateProcess(p._handle, 1) return None return p.wait() ret = execute_and_wait(["notepad", "c:\\python\\LICENSE.txt"], 5000) print "ret=",ret -- Gabriel Genellina __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From ed.taekema at gmail.com Fri Jun 1 16:50:01 2007 From: ed.taekema at gmail.com (ed.taekema at gmail.com) Date: Fri, 01 Jun 2007 20:50:01 -0000 Subject: Updated Jython Bibliography Message-ID: <1180731001.992210.125670@u30g2000hsc.googlegroups.com> To celebrate jython's recent progress I've updated my Jython Bibliography to include new resources I've tripped over in the last little while. Its available here: http://www.fishandcross.com/blog/?p=194 Please let me know if I've missed anything. From martin at v.loewis.de Thu Jun 14 17:03:26 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Thu, 14 Jun 2007 23:03:26 +0200 Subject: Serialization across languages? In-Reply-To: <46719c90$0$10851$88260bb3@free.teranews.com> References: <46719c90$0$10851$88260bb3@free.teranews.com> Message-ID: <4671ad1e$0$3511$9b622d9e@news.freenet.de> > First, what do I need to be aware of when sending arbitrary > data by a POST, and Second, is there a universally supported > version of what python can do with pickle? I mostly need > python and PHP, but perl would be nice too. You might want to use WDDX. There are WDDX libraries for Python, PHP, and Perl. Regards, Martin From uymqlp502 at sneakemail.com Fri Jun 8 15:30:01 2007 From: uymqlp502 at sneakemail.com (Russ) Date: Fri, 08 Jun 2007 12:30:01 -0700 Subject: compiling python and calling it from C/C++ In-Reply-To: <5csdfgF32026kU1@mid.uni-berlin.de> References: <1181276348.740945.312970@x35g2000prf.googlegroups.com> <5csdfgF32026kU1@mid.uni-berlin.de> Message-ID: <1181331001.206210.235160@n15g2000prd.googlegroups.com> Diez B. Roggisch wrote: > Russ schrieb: > > Is it possible to compile python code into a library (on unix), then > > link to it and call it from C/C++? If so, where can I learn how. > > You can't compile python, but what you can do is create a > library-wrapping around it using elmer which will make it C-callable. > > http://elmer.sourceforge.net/ This looks promising. Thanks. From topkatz at msn.com Thu Jun 14 17:02:01 2007 From: topkatz at msn.com (Talbot Katz) Date: Thu, 14 Jun 2007 17:02:01 -0400 Subject: Questions about mathematical and statistical functionality in Python Message-ID: Greetings Pythoners! I hope you'll indulge an ignorant outsider. I work at a financial software firm, and the tool I currently use for my research is R, a software environment for statistical computing and graphics. R is designed with matrix manipulation in mind, and it's very easy to do regression and time series modeling, and to plot the results and test hypotheses. The kinds of functionality we rely on the most are standard and robust versions of regression and principal component / factor analysis, bayesian methods such as Gibbs sampling and shrinkage, and optimization by linear, quadratic, newtonian / nonlinear, and genetic programming; frequently used graphics include QQ plots and histograms. In R, these procedures are all available as functions (some of them are in auxiliary libraries that don't come with the standard distribution, but are easily downloaded from a central repository). For a variety of reasons, the research group is considering adopting Python. Naturally, I am curious about the mathematical, statistical, and graphical functionality available in Python. Do any of you out there use Python in financial research, or other intense mathematical/statistical computation? Can you compare working in Python with working in a package like R or S-Plus or Matlab, etc.? Which of the procedures I mentioned above are available in Python? I appreciate any insight you can provide. Thanks! -- TMK -- 212-460-5430 home 917-656-5351 cell From paul.sijben at xs4all.nl Thu Jun 14 03:14:50 2007 From: paul.sijben at xs4all.nl (Paul Sijben) Date: Thu, 14 Jun 2007 09:14:50 +0200 Subject: Windows XP timezone language issue In-Reply-To: <1181770874.510964.157530@i13g2000prf.googlegroups.com> References: <466f8f45$0$329$e4fe514c@news.xs4all.nl> <1181770874.510964.157530@i13g2000prf.googlegroups.com> Message-ID: <4670eaea$0$333$e4fe514c@news.xs4all.nl> MRAB wrote: > On Jun 13, 7:31 am, Paul Sijben wrote: >> I ran into an internationalization issue. I need a consistent idea about >> the timezone my application is running on. However when I run the following: >> >>> import time >> >>> time.tzname >> >> I get back ('West-Europa (standaardtijd)', 'West-Europa (zomertijd)') >> which is in dutch (the language of the host machine) and verbose. >> I wanted to get ('CEST','CET') or something international so I can work >> with itin the same way on all platforms. >> >> That is the right way to find out the timezone in a consistent way >> across platforms (windows/linux/mac) and languages? >> > Well, time.timezone will return the timezone as an integer. > true, I am wondering if that is enough for my app. (with some of the odd timezones in the world and DTS issues and all.... From anamax at earthlink.net Tue Jun 26 11:49:32 2007 From: anamax at earthlink.net (Andy Freeman) Date: Tue, 26 Jun 2007 08:49:32 -0700 Subject: Python's "only one way to do it" philosophy isn't good? In-Reply-To: <7xy7i7xjl5.fsf@ruckus.brouhaha.com> References: <7x3b0nmkk6.fsf@ruckus.brouhaha.com> <1182750077.570603.160240@q69g2000hsb.googlegroups.com> <7xir9cbm0g.fsf@ruckus.brouhaha.com> <7xejjzmk7u.fsf@ruckus.brouhaha.com> <7xy7i7xjl5.fsf@ruckus.brouhaha.com> Message-ID: <1182872972.417776.78650@o11g2000prd.googlegroups.com> On Jun 26, 12:26 am, Paul Rubin wrote: > Precisely, I think that's what Alexander was trying to get across, Lisp > didn't have a uniform interface for traversing different types of sequence. And he's wrong, at least as far as common lisp is concerned - map does exactly that. http://www.lispworks.com/documentation/HyperSpec/Body/f_map.htm Map doesn't work on generators or iterators because they're not part of the common lisp spec, but if someone implemented them as a library, said library could easily include a map that handled them as well. From toby at tobiah.org Wed Jun 20 15:03:08 2007 From: toby at tobiah.org (Tobiah) Date: Wed, 20 Jun 2007 12:03:08 -0700 Subject: Reference current module? In-Reply-To: References: <4678201b$0$16340$88260bb3@free.teranews.com> Message-ID: <46796d2d$0$16309$88260bb3@free.teranews.com> Gabriel Genellina wrote: > En Tue, 19 Jun 2007 16:34:50 -0300, Steven Bethard > escribi?: > >> Tobiah wrote: >>> >>> getattr(current_module, 'foo') >>> >>> where 'current_module' is a handle the the one >>> that the code is in? Just like > A simple way would be using sys.modules[__name__]. > But I prefer using globals()['foo'] as it is simpler and does not assume > additional requirements (like __name__ still being the same, or the > module still available for importing). > > --Gabriel Genellina > In this case I really wanted a reference to the actual module, so that I could walk down from there in a sort of object mapping: def remote_call(call = 'foo.bar.other.thing'): destination_object = sys.modules[__name__] for part in call.split('.'): destination_object = getattr(destination_object, part) Tobiah -- Posted via a free Usenet account from http://www.teranews.com From steve at REMOVE.THIS.cybersource.com.au Fri Jun 1 21:12:34 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sat, 02 Jun 2007 11:12:34 +1000 Subject: subexpressions References: Message-ID: On Fri, 01 Jun 2007 07:09:50 -0400, Steve Holden wrote: >>>>> The real answer is of course: Use a function. >>>> But what about something like >>>> >>>> lambda x: sin(y)+cos(y) where y=x*x >>>> >>>> ? >>>> May be this could be a PEP? If there is no straight way to do this. >>> def f(x): >>> y = x*x >>> return sin(y) + cos(y) >>> >>> What is not straightforward about that? >> >> This code is needed once in a map, so I don't want 3+ extra lines. >> Solution seemed so simple... >> I always considered python as languague, where simple things do not require >> extensive coding. >> Moreover, this construction is common thing in functional programming. >> >> > Stop thinking of three lines as "extensive coding" and your problem > disappears immediately. The F-bot once suggested adding a clause to the Zen of Python about "writing two lines of code is not a sin" or "cramming two lines of code into one is not a virtue" (my paraphrases). Check the two alternatives: def f(x): y = x*x return sin(y) + cos(y) 44 key presses, including tabs and newlines and a blank line after the function, but excluding counting the shift key separately. lambda x: (lambda y: sin(y) + cos(y))(x*x) 42 key presses. Apart from the extremely minor issue of "namespace pollution", I think that speaks for itself. -- Steven. From brian at sweetapp.com Sat Jun 30 17:33:57 2007 From: brian at sweetapp.com (Brian Quinlan) Date: Sat, 30 Jun 2007 22:33:57 +0100 Subject: Building a Python app with Mozilla In-Reply-To: <46867432.7060400@codebykevin.com> References: <46867432.7060400@codebykevin.com> Message-ID: <4686CC45.9010405@sweetapp.com> Kevin Walzer wrote: > Komodo is not a Python application. It is a Mozilla application that > supports Python development. Komodo is more akin to Thunderbird and > Firefox than anything else; it uses the XUL framework for rendering > widgets, if I'm not mistaken. If you want to build an application like > Komodo, get a book on developing with the Mozilla framework (XUL, XPCOM, > and all that) and look at that. Python has little to do with that. Most application logic in Komodo is implemented in Python, using the PyXPCOM bindings. The UI is implemented using XUL and JavaScript. The editor is Scintilla (C++). ../Komodo Edit.app/Contents/MacOS % find . -name "*.py" | xargs wc ... ... 126392 456858 4949602 total This doesn't include the python code in the Python libraries themselves. Cheers, Brian From claird at lairds.us Tue Jun 5 14:36:26 2007 From: claird at lairds.us (Cameron Laird) Date: Tue, 5 Jun 2007 18:36:26 +0000 Subject: How do you htmlentities in Python References: <1180977447.745432.109040@q19g2000prn.googlegroups.com> Message-ID: In article <1180977447.745432.109040 at q19g2000prn.googlegroups.com>, Matimus wrote: >On Jun 4, 6:31 am, "js " wrote: >> Hi list. >> >> If I'm not mistaken, in python, there's no standard library to convert >> html entities, like & or > into their applicable characters. >> >> htmlentitydefs provides maps that helps this conversion, >> but it's not a function so you have to write your own function >> make use of htmlentitydefs, probably using regex or something. >> >> To me this seemed odd because python is known as >> 'Batteries Included' language. >> >> So my questions are >> 1. Why doesn't python have/need entity encoding/decoding? >> 2. Is there any idiom to do entity encode/decode in python? >> >> Thank you in advance. > >I think this is the standard idiom: > >>>> import xml.sax.saxutils as saxutils >>>> saxutils.escape("&") >'&' >>>> saxutils.unescape(">") >'>' >>>> saxutils.unescape("A bunch of text with entities: & > <") >'A bunch of text with entities: & > <' > >Notice there is an optional parameter (a dict) that can be used to >define additional entities as well. . . . Good points; I like your mention of the optional entity dictionary. It's possible that your solution is to a different problem than the original poster intended. has de- tails about HTML entities vs. XML entities. From sjmachin at lexicon.net Sun Jun 10 08:45:47 2007 From: sjmachin at lexicon.net (John Machin) Date: Sun, 10 Jun 2007 05:45:47 -0700 Subject: matching objects by a tuple field criterion In-Reply-To: <1181478777.274329.276020@g37g2000prf.googlegroups.com> References: <1181473124.790391.293120@r19g2000prf.googlegroups.com> <5d25b6F3215liU1@mid.uni-berlin.de> <5d26e3F337ov1U1@mid.uni-berlin.de> <1181478777.274329.276020@g37g2000prf.googlegroups.com> Message-ID: <1181479547.039193.20450@i38g2000prf.googlegroups.com> On Jun 10, 10:32 pm, bullockbefriending bard wrote: > quite so, i rephrased docstring to be: > > """criteria is an iterable containing either '*' instances or strings > of comma-separated integers. e.g. ['*','1,2,3', '11,12']""" > > thanks very much for the idea! upon further reflection, this seems to > be a more elegant solution for my case than the ad-hoc generator or > list comprehension approach. this is because i *do* have to filter > data based on multiple single field criteria and i know all of these > criteria at the same time - so it makes a lot of sense to do as you > have done and then only do one filter operation to pull out all the > objects i am interested in. """i want to search on *one only* tuple field/value.""" """i will only ever specify an integer match for one tuple field.""" """the cheque's in the mail""" """of course i'll still love you in the morning""" So augment my pre-built approach by intersection (or union? your wording is somewhat vague) of the selected answer sets. From nick at craig-wood.com Mon Jun 25 05:30:06 2007 From: nick at craig-wood.com (Nick Craig-Wood) Date: Mon, 25 Jun 2007 04:30:06 -0500 Subject: automatical pdf generating References: <1182700820.325024.107040@g4g2000hsf.googlegroups.com> Message-ID: Jackie wrote: > There are 50 folders in my hard driver C: > C:\01.c:\02,...,c:\50 > > There are 4 pictures in each folder: > 1.jpg,2.jpg,3.jpg,4.jpg > > For each folder, I want to print the 4 pictures into a single-paged > pdf file (letter sized; print horizontally). All together, I want to > get 50 pdf files with names: 01.pdf,02.pdf,...,50.pdf. ImageMagick eats this sort of thing for lunch. It is a set of command line tools for unix. You can get them with cygwin also Eg montage -geometry 1000x1000+100+100 1.jpg 2.jpg 3.jpg 4.jpg 01.pdf Which resizes each image to a max dimension of 1000 pixels and then tiles them into a PDF. -- Nick Craig-Wood -- http://www.craig-wood.com/nick From richardjones at optushome.com.au Fri Jun 8 19:50:07 2007 From: richardjones at optushome.com.au (Richard Jones) Date: Sat, 09 Jun 2007 09:50:07 +1000 Subject: Bragging about Python References: Message-ID: <4669eb2f$0$17155$afc38c87@news.optusnet.com.au> Steve Howell wrote: > --- Szabolcs Nagy wrote: >> >> actually i don't like when a tutorial uses over >> complicated cute names >> if the context is obvious (fibonacci) then we don't >> need to add >> 'parent_rabbits' and such identifiers > > I still prefer the use of "rabbits," but I don't mind > if people change that, as I understand the brevity argument. The rabbit naming scheme makes the code far more accessible to people who aren't as familiar with fibonacci. Really, this is about making Python accessible to more people, not the same people it's currently accessible to :) Richard From mike.klaas at gmail.com Mon Jun 25 16:34:00 2007 From: mike.klaas at gmail.com (Klaas) Date: Mon, 25 Jun 2007 20:34:00 -0000 Subject: Using a switch-like if/else construct versus a dictionary? In-Reply-To: <1182282008.522677.269730@g4g2000hsf.googlegroups.com> References: <1182282008.522677.269730@g4g2000hsf.googlegroups.com> Message-ID: <1182803640.772899.237820@i38g2000prf.googlegroups.com> On Jun 19, 12:40 pm, asincero wrote: > Which is better: using an if/else construct to simulate a C switch or > use a dictionary? Example: Whichever results in the clearest code that meets the performance requirements. FWIW, if you define the dictionary beforehand, the dict solution is O(1) while if/else is O(N), which can be important. -Mike From nikbaer at gmail.com Wed Jun 13 22:11:22 2007 From: nikbaer at gmail.com (nik) Date: Thu, 14 Jun 2007 02:11:22 -0000 Subject: save class In-Reply-To: References: <1181784016.454693.42340@o11g2000prd.googlegroups.com> Message-ID: <1181787082.712869.72770@z28g2000prd.googlegroups.com> On Jun 13, 6:48 pm, "Gabriel Genellina" wrote: > En Wed, 13 Jun 2007 22:20:16 -0300, nik escribi?: > > > I would like to create a class and then save it for re-use later. I > > have tried to usepickle, but am not sure if that is right. I am > > sorry, but I am new to python. > > Do you want to save the *source*code* of your class, or do you want to > save created *instances* -objects- of your classes to retrieve them later > (like a database)? > > > Basically, I have a class, Map. I want to be able to create new maps: > > MapA, MapB... that have Map as the base class. > > > start with- > > class Map: > > pass > > > and then get a different class > > > class MapA(Map): > > pass > > > that can be saved in a .py file for re-use > > You just create the .py file with any text editor, containing the source > code for all your classes. > > > so far I thought that - > > cls = new.classobj('MapA', (Map, ), {}) > > file = open('somefile', mode='w') > >pickle.dump(cls, file) > > > -might work, but it didn't.... can anybody point me in the right > > direction? I know that classes must get saved from the interactive > > console, so I would think that it would be a standard thing to do. > > This would try to save the *class* definition, which is usually not > required because they reside on your source files. > If this is actually what you really want to do, try to explain us exactly > why do you think so. Chances are that there is another solution for this. > > -- > Gabriel Genellina Thanks for the response. It would seem that I want to actually save the source code for the class. I know that I could of course open up an editor and just make it, but my ideal would be to have the base class, Map, be able to make the sub-classes. I don't want the class definition. What I want is an actual class that I could later import and use somewhere else. I am planning to have each one of these map objects contain a different dictionary and then be able to import the map into the application, but have certain methods defined in the Map super-class to draw data out of the specific map's specific dictionary. I hope that makes sense. Something like, class Map: dict = {} def DoSomething(self): pass def MakeNewMapSubClass(self, newclassname): """ make a new file, newclassname.py that contains a new class newclassname(Map) that inherits from base-class Map. Thanks, Nik From ljz at asfast.com Sun Jun 3 20:28:33 2007 From: ljz at asfast.com (Lloyd Zusman) Date: Sun, 03 Jun 2007 20:28:33 -0400 Subject: subexpressions (OT: math) References: <4662675b$1_5@news.bluewin.ch> <1180890214.317409.85100@w5g2000hsg.googlegroups.com> <1180894045.538031.111610@g4g2000hsf.googlegroups.com> <1180895200.108582.313010@k79g2000hse.googlegroups.com> Message-ID: <87y7j0imvi.fsf@asfast.com> "Steven D'Aprano" writes: > On Sun, 03 Jun 2007 11:26:40 -0700, Stebanoid at gmail.com wrote: > >> if you are discordant read more :P : >> sine is a dimensionless value. >> if we expand sine in taylor series sin(x) = x - (x^3)/6 + (x^5)/120 >> etc. >> you can see that sin can be dimensionless only if x is dimensionless >> too. >> >> I am a professional physicist and a know about what I talk > > I am confused why you get different results for the square root of an > angle depending on whether you use degrees or radians: > > sqrt(25?) = 5? = 0.087266462599716474 radians > sqrt(25*pi/180) = 0.66055454960100179 radians > > If angles are dimensionless numbers, then: > > degrees_to_radians(sqrt(25?)) > > should equal > > sqrt(degrees_to_radians(25?)) > > but they don't. That's because for arbitrary functions f and g, f(g(x)) is not equivalent to g(f(x)) This has nothing to do with whether or not x is a dimensionless number. (replace "f" with "degrees_to_radians" and "g" with "sqrt") -- Lloyd Zusman ljz at asfast.com God bless you. From reedobrien at gmail.com Sat Jun 2 18:16:57 2007 From: reedobrien at gmail.com (reed) Date: Sat, 02 Jun 2007 22:16:57 -0000 Subject: SMTPlib Sender Refused? In-Reply-To: <1180804851.201748.215890@k79g2000hse.googlegroups.com> References: <1180804851.201748.215890@k79g2000hse.googlegroups.com> Message-ID: <1180822617.891663.215620@p47g2000hsd.googlegroups.com> On Jun 2, 1:20 pm, erikcw wrote: > Hi, > > I'm trying to send an email message with python, and I'm getting this > error: > > Traceback (most recent call last): > File "wa.py", line 430, in ? > main() > File "wa.py", line 425, in main > smtp.sendmail(fromaddr, to, msg.encode('utf-8')) > File "/usr/local/lib/python2.4/smtplib.py", line 680, in sendmail > raise SMTPSenderRefused(code, resp, from_addr) > smtplib.SMTPSenderRefused: (503, 'sender already given', > '... at mydomain.com') > > What is causing this? > > Thanks! > Erik This error is given when the MAIL command has already been sent. Usually this is indicative of some command failing (maybe invalid rcpt to:??) and retrying without sending the RSET command. Try connecting manually and see what you get. ~r From notbob at nothome.com Thu Jun 21 10:58:16 2007 From: notbob at nothome.com (notbob) Date: Thu, 21 Jun 2007 09:58:16 -0500 Subject: The Modernization of Emacs References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182370894.001918.36590@k79g2000hse.googlegroups.com> <1182372821.298343.316860@g4g2000hsf.googlegroups.com> <1182375321.067664.190780@o61g2000hsh.googlegroups.com> <86hcp1l6hb.fsf@lola.quinscape.zz> Message-ID: On 2007-06-21, David Kastrup wrote: > You know you can use something like > C-x C-f /su::/etc/fstab RET > (or /sudo::/etc/fstab) in order to edit files as root in a normal > Emacs session? As I understand it, this will only work for ver 22 and later or if you have tramp(?) installed. I have 2.3.1 (no tramp) and all I get is: ftp> open su ftp: su: Unknown host I'm looking at upgrading to 22 for a couple other features, too. nb From needpassion at gmail.com Wed Jun 13 20:47:16 2007 From: needpassion at gmail.com (mike) Date: Wed, 13 Jun 2007 17:47:16 -0700 Subject: How can I capture all exceptions especially when os.system() fail? Thanks Message-ID: <1181782036.646379.28510@g37g2000prf.googlegroups.com> Hi Guys, Following piece of code can capture IOError when the file doesn't exist, also, other unknown exceptions can be captured when I press Ctrl-C while the program is sleeping(time.sleep). Now the question is: when I run the non-exist command, the exception cannot be captured. Here is the code: =================================== #!/usr/bin/python import os import sys import time try: fh = open("tt.py") time.sleep(10) #os.system("wrong_command_test") except IOError: print 'failed to open.' sys.exit(0) except: print 'Some exceptions occurred.' else: print 'well', print 'Done' =================================== when the tt.py doesn't exist, the script printed: failed to open. when the tt.py exists, the script printed: well done when I press Ctrl-C while the program is sleeping, the script printed: Some exceptions occurred. Done So far so good, then I changed the code to run a non-exist command "wrong_command_test"(commented the open and sleep lines), then the script printed: sh: wrong_command_test: command not found well Done Any opinions would be appreciated. Mike From steve at REMOVE.THIS.cybersource.com.au Tue Jun 19 20:01:13 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Wed, 20 Jun 2007 10:01:13 +1000 Subject: Python's "only one way to do it" philosophy isn't good? References: <1181368143.874341.273140@r19g2000prf.googlegroups.com> Message-ID: On Tue, 19 Jun 2007 17:46:35 -0400, Douglas Alan wrote: > I think that most people who program in Scheme these days don't do it > to write practical software. They either do it to have fun, or for > academic purposes. On the other hand, most people who program in > Python are trying to get real work done. Which is precisely why I > program a lot in Python and very little in Scheme these days. It's > nice to have the batteries included. So, once you've succeeded in your campaign to make Python more like Scheme, what language will you use for getting real work done? And how long will it take before Schemers start agitating for it to become more like Scheme? There is a huge gulf between the claim that Python needs to be more Scheme-like, and the fact that by your own admission you use Python, not Scheme, for real work. What benefit will be gained? The ability to "directly explore some pretty mind-bending stuff ... in a hackerly, brain-expanding/brain-teaser kind of way"? -- Steven. From george.sakkis at gmail.com Mon Jun 11 00:46:59 2007 From: george.sakkis at gmail.com (George Sakkis) Date: Mon, 11 Jun 2007 04:46:59 -0000 Subject: ANN: papyros 0.1 Message-ID: I am pleased to announce the first alpha release of Papyros, a lightweight platform-independent package for parallel processing. Papyros provides a master-slave model: clients can submit jobs to a master object which is monitored by one or more slave objects that do the real work. Two main implementations are provided, one using multiple threads and one multiple processes in one or more hosts through Pyro (http://pyro.sourceforge.net/). Papyros' primary design goal is simplicity: a time consuming loop in a single-thread single-process program can be replaced with an equivalent parallel version in a few lines, with minimal boilerplate code overhead. To get a copy, visit http://code.google.com/p/papyros/; also available from the Cheeseshop at http://www.python.org/pypi/papyros/. George Sample code ========== Here's a basic example; for more details go through the README and the included demo script. import papyros class FactorizationJob(papyros.Job): '''A job for computing the prime factors of an integer.''' def __call__(self, n): # <-- find the prime factors here --> # return factors # create a multithreded master with three slave threads from papyros.multithreaded import MultiThreadedMaster master = MultiThreadedMaster(3) # factorize concurrently ten random numbers import random for _ in xrange(10): master.addJob(FactorizationJob(random.randrange(1e6,1e7))) # fetch each job as soon as it finishes for job in iter(master.popProcessedJob, None): factors = job.result print '%d prime factors for %d: %s' % (len(factors), job.args[0], factors) From timr at probo.com Sat Jun 23 01:08:31 2007 From: timr at probo.com (Tim Roberts) Date: Sat, 23 Jun 2007 05:08:31 GMT Subject: The Modernization of Emacs: terminology buffer and keybinding References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182272495.990807.99110@a26g2000pre.googlegroups.com> <87tzt3ihev.fsf@kobe.laptop> <1182370216.961241.6960@n60g2000hse.googlegroups.com> <85zm2ufjpb.fsf@lola.goethe.zz> <1182372592.803332.288260@u2g2000hsc.googlegroups.com> <1182373919.262388.100740@c77g2000hse.googlegroups.com> <85r6o6fhkb.fsf@lola.goethe.zz> <1182375045.626510.188170@m36g2000hse.googlegroups.com> Message-ID: <4jap73pfdme1pth2tji1vmd8j9qqss7pcf@4ax.com> Bjorn Borud wrote: > >bah, UNIX is not user hostile; it is just selective about its >friends. Right. My favorite Unix quote is from the same source (Dennis Ritchie): Unix is the answer. You just have to phrase the question very carefully. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From frank at chagford.com Mon Jun 11 08:27:35 2007 From: frank at chagford.com (Frank Millman) Date: Mon, 11 Jun 2007 05:27:35 -0700 Subject: Postpone creation of attributes until needed In-Reply-To: References: <1181553891.447344.109390@g4g2000hsf.googlegroups.com> <1181559496.911368.219210@p77g2000hsh.googlegroups.com> Message-ID: <1181564855.890242.116840@m36g2000hse.googlegroups.com> On Jun 11, 1:56 pm, Steven D'Aprano wrote: > > Unless you have thousands and thousands of instances, __slots__ is almost > certainly not the answer. __slots__ is an optimization to minimize the > size of each instance. The fact that it prevents the creation of new > attributes is a side-effect. > Understood - I am getting there slowly. I now have the following - >>> class A(object): ... def __init__(self,x,y): ... self.x = x ... self.y = y ... def __getattr__(self,name): ... print 'getattr',name ... self.compute() ... return self.__dict__[name] ... def compute(self): # compute all missing attributes ... self.__dict__['z'] = self.x * self.y [there could be many of these] >>> a = A(3,4) >>> a.x 3 >>> a.y 4 >>> a.z getattr z 12 >>> a.z 12 >>> a.q KeyError: 'q' The only problem with this is that it raises KeyError instead of the expected AttributeError. > > You haven't told us what the 'compute' method is. > > Or if you have, I missed it. > Sorry - I made it more explicit above. It is the method that sets up all the missing attributes. No matter which attribute is referenced first, 'compute' sets up all of them, so they are all available for any future reference. To be honest, it feels neater than setting up a property for each attribute. I would prefer it if there was a way of raising AttributeError instead of KeyError. I suppose I could do it manually - try: return self.__dict__[name] except KeyError: raise AttributeError,name Frank From gerald.kaszuba at gmail.com Sun Jun 17 02:52:01 2007 From: gerald.kaszuba at gmail.com (Gerald Kaszuba) Date: Sun, 17 Jun 2007 06:52:01 -0000 Subject: Is there a way to hook into module destruction? In-Reply-To: <1182062751.957483.278010@o11g2000prd.googlegroups.com> References: <1182060189.246474.128710@j4g2000prf.googlegroups.com> <1182062751.957483.278010@o11g2000prd.googlegroups.com> Message-ID: <1182063121.821089.285540@o11g2000prd.googlegroups.com> > I doubt python calls __del__ when unloading module... and plus, I > don't really think python does module unloading though. del module Ah! Apologies... I mis-read the question. Unloading or at least destroying the reference to a loaded module, you could go for "del module_name"? -- Gerald Kaszuba http://geraldkaszuba.com From mschaef at eris.io.com Tue Jun 26 22:47:53 2007 From: mschaef at eris.io.com (MSCHAEF.COM) Date: Tue, 26 Jun 2007 21:47:53 -0500 Subject: The Modernization of Emacs: terminology buffer and keybinding References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182553682.197778.138500@g37g2000prf.googlegroups.com> <87r6nzc9nu.fsf@mail.eng.it> <1182904631.083783.170640@o61g2000hsh.googlegroups.com> Message-ID: <24udnWmPrOxEUhzbnZ2dnUVZ_oqmnZ2d@io.com> In article <1182904631.083783.170640 at o61g2000hsh.googlegroups.com>, Twisted wrote: ... >In the other corner, we have just about every Unix application ever >developed. When a user needs help, they may do such things as manually >explore the directories where the application was installed >(equivalent to rooting around in C:\Program Files\Appname for .hlp >files, because F1 didn't work and there was no "help" menu, I just pressed F1 in a running session of a Emacs under Ubuntu Linux... it brought up online help. >if such a thing ever happened on Windoze). Such things happen _all the time_ on Windows, particularly if you count help menus that lead solely to useless About boxes. This might be a moot point anyway, given the high number of people I've met that don't even bother reading online help in the first place. -Mike -- http://www.mschaef.com From twisted0n3 at gmail.com Wed Jun 20 17:30:45 2007 From: twisted0n3 at gmail.com (Twisted) Date: Wed, 20 Jun 2007 21:30:45 -0000 Subject: The Modernization of Emacs: terminology buffer and keybinding In-Reply-To: <85r6o6fhkb.fsf@lola.goethe.zz> References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182272495.990807.99110@a26g2000pre.googlegroups.com> <87tzt3ihev.fsf@kobe.laptop> <1182370216.961241.6960@n60g2000hse.googlegroups.com> <85zm2ufjpb.fsf@lola.goethe.zz> <1182372592.803332.288260@u2g2000hsc.googlegroups.com> <1182373919.262388.100740@c77g2000hse.googlegroups.com> <85r6o6fhkb.fsf@lola.goethe.zz> Message-ID: <1182375045.626510.188170@m36g2000hse.googlegroups.com> On Jun 20, 5:21 pm, David Kastrup wrote: > Twisted writes: > > On Jun 20, 4:49 pm, Twisted wrote: > >> On Jun 20, 4:35 pm, David Kastrup wrote: > >> > Twisted writes: > >> > > I continue to suspect that there's an ulterior motive for making and > >> > > keeping certain software actively beginner-hostile; a certain macho > >> > > elitism also seen with light aircraft pilots and commented on at > >> > >www.asktog.com(exactURLescapes me; sorry). > > >> > You are babbling. > > >> No, I am not. You, however, are being gratuitously insulting. > > > I have that exact URL now -- > >http://www.asktog.com/columns/027InterfacesThatKill.html > > Utterly unrelated to Emacs. I think it is quite relevant. Clunky computer interfaces may not be so dramatically dangerous, but they certainly can hamper productivity. Between Windows bugs and gratuitous misfeatures (e.g. DRM) and Unix clunkiness, billions of dollars of potential productivity is lost worldwide every *month*. From mistabean at gmail.com Tue Jun 5 02:41:19 2007 From: mistabean at gmail.com (mistabean at gmail.com) Date: Mon, 04 Jun 2007 23:41:19 -0700 Subject: Embedding Python in C In-Reply-To: References: <1180969118.795850.15160@w5g2000hsg.googlegroups.com> Message-ID: <1181025679.979188.52960@h2g2000hsg.googlegroups.com> On 5 Jun., 01:32, "Gabriel Genellina" wrote: > En Mon, 04 Jun 2007 11:58:38 -0300, escribi?: > > > > > > > Onwards to the problem, I have been having difficulty embedding a > > python module into my C/C++ program. (just a test program before > > moving on into the real thing). I have been making test runs using the > > codes fromhttp://docs.python.org/ext/pure-embedding.htmlas a basic, > > but modifiying it now as a function inside my C/C++ code. > > > Problem started when I started passing an array as an argument. The > > module also need an array as an argument, but somehow I can't make > > them to go pass the "input-error checking" of the module. > > > The code for argument building and calling are as follows: > > > void CallSnake(char ModName[], char FuncName[], double result[]) > > { > > ... > > /*Some operations to import modname, and preping FuncName, all is > > ok*/ > > ... > > /*Processing the result array and calling the function, problem > > time*/ > > pArgs = PyTuple_New(MAX_ELEMENT); > > Should check for a NULL return value. > > > pArg = PyList_New(1); > > Same here. > > > for (i = 0; i < MAX_ELEMENT; ++i) > > { > > pValue = Py_BuildValue("d", result[i]); > > I'd use PyFloat_FromDouble here. > > > PyTuple_SetItem(pArgs, i, pValue); > > > if (!(*pArgs).ob_refcnt) > > What do you expect from this? pArgs is a newly created tuple - unless you > DECREF it explicitely, ob_refcnt should never be 0. (Also, the -> operator > exists for exactly this usage). > > > PyList_SetItem(pArg, 0, pArgs); > > pValue = PyObject_CallFunctionObjArgs(pFunc,pArg,NULL); > > You didn't show us how you got pFunc here. Just to make it clear, you are > calling pFunc with a single argument, which is a list that contains a > single element, which is a tuple containing exactly MAX_ELEMENT float > objects. > > > Traceback > > if x.ndim != 1; /*x is the input array, checking if it's a 1D*/ > > AttributeError: 'list' object has no attribute 'ndim' > > Python lists don't have a ndim attribute. Perhaps you want some kind of > Numeric array? (ndarray?) > > > I have been trying many call variations, but alas, I think the problem > > lies in the list building process. I have no problems calling a non- > > arrayed (albeit,still single) argument. > > Yes, it appears that you are building a plain list but your code is > expecting another kind of object. I'm unfamiliar with Numeric arrays, if > that is what you need; perhaps someone else can help, or ask again in a > Numeric-specific list. > > -- > Gabriel Genellina- Zitierten Text ausblenden - > > - Zitierten Text anzeigen - yeah, i was looking at am array full of numbers. import numpy,scipy, maybe pylab too while i was testing out the function over at a python shell, make a linspace, sin it, and then call the function (which also is from the scipy cookbook). Is numeric arrays (or ndarray) unlike normal listing then? Since I started off programming in C, I am having a bit of a confusion identifiying the different type of arrays, listing and tuples and such... (since it's just "build an array of type so and so, and pass it over" ^^;;) the reason i didn't show pFunc is that because it is the result of operations done to FuncName (ModName = module to be imported, FuncName = function to be called), therefore i feel it would be a bit waste of time/space to put in the pFunc function, since I didn't change the operations concerning pFunc other than changing argv[1] to FuncName from the link i gave (and not the core of my problem). so yeah, maybe I am building and passing the array/calling the function the wrong way... will have to take a look at numpy/numerical specific C API and stuff now thanks for your time and the help From mail at microcorp.co.za Thu Jun 14 02:32:38 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Thu, 14 Jun 2007 08:32:38 +0200 Subject: Goto References: <1181762459.749538.151730@z28g2000prd.googlegroups.com> Message-ID: <016501c7ae68$1e70f6e0$03000080@hendrik> "HMS Surprise" wrote: > > How does one effect a goto in python? I only want to use it for debug. > I dasn't slap an "if" clause around the portion to dummy out, the > indentation police will nab me. I use a global boolean called trace: if trace: do debug stuff But to try to answer your question: There are two gotos in standard Python. They are spelled: "continue" and "break" The first jumps to the start of a loop, and the last to after the end of one. Anything more fancy is "Verboten" - except, that, if you ask nicely, John Machin might explain his comefrom construct. And maybe I will understand it this time around... - Hendrik From filox_realmmakniovo at yahoo.com Mon Jun 18 15:48:36 2007 From: filox_realmmakniovo at yahoo.com (filox) Date: Mon, 18 Jun 2007 21:48:36 +0200 Subject: getting the size of an object References: <1182182932.947333.251020@o61g2000hsh.googlegroups.com> Message-ID: "Brett Hoerner" wrote in message news:1182182932.947333.251020 at o61g2000hsh.googlegroups.com... > On Jun 18, 11:07 am, "filox" wrote: >> is there a way to find out the size of an object in Python? e.g., how >> could >> i get the size of a list or a tuple? > > "Size" can mean a lot of things, > > len(my_list) > len(my_tuple) > > Although I have the feeling you mean "how many bytes does this object > take in memory" - and I believe the short answer is no. > is there a long answer? what i want is to find out the number of bytes the object takes up in memory (during runtime). since python has a lot of introspection mechanisms i thought that should be no problem... -- You're never too young to have a Vietnam flashback From kyosohma at gmail.com Mon Jun 25 13:45:07 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Mon, 25 Jun 2007 10:45:07 -0700 Subject: Changing sound volume In-Reply-To: References: <1182727056.516883.241390@o61g2000hsh.googlegroups.com> Message-ID: <1182793507.371402.263850@q69g2000hsb.googlegroups.com> On Jun 25, 7:48 am, simon kagwe wrote: > > And finally a way that might work using ctypes: > > >http://mail.python.org/pipermail/python-win32/2006-March/004436.html > > > Mike > > Hi, > > Thanks for your reply. > > I had already read about the Snack, but I can't use it since my program uses > wxPython for the GUI and Snack requires tk. The best option was the ctypes > method you told me about. I used the code in the sample, but I am getting the > following error: > > exceptions.WindowsError Error 11 while setting volume > > The author of the code claims it works. What could be causing the above error? > > [ I am using Python 2.4.4 and ctypes 1.0.1 ] > > Regards, > Simon I'm not sure what the deal is. I just tested that script on my workstation and it works fine for me. I think I have the latest ctypes, but I can't figure out how to get the version number off of it to be sure. I am running Python 2.4.3 on Windows XP SP2 though. You might try that pygames idea. I've never tried it, but you'd think that would work. Mike From dustin at v.igoro.us Sun Jun 10 15:57:05 2007 From: dustin at v.igoro.us (Dustin J. Mitchell) Date: Sun, 10 Jun 2007 14:57:05 -0500 Subject: Redux: Allowing 'return obj' in generators Message-ID: <20070610195705.GS19216@v.igoro.us> This question was first brought up in October of 2005[1], and was included in the "Unresolved Issues" section of my microthreading PEP, which I have quietly withdrawn from consideration due to lack of community interest. PEP 255 says Q. Then why not allow an expression on "return" too? A. Perhaps we will someday. In Icon, "return expr" means both "I'm done", and "but I have one final useful value to return too, and this is it". At the start, and in the absence of compelling uses for "return expr", it's simply cleaner to use "yield" exclusively for delivering values. As those of you who looked at my PEP or are familiar with some of the implementations will realize, microthreaded functions are syntactically generator functions, but semantically act as regular functions. There is a well-defined meaning to 'return x' in such a function: take the value of x, and use it in the expression where this function was called. For example: def read_integer(sock): txt = yield sock.readline().strip() try: return int(txt) except: raise AppProtocolError("Expected an integer") The implementation of the syntax would be similar to that of an expressionless 'return', but supplying the expression_list to the StopIteration's 'args' -- this is described quite well in Piet Delport's post[2]. Given this use-case (and note that I chose an example that will exercise the interactions of try/except blocks with the StopIteration behavior), is it time to revisit this issue? BDFL said: I urge you to leave well enough alone. There's room for extensions after people have built real systems with the raw material provided by PEP 342 and 343.[3] and Nick Coghlan said (to applause from GvR): I'm starting to think we want to let PEP 342 bake for at least one release cycle before deciding what (if any) additional behaviour should be added to generators.[4] I think we have a decent number of implementations in the wild now (I have learned of Christopher Stawarz's 'multitask'[5] since last posting my PEP). With 2.5.1 out, might I suggest this is worth reconsidering for the 2.6 release? Dustin [1] http://www.python.org/dev/summary/2005-10-01_2005-10-15/#allowing-return-obj-in-generators [2] http://mail.python.org/pipermail/python-dev/2005-October/056957.html [3] http://mail.python.org/pipermail/python-dev/2005-October/057119.html [4] http://mail.python.org/pipermail/python-dev/2005-October/057133.html [5] http://o2s.csail.mit.edu/o2s-wiki/multitask From matiassurdi at gmail.com Sat Jun 2 11:45:48 2007 From: matiassurdi at gmail.com (Matias Surdi) Date: Sat, 02 Jun 2007 17:45:48 +0200 Subject: Delete a file from a CGI References: Message-ID: Steve Holden escribi?: > Matias Surdi wrote: >> Thanks for your reply. >> >> This is the code that creates the file: >> lock_file = open(".lock","w") >> lock_file.write("test") >> lock_file.close() >> #Change permissions so that CGI can write lock file >> os.chmod(".lock",stat.S_IMODE(stat.S_IRWXU | stat.S_IRWXO | >> stat.S_IRWXG)) >> >> This script was run as root. >> >> Now, the code of the CGI that should delete the file: >> >> #As you see, I can write to the file >> lock_file = open(".lock","w") >> lock_file.write("") >> lock_file.close() >> # But the following line raises a "permission denied" OSError >> os.remove(".lock") >> >> I've seen that the script is running as "nobody", but, the file is rwx by >> everybody. I've also tryed changing the owner of the file to "nobody" >> also, but no luck anyway. >> >> Thanks a lot. >> >> >> Steve Holden wrote: >> >>> Matias Surdi wrote: >>>> HI! >>>> >>>> I want to delete a file from a CGI, but I always get a Permission >>>> denied error. >>>> >>>> I've tryed this after creating the file (from a normal script): >>>> >>>> os.chmod(".lock",stat.S_IMODE(stat.S_IRWXU | stat.S_IRWXO | >>>> stat.S_IRWXG)) >>>> os.chown(".lock",pwd.getpwnam("nobody")[2],pwd.getpwnam("nobody")[3]) >>>> >>>> but the CGI still can't delete the file. >>>> >>>> I will appreciate very much your help. >>>> >>>> Thanks a lot. >>>> >>>> >>> How was the file created in the first place? If you don't have >>> permissions to delete it you may well not have permissions to reown it >>> or change its permissions either! >>> > Most likely, your problem is that to delete a file you need write > permissions on the directory that contains it [1]. Apparently the web > user (nobody, or apache, or whatever) doesn't have those permissions. > > regards > Steve > > [1]: Unless the sticky bit is set on the containing directory, when > other tests are applied instead. If this makes no sense to you, ignore it. Hi! I feel so s**id.... it's very likely to be that the problem.... I'll try this next week at work. Thanks a lot for the cold water on the face! From james.p.turk at gmail.com Wed Jun 13 18:08:14 2007 From: james.p.turk at gmail.com (James Turk) Date: Wed, 13 Jun 2007 22:08:14 -0000 Subject: one-time initialization of class members Message-ID: <1181772494.803499.266690@o11g2000prd.googlegroups.com> Hi, I have a situation where I have some class members that should only be done once. Essentially my problem looks like this: class Base(object): dataset = None def __init__(self, param): if type(self).dataset is None: # code to load dataset based on param, expensive class ChildClass1(Base): def __init__(self): Base.__init__(self, data_params) class AnotherChildClass(Base): def __init__(self): Base.__init__(self, other_data_params) This seems to work, initialization is only done at the first creation of either class. I was just wondering if this is the 'pythonic' way to do this as my solution does feel a bit hackish. From mwm at mired.org Wed Jun 6 15:55:58 2007 From: mwm at mired.org (Mike Meyer) Date: Wed, 6 Jun 2007 15:55:58 -0400 Subject: urllib2.urlopen broken? In-Reply-To: <18023.2281.63362.844051@bhuda.mired.org> References: <18023.2281.63362.844051@bhuda.mired.org> Message-ID: <18023.4430.362161.647685@bhuda.mired.org> In <18023.2281.63362.844051 at bhuda.mired.org>, Mike Meyer typed: > In 2.5.1 (and 2.[45], but not 2.3): Sigh. Sorry 'bout that. Since I started it, the breakage is: Python 2.5.1 (r251:54863, May 15 2007, 15:31:37) [GCC 3.4.6 [FreeBSD] 20060305] on freebsd6 Type "help", "copyright", "credits" or "license" for more information. >>> import urllib2 >>> u = urllib2.urlopen('http://www.mired.org/') >>> u.fileno() Traceback (most recent call last): File "", line 1, in File "/usr/opt/lib/python2.5/socket.py", line 252, in fileno return self._sock.fileno() AttributeError: HTTPResponse instance has no attribute 'fileno' The problem is that urlib2 was changed to wrap an HTTPResponse object in a socket._fileobject to get a few more file methods. Except (as reported above) HTTPResponse doesn't have a fileno() method, so when _fileobject tries to use it, it blows up. Adding an appropriate method to HTTPResponse: def fileno(self): return self.fp.fileno() fixes the problem, but may not be the best solution. If no one suggests a better one, I'll file the appropriate bug report. http://www.mired.org/consulting.html Independent Network/Unix/Perforce consultant, email for more information. From josiah.carlson at sbcglobal.net Sat Jun 30 03:19:43 2007 From: josiah.carlson at sbcglobal.net (Josiah Carlson) Date: Sat, 30 Jun 2007 00:19:43 -0700 Subject: Building a Python app with Mozilla In-Reply-To: References: Message-ID: <9qnhi.9511$c06.3368@newssvr22.news.prodigy.net> Thorsten Kampe wrote: > Hi, > > I've already sent this to the Komodo mailing list (which seemed to me > the more appropriate place) but unfortunately I got no response. > > I'd like to build a Python GUI app. Neither Tkinter nor Wxpython nor > PyQT are actually what I want (because the lack of GUI builders and > they don't really look good on Windows and Linux). You apparently didn't look very hard. On the wxPython end of things (which I have experience with), there is wxGlade, XRCed, Boa Constructor, Dabo, etc. I don't know about Tkinter (I don't use it), but I know that at least Qt has a very nice GUI designer and builder (from Trolltech if you are willing to pay for it), and if I remember correctly, Eric4 offers some tools to make PyQt editing nice and friendly. I'm sure there are others. As for wxPython applications not looking good on all platforms; I hate to break it to you, but the majority of the controls are *native* on whatever platform you happen to be using (except for Qt-based frontends in *nix, wxPython uses a Gtk binding in *nix). Take a browse through a few of the applications listed in the wiki: http://wiki.wxpython.org/wxPythonPit_Apps , or even Andrea Gavana's custom widgets http://xoomer.alice.it/infinity77/eng/freeware.html . > Komodo itself is an excellent example of a - at least Python driven - > application that looks superb and has superior functionality so it > seems natural to use the Komodo approach for me. I could have sworn that Komodo was written in PyQt. Unless my memory is failing me (doubtful, as they at least used to offer some PyQt development tools), I would imagine they merely embedded the mozilla bits and pieces with some C extensions. In any case, you really don't want to be developing an application using XPI. According to everyone I've ever talked to about XPI, while getting the basic stuff working isn't bad, doing anything worth mentioning is about as big a pain in the butt than just writing everything in 8088 assembly. You mileage may vary of course. > * Is there a simple How-To how to build a very simple (Python) app > with the Mozilla framework? Kind of "Hello world"...? Maybe. Search terms you should use are 'embed XPI python', which give me about 189k results in google, some of which seem applicable on the first page (which also leads me to believe that my statements regarding Komodo embedding mozilla technology may be right, though maybe they wrote Komodo in C and Qt). > * Is is reasonable to think that building a GUI with Mozilla is easier > than using Python frameworks because Mozilla does most of the GUI > work? Doubtful. Building a GUI app with XRCed and wxPython is pretty easy if you understand Python and object-oriented programming. There are some annoying vagaries with events, but if you ask your questions on the wxpython-users mailing list (over at wxpython.org), one of at least a half-dozen people will likely answer your question. - Josiah From josiah.carlson at sbcglobal.net Mon Jun 18 20:11:38 2007 From: josiah.carlson at sbcglobal.net (Josiah Carlson) Date: Mon, 18 Jun 2007 17:11:38 -0700 Subject: cStringIO unicode weirdness In-Reply-To: <7x7iq0j2ik.fsf@ruckus.brouhaha.com> References: <7x7iq0j2ik.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > Python 2.5 (r25:51908, Oct 6 2006, 15:24:43) > [GCC 4.1.2 20060928 (prerelease) (Ubuntu 4.1.1-13ubuntu4)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> import StringIO, cStringIO > >>> StringIO.StringIO('a').getvalue() > 'a' > >>> cStringIO.StringIO('a').getvalue() > 'a' > >>> StringIO.StringIO(u'a').getvalue() > u'a' > >>> cStringIO.StringIO(u'a').getvalue() > 'a\x00\x00\x00' > >>> > > I would have thought StringIO and cStringIO would return the > same result for this ascii-encodeable string. Worse: You would be wrong. The behavior of StringIO and cStringIO are different under certain circumstances, and those differences are intended. Among them is when they are confronted with unicode, as you saw. Another is when provided with an initializer... >>> cs = cStringIO.StringIO('a') >>> cs.write('b') Traceback (most recent call last): File "", line 1, in ? AttributeError: 'cStringIO.StringI' object has no attribute 'write' >>> s = StringIO.StringIO('a') >>> s.write('b') There is a summer of code project that is working towards making them behave the same, but the results will need to wait until Python 2.6 and/or 3.0 . Note that there are a few "closed, won't fix" bug reports regarding these exact same issues in the Python bug tracker at sourceforge. - Josiah From twisted0n3 at gmail.com Tue Jun 26 20:37:11 2007 From: twisted0n3 at gmail.com (Twisted) Date: Wed, 27 Jun 2007 00:37:11 -0000 Subject: The Modernization of Emacs: terminology buffer and keybinding In-Reply-To: <87r6nzc9nu.fsf@mail.eng.it> References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182272495.990807.99110@a26g2000pre.googlegroups.com> <87tzt3ihev.fsf@kobe.laptop> <1182370216.961241.6960@n60g2000hse.googlegroups.com> <85zm2ufjpb.fsf@lola.goethe.zz> <1182372592.803332.288260@u2g2000hsc.googlegroups.com> <1182549094.366282.286740@m37g2000prh.googlegroups.com> <87bqf7fwmg.fsf@telesippa.clsnet.nl> <1182553682.197778.138500@g37g2000prf.googlegroups.com> <87r6nzc9nu.fsf@mail.eng.it> Message-ID: <1182904631.083783.170640@o61g2000hsh.googlegroups.com> On Jun 26, 6:06 am, Gian Uberto Lauri wrote: > >> > HOW IN THE BLOODY HELL IS IT SUPPOSED TO OCCUR TO SOMEONE TO > >> ENTER > THEM, GIVEN THAT THEY HAVE TO DO SO TO REACH THE HELP THAT > >> WOULD TELL > THEM THOSE ARE THE KEYS TO REACH THE HELP?! > > >> What's your problem ? > > >> Ofcourse a mere program-consumer would not look what was being > >> installed on his/her system in the first place ... So after some > >> trivial perusing what was installed and where : WOW Look, MA ! > >> .... it's all there! > > >> lpr /usr/local/share/emacs/21.3/etc/refcard.ps or your > >> install-dir........^ ^ or your > >> version.............................^ > > n> So now we're expected to go on a filesystem fishing expedition > n> instead of just hit F1? One small step (backwards) for a man; one > n> giant leap (backwards) for mankind. :P [snipping some thinly-veiled insults and irrelevancies throughout] > There's a program called find, not this intuitive but worth learning > > It could solve the problem from the root with something like > > find / -name refcard.ps -exec lpr {} \; 2> /dev/null Let me get this straight. In this corner, we have just about every Windows application ever developed. When a user needs help, a click on the "help" menu or tap of the F1 key is all it takes to obtain some. Sometimes the help is not of the greatest quality, but that is another issue we won't concern ourselves with here. In the other corner, we have just about every Unix application ever developed. When a user needs help, they may do such things as manually explore the directories where the application was installed (equivalent to rooting around in C:\Program Files\Appname for .hlp files, because F1 didn't work and there was no "help" menu, if such a thing ever happened on Windoze). Or alternatively it can just magically come to them as a divinely inspired insight, or in a dream or a burning bush or stone tablets from heaven or something, that something useful might happen if the unlikely combination of symbols "find / -name refcard.ps -exec lpr {} \; 2> /dev/null" were typed at the console, which otherwise would obviously never occur to them. Even if they knew the find tool and its syntax, it would still have to somehow occur to them that "refcard.ps" might be a useful search target. On Windows, if push came to shove, clicking Start->Search and putting in ".hlp" and "C:\Program Files\Appname" would quickly find any help files. If they were given the usual file extension. If not, good luck, but most usually the help files would be named to end with .hlp. Moreover, once found, a quick double click and they're in a hypertext browser viewing the help. Unless I miss my guess, refcard.ps would require mucking about installing and configuring Ghostscript and GSView, which for Joe Winblows User is daunting enough. Trying to read anything serious and navigate in GSView is no picnic either. A hypertext browser it ain't. Adobe Acrobat Reader *might* be able to do more with a .ps file, but it's proprietary. On a Unix box, if you don't know exactly how to get some app viewing a .ps file and how to navigate in it I'm guessing you're SOL. The original suggestion with "lpr" implies printing it rather than viewing it online, which a) costs money and b) requires configuring a printer and a Postscript interpreter, given that unless the printer cost more than the computer's CPU it surely won't natively grok Postscript. We're back to configuring Ghostscript, only this time on the Unix box where I have no doubt it's even more painful than it is on a Windoze box, as well as configuring a printer on a Unix box, itself a recurring nightmare of mine for years now since one night in the nineties when I got caught in the crossfire between someone's Epson inkjet and their Mandrake 7.somethingorother Linux. Reexamining that "find" line it looks like it tries to automatically "lpr" the file(s) found. That is cause for concern, since I can easily see something like this going into Sorceror's Apprentice mode and costing you a fortune in ink and paper if there's either a misspelling or other mistake (easy enough to make in a complex arcane command line like that one) or more "refcard.ps" matches than you expected there'd be in the target directory and its descendants. From nis at superlativ.dk Tue Jun 12 06:24:10 2007 From: nis at superlativ.dk (=?ISO-8859-1?Q?Nis_J=F8rgensen?=) Date: Tue, 12 Jun 2007 12:24:10 +0200 Subject: Thunderbird access to this newsgroup In-Reply-To: <1181640420.561878.224690@x35g2000prf.googlegroups.com> References: <1181640420.561878.224690@x35g2000prf.googlegroups.com> Message-ID: <466e7451$0$90271$14726298@news.sunsite.dk> Rostfrei skrev: > Hello! > > I'm writing this message over Google web access. I'm trying to access > to the comp.lang.python newsgroup trough the Thunderbird, but I just > can't configure it properly. What is the news server for this > newsgroup. If I ping comp.lang.python it is not resolved. For instance > I had no problem configuring Eclipse news server. I just entered > news.eclipse.org as a news server address and after it I can browse > available groups. Newsgroups are not specific to one server, they can be "carried" by any number of servers. Most ISP's make a news server available to their customers which carries the "standard" newsgroup hierarchy - which comp.lang.python is part of. Try using news. as the server name, or look at their help pages for the correct server name/setup. There used to be quite a few free and open servers available, but I don't know the situation today. Many organizations keep their own newsgroup servers, which carry only their own groups (and possibly a few relevant ones from the standard hierarchy) - news.eclipse.org is probably such a server. Hope this helps. Nis From bj_666 at gmx.net Mon Jun 4 03:11:45 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Mon, 04 Jun 2007 09:11:45 +0200 Subject: magic names in python References: <1180939436.862957.127810@p77g2000hsh.googlegroups.com> Message-ID: In <1180939436.862957.127810 at p77g2000hsh.googlegroups.com>, per9000 wrote: > I just used a search engine a little on this topic and I found no > comprehensive list of magic names in python. They are usually mentioned in parts of the docs where the relevant functionality is explained. For example in `Special method names`_ in the reference manual. And of course all covered in the reference manual are under `_ (underscore)`_ in its index. In the `library reference's index`_ you'll find some more that are used by modules. .. _`_ (underscore)`: http://docs.python.org/ref/genindex.html#letter-_ .. _library reference's index: http://docs.python.org/lib/genindex.html .. _Special method names: http://docs.python.org/ref/specialnames.html > * are these lists complete or can magic names be added over time (to > the python "core")? Magic names can be added over time. For example the ``with`` statement introduced `__enter__()` and `__exit__()` in Python 2.5. And some special names may even change were the docs say so or if they aren't mentioned at all in the docs. > * are magic names the same in different python versions? Yes. > So another question emerges: > * is the use of magic names encouraged and/or part of good coding > practice. What do you mean by "use"? Implement them to override behavior? Yes, that's their purpose. Invent new magic names? No of course not, they are special for a reason: preventing name clashes with the user's names. Ciao, Marc 'BlackJack' Rintsch From JoeSalmeri at hotmail.com Mon Jun 4 19:53:44 2007 From: JoeSalmeri at hotmail.com (Joe Salmeri) Date: Mon, 4 Jun 2007 19:53:44 -0400 Subject: Python 2.5.1 broken os.stat module References: <466140A6.1090100@v.loewis.de> <-aOdnbFdroD_gP_bnZ2dnUVZ_uKknZ2d@comcast.com> <4662750b$0$29898$9b622d9e@news.freenet.de> <4662F98C.8070709@v.loewis.de> <466472C8.9020003@v.loewis.de> Message-ID: I have tried (unsuccessfully) to get you to view things from the end user perspective. I wish that you would consider looking at what the end user sees because that is what really matters. Without end users we would not need to develop software would we? This entire conversation was VERY nicely summarized (by you) with the following statement: 01/02/2007 7:00 PM EST == 01/02/2007 8:00 PM EDT I agree with that statement 100%. Python displays the date as 01/02/2007 7:00 PM EST Windows displays the date as 01/02/2007 8:00 PM EDT. Python and Windows are BOTH correct! However, there is a problem. Windows does *not* display the date like that. Windows displays the date as 01/02/2007 08:00 PM. Windows does *not* give *any* indication when it made the switch from EST to EDT!!! All the end user sees is that the file said it was last changed at 07:00 PM one day and then the next day after DST started it now says the file was last changed at 08:00 PM. The user is left scratching their head. I prefer not to leave my end users in that situation. >From Python I could resolve this using strftime with %Z to show the timezone / EST / EDT but from Windows you cannot get it to show you the timezone / DST value. The only place in Windows that I have found that indicates EST / EDT is in Control Panel Date and Time Properties. Since the dir command and Explorer do not display the timezone / DST information the end experience is confusion when the EST / EDT switch occurs. You understand what happend, I understand what happen, but the typical user does not. From stefaan.himpe at gmail.com Sun Jun 10 02:31:49 2007 From: stefaan.himpe at gmail.com (stefaan) Date: Sat, 09 Jun 2007 23:31:49 -0700 Subject: DAO and Access97 WHERE clause fails In-Reply-To: References: Message-ID: <1181457109.310138.86790@p77g2000hsh.googlegroups.com> > I should point out that I don't do DAO (or ADO) -- and if I had to > code Python to access JET, I'd probably hijack a copy of mxODBC in order > to get a "sane" SQL interface. I have successfully used the dejavu object-relational mapper (http:// projects.amor.org/docs/dejavu/1.5.0RC1/) to access MS ACCESS databases recently. Bestregards, Stefaan. From jstroud at mbi.ucla.edu Mon Jun 25 17:48:00 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Mon, 25 Jun 2007 14:48:00 -0700 Subject: Internals and complexity of types, containers and algorithms In-Reply-To: References: Message-ID: Harald Luessen wrote: > Hi, I am new to python and I miss some understanding of the internals > of some types and containers. With my C/C++ background I hope to get > some hints to chose the best data structure for my programs. Here are > some questions: This depends on how you define "best". If you want speed and optimization, you can use the numpy package built with ATLAS tuned for a specific machine. Beyond speed, "best" in the python community usually means "most suited" from an idiomatic perspective and from the perspective of structure that lends itself to long term maintainability because [C]python data structures seem to undergo optimizations in their implementation at each revision. Your best bet is probably to forget about implementation and write code that makes sense. For example, some have suggested a tuple-keyed dictionary to represent a chess board: board = ((c,r) for r in xrange(1, 9) for c in 'abcdefgh') starting = 'RNBQKBNR' + 'P' * 8 + ' ' * 32 + 'p' * 8 + 'rnbqkbnr' position = dict(zip(board, starting)) Of course we see here the chief problem with algebraic notation: it begins numbering at 1 which is painfully reminiscient of fortran. James From evan at yelp.com Wed Jun 20 22:28:53 2007 From: evan at yelp.com (Evan Klitzke) Date: Wed, 20 Jun 2007 19:28:53 -0700 Subject: The Modernization of Emacs In-Reply-To: <2jpok4-ajt.ln1@zoogz.gregorie.org> References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182344981.372713.298580@w5g2000hsg.googlegroups.com> <1182370884.853838.321440@c77g2000hse.googlegroups.com> <2jpok4-ajt.ln1@zoogz.gregorie.org> Message-ID: On 6/20/07, Martin Gregorie wrote: > Amongst its benefits are that you can do anything its capable of by > using only a standard QUERTY keyboard plus ESC - no function keys, etc > are needed - which can save your bacon if somebody misconfigured your > console or the computer is dieing. While it is true that the original incarnation of vi only uses the "regular" keyboard keys and the escape key, to make vi not painful to use there are a whole slew of commands that have been added in vim and other vi clones to add basic features, and many of these commands use Ctrl (or some other function key). For example, the original vi lacks a redo command (!), and consequently the redo command sequence in vim is Ctrl-r. I don't think nearly as many people would use vi if none of the Ctrl sequence commands present on modern versions of vi were available due to the lack of features like this one. -- Evan Klitzke From martin at see.sig.for.address Tue Jun 26 18:59:32 2007 From: martin at see.sig.for.address (Martin Gregorie) Date: Tue, 26 Jun 2007 23:59:32 +0100 Subject: Date<->UNIX timestamp mapping (was Portable general timestamp format, not 2038-limited) In-Reply-To: <7x645al8kc.fsf@ruckus.brouhaha.com> References: <1182544384.709759.235300@o11g2000prd.googlegroups.com> <20070625133843.9e25d0ab.steveo@eircom.net> <82b5l4-tvh.ln1@zoogz.gregorie.org> <7xbqf3lc7i.fsf@ruckus.brouhaha.com> <70c7l4-2gp.ln1@zoogz.gregorie.org> <7xlke6y6y1.fsf@ruckus.brouhaha.com> <7x645al8kc.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > Martin Gregorie writes: >>> Same one already given: http://cr.yp.to/proto/utctai.html >> >> Nope - you referenced leap seconds, not TAI and not that URL > > Oh whoops, I thought I put that url further up in the thread. > I remember grumbling to myself about having to look for it twice. > Maybe I'm just confused. Anyway it's pretty interesting stuff, > as is the Wikipedia article someone else linked to. > Thinking of interesting date & time related stuff, there's another document I remember seeing a while back - probably around early '98. It was an ASCII configuration file that contained to rules for mapping human readable dates & times to UNIX timestamps after taking account of changes of calendar (e.g. the switch between Julian and Gregorian calendars), the introduction of daylight saving time, etc. I remember that it was mostly comment interspersed with mapping rules and that the comments were vast and fascinating, often including copies of e-mail threads. The file was part of a Linux distro, probably Debian. Some time later, after I set up my first Linux system, I went looking for it without success, probably because by that time (RedHat 6.2) the date mapping rules had become encoded as some sort of binary rule set. I'd very much like to know where I could find a copy of that file. -- martin@ | Martin Gregorie gregorie. | Essex, UK org | From Shihpin.Lin at gmail.com Mon Jun 4 03:13:14 2007 From: Shihpin.Lin at gmail.com (Shihpin) Date: Mon, 04 Jun 2007 00:13:14 -0700 Subject: example: 40286 -> 68204 In-Reply-To: <1180932308.558055.42370@h2g2000hsg.googlegroups.com> References: <1180916590.000664.249810@z28g2000prd.googlegroups.com> <1180932308.558055.42370@h2g2000hsg.googlegroups.com> Message-ID: <1180941194.291451.38200@o11g2000prd.googlegroups.com> Thanks Steven, I will try to decipher that. Shihpin On 6 4 , 1:45, attn.steven.... at gmail.com wrote: > On Jun 3, 5:23 pm, Shihpin wrote: > > Is there a fuction that reverse the digits of a number? > One can use int, str and a slice: > > print int(str(40286)[::-1]) > > -- > Hope this helps, > Steven From fred at adventistcare.org Wed Jun 6 08:37:32 2007 From: fred at adventistcare.org (Sells, Fred) Date: Wed, 6 Jun 2007 08:37:32 -0400 Subject: Beginning Python Message-ID: I find 3 elements contribute significantly to becoming competent in python 1. a decent IDE so you can see the big picture (multiple files and directories). I use Eclipse + PyDev because Eclipse supports other goodies like CVS. I'm sure other IDE's are as good if not better, but who has time to check them all out. 2. Looking at others examples especially when solving real-world problems. I've learned much from the Python Cookbook even though I've used Python for 15 years. 3. Building a real-world application where you cannot change the requirements to fit your current knowledge. of course that's just my opinion, I could be wrong :) ---snip--- > > Seriously, there is no way for anyone to predict how long it will > take you to learn something. In this case, that something (Python) > is a moving target -- there are a few things I use daily that > weren't > even part of the language when I started. > > I do believe that it takes about three years to get reasonably > competent at anything. And about ten years to get really > good at it. > And probably another ten years to be a master (I'm only guessing > though -- because I haven't been doing anything for twenty years > yet). Of course, by my metrics I guess even Guido wouldn't be a > master at Python so perhaps I'm full of crap :-) > > Hope this helps, > Michael > > From chinchia.kuo at sbcglobal.com Fri Jun 29 15:04:28 2007 From: chinchia.kuo at sbcglobal.com (Kuo) Date: Fri, 29 Jun 2007 19:04:28 GMT Subject: appending file Message-ID: <0Jchi.16365$2v1.11172@newssvr14.news.prodigy.net> Hi, I'm trying to read a file (fileA) and append to another file(fileB). However, I always get "^M" at the end. Does anyone know why ? Here is my code ? os.system("../syn/pin_assign.pl customer_netlist.txt") shutil.copy("../fileB", "fileB") ucf = open("fileB", "a") pin = open("fileA", "r") ucf.write(pin.read()) ucf.close; pin.close; sys.exit(0); Here is what I get. # FPGA CLOCK^M NET "SYSCLK_A" loc = N16 | TNM_NET = SYSCLK_A;^M NET "SYSCLK_AN" loc = M16 | TNM_NET = SYSCLK_A;^M Note that if I don't do "ucf.write(pin.read())", everything is ok. Thanks for any help. From jjl at pobox.com Mon Jun 25 15:38:43 2007 From: jjl at pobox.com (John J. Lee) Date: Mon, 25 Jun 2007 19:38:43 GMT Subject: Indenting in Emacs References: <1182415666.423187.274240@u2g2000hsc.googlegroups.com> <87bqf8nagp.fsf@pobox.com> Message-ID: <874pkvvn7g.fsf@pobox.com> Michael Hoffman writes: > John J. Lee wrote: >> Eugene Morozov writes: >> >>> Steven W. Orr ?????: >>> > Ok. I'm not stupid but I do not see a 4.78 anywhere even though I >>> see refs >>>> from google. I have 4.75 The SVN tree doesn't seem to even have >>>> that. >>>> >>>> I checked the latest copy out from sourceforge and that was 4.75 too. >>>> >>>> Can someone please tell me where to find the latest? >>>> >>> It's from Emacs 22. >> >> Note that's a different python-mode to the old one that lives on SF. >> Yes, there are now two of them. > > Which one is better? I've not noticed a big difference in usability. I find indentation with the new mode very mildly more annoying than the old mode. YMMV on that. There are probably annoyances with the old mode that I've now forgotten about. I'm told by an emacs developer at work that the new mode is more emacsy in its implementation -- I don't know in what ways exactly, but presumably that, plus the fact that the new mode is included with emacs 22, will mean that it's likely to work better with other emacs code (not that I ever had much problem with the old mode -- but then I didn't push it very far). John From mail at microcorp.co.za Fri Jun 1 01:57:44 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Fri, 1 Jun 2007 07:57:44 +0200 Subject: file reading by record separator (not line by line) References: <1180614374.027569.235540@g4g2000hsf.googlegroups.com> <1180615143.228557.258760@g4g2000hsf.googlegroups.com> Message-ID: <007c01c7a411$c6ca6260$03000080@hendrik> "Lee Sander" wrote: > I wanted to also say that this file is really huge, so I cannot > just do a read() and then split on ">" to get a record > thanks > lee > > On May 31, 1:26 pm, Lee Sander wrote: > > Dear all, > > I would like toreada really hugefilethat looks like this: > > > > > name1.... > > > > line_11 > > line_12 > > line_13 > > ...>name2 ... > > > > line_21 > > line_22 > > ... > > etc > > > > where line_ij is just a free form text on that line. > > > > how can ireadfileso that every time i do a "read()" i get exactly > > onerecord > > up to the next ">" > > > > many thanks > > Lee > I would do something like: (not tested): def get_a_record(f,sep): ret_rec = '' while True: char = f.read(1) if char == sep: break else: ret_rec += char return ret_rec - Hendrik From tjreedy at udel.edu Thu Jun 7 14:29:23 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 7 Jun 2007 14:29:23 -0400 Subject: Bug/Weak Implementation? popen* routines can't handle simultaneousread/write? References: <1181232071.928835.301710@w5g2000hsg.googlegroups.com> Message-ID: "dmoore" wrote in message news:1181232071.928835.301710 at w5g2000hsg.googlegroups.com... | alternatives in the standard python distro) Is there some place I can | submit this as a feature request? (Python dev?) http://sourceforge.net/tracker/?group_id=5470 But don't hold your breath for a volunteer to respond. Discussion here is good until you have a concrete request and support/rationale. From roy at panix.com Sun Jun 3 17:28:33 2007 From: roy at panix.com (Roy Smith) Date: Sun, 03 Jun 2007 17:28:33 -0400 Subject: Is 1 large Regex faster than 3 smaller ones? References: <1180896727.419817.303960@p47g2000hsd.googlegroups.com> Message-ID: In article <1180896727.419817.303960 at p47g2000hsd.googlegroups.com>, erikcw wrote: > Hi, > > I need to match 3 small strings in a small text file (about 200 words > of text). > > Would it be faster to write 1 compiled regex that matches all 3 > substrings in one go, or to use 3 separate regular expressions to do > the same job? > > Thanks! > Erik For a classic regex, the answer is one big one. Matching against a regex takes time proportional to the number of characters of input. One big regex will probably consume more memory, and may be slower to compile, but it should run faster. On the other hand, there are a lot of things that pattern maching libraries accept these days under the guise of being a "regex" which are not strictly regexes in the classic sense. >From a purely practical point of view, if your input is only 200 words, it's likely that the search time will be insignificant no matter what you do. From solisgb at gmail.com Mon Jun 4 06:17:26 2007 From: solisgb at gmail.com (luis) Date: Mon, 04 Jun 2007 03:17:26 -0700 Subject: ctypes: error passing a list of str to a fortran dll Message-ID: <1180952246.415068.237400@h2g2000hsg.googlegroups.com> I'm using ctypes to call a fortran dll from python. I have no problems passing integer and double arryas, but I have an error with str arrys. For example: .... StringVector = c_char_p * len(id) # id is a list of strings Id_dat=StringVector() for i in range(len(Id)): ...Id_dat[i]=id[i] n=c_int(len(Id_dat)) myDll = windll.LoadLibrary(org) myDll.myFunc(byref(n), byref(Id_dat)) and then ValueError: Procedure probably called with not enough arguments (4 bytes missing) In a similar way I have bo problemns with int or double arryas Some suggestions are wellcome ! From half.italian at gmail.com Sun Jun 17 23:25:25 2007 From: half.italian at gmail.com (half.italian at gmail.com) Date: Sun, 17 Jun 2007 20:25:25 -0700 Subject: Windows XMLRPC Service Message-ID: <1182137125.879556.319030@g37g2000prf.googlegroups.com> Hi, I'm trying to serve up a simple XMLRPC server as a windows service. I got it to run properly, I'm just not sure how to stop it properly. Most of the documentation/examples I found for this was from forums, so I'd love some links to relevant info also. Here's what I have...taken from the cookbook with the xmlrpc server added: import win32serviceutil import win32service import win32event import SimpleXMLRPCServer class MyClass(object): def hello(self): return "Hello World!" class SmallestPythonService(win32serviceutil.ServiceFramework): _svc_name_ = "PythonXMLRPC" _svc_display_name_ = "PythonXMLRPC" def __init__(self, args): win32serviceutil.ServiceFramework.__init__(self, args) # Create an event which we will use to wait on. # The "service stop" request will set this event. self.hWaitStop = win32event.CreateEvent(None, 0, 0, None) def SvcStop(self): # Before we do anything, tell the SCM we are starting the stop process. self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) # quit the xmlrpc sever self.server.quit() # And set my event. win32event.SetEvent(self.hWaitStop) def SvcDoRun(self): # Serve up the XMLRPC forever self.server = SimpleXMLRPCServer.SimpleXMLRPCServer(("10.0.1.6", 8000)) self.server.register_instance(MyClass()) self.server.serve_forever() win32event.WaitForSingleObject(self.hWaitStop) if __name__=='__main__': win32serviceutil.HandleCommandLine(SmallestPythonService) ~Sean From dkuhlman at rexx.com Wed Jun 27 16:56:17 2007 From: dkuhlman at rexx.com (Dave Kuhlman) Date: Wed, 27 Jun 2007 20:56:17 GMT Subject: Zip File Woes References: <4966172950419983052@unknownmsgid> Message-ID: Jerry Hill wrote: > On 6/27/07, Robert Rawlins - Think Blue > wrote: >> zip = zipfile.ZipFile('Media/Media.zip', 'r') > > Shouldn't you open this file in binary mode? It shouldn't make > any difference on unix machines, but will possibly break under > windows. That may also explain why it works properly in one > environment, and not in another. > It wouldn't hurt, but ... Actually, it is the underlying file that should be opened in binary mode. I just looked at the source for the zipfile module. It throws away the 'b' if the mode contains a 'b'. If you pass it a file name, zipfile always opens the underlying file in binary mode. If you pass in a file, then it is your responsibility to open that file in binary mode. Dave -- http://www.rexx.com/~dkuhlman From __peter__ at web.de Tue Jun 26 16:01:43 2007 From: __peter__ at web.de (Peter Otten) Date: Tue, 26 Jun 2007 22:01:43 +0200 Subject: problem mixing gettext and properties References: <1182880358.100599.139120@j4g2000prf.googlegroups.com> <1182885474.515335.242470@e9g2000prf.googlegroups.com> Message-ID: Andr? wrote: > On Jun 26, 3:56 pm, Peter Otten <__pete... at web.de> wrote: >> Andr? wrote: >> > I've encountered a problem using gettext with properties while using a >> > Python interpreter. >> >> > Here's a simple program that illustrate the problem. >> > ============== >> > # i18n_test.py: test of gettext & properties >> >> > import gettext >> >> > fr = gettext.translation('i18n_test', './translations', >> > languages=['fr']) >> >> _ = fr.gettext # untested >> >> >> >> > help = _("Help me!") >> >> > class Test_i18n(object): >> > def get(self): >> > __help = _("HELP!") >> > return __help >> > help_prop = property(get, None, None, 'help') >> >> > test = Test_i18n() >> >> > print help >> > print test.help_prop >> > #### end of file >> >> > To run the above program, you need to have the strings translated and >> > the proper ".po" and ".mo" files created. (for those interested, I >> > can send the whole lot in a zip file) >> >> > If I run the program as is, the output is: >> > Aidez-moi! >> > AIDE!!! >> >> > Ok, let's try with the Python interpreter: >> >> > ActivePython 2.4.2 Build 248 (ActiveState Corp.) based on >> > Python 2.4.2 (#67, Oct 30 2005, 16:11:18) [MSC v.1310 32 bit (Intel)] >> > on win32 >> > Type "help", "copyright", "credits" or "license" for more information. >> >>>> import i18n_test >> > Aidez-moi! >> > AIDE!!! >> >> > # No surprise there so far. >> >> >>>> print i18n_test.help >> > Aidez-moi! >> >>>> print i18n_test.test.help_prop >> > AIDE!!! >> >>>> i18n_test.help >> > 'Aidez-moi!' >> >> > # all of the above are as expected; now for the first surprise >> >> >>>> i18n_test.test.help_prop >> > Traceback (most recent call last): >> > File "", line 1, in ? >> > File "i18n_test.py", line 12, in get >> > __help = _("HELP!") >> > TypeError: 'str' object is not callable >> >> > # and a second surprise where we try to repeat something that used to >> > work >> >> >>>> print i18n_test.test.help_prop >> > Traceback (most recent call last): >> > File "", line 1, in ? >> > File "i18n_test.py", line 12, in get >> > __help = _("HELP!") >> > TypeError: 'str' object is not callable >> >> > #============= >> >> > Dare I say: "Help!" I really need to use the above at the >> > interpreter prompt. >> >> > Andr? >> >> The _ builtin is set to the result of the last expression evaluated by >> the interpreter: >> >> >>> for i in range(3): >> >> ... i >> ... >> 0 >> 1 >> 2>>> _ >> 2 >> >>> import __builtin__ >> >>> __builtin__._ >> >> 2 >> >> Therefore you get a name clash with _() as an alias for gettext(). Use >> module-global aliases instead, e. g. >> >> _ = fr.gettext >> >> in the above code. >> >> Peter > > Thanks, that works ... but, it brings many other "complications". I > have multiple modules, and I want to be able to switch languages > easily. Unless I am mistaken, if I do it with module-global aliases > instead, I will need to have something like > > lang = {} > for code in ['en', 'fr', ...]: > lang[code] = gettext.translation('i18n_test', './translations', > languages=[code]) > > def switch_language(code): > ... > import module1 > import module2 > ... > module1._ = lang[code].gettext > module2._ = lang[code].gettext > ... > If you need to change the language while the program is running you can put def _(s): return gettext(s) into one "master" module and have the other modules import that: from master import _ This comes at the cost of one extra indirection. > And I will need to make sure to keep track of all the modules that > require translation... Is there an easier, less tedious way to do > this? If your users don't rely on _ in the interpreter, you can write a custom sys.displayhook that doesn't set __builtin__._ Peter From Allen.Chenal at gmail.com Tue Jun 12 21:44:26 2007 From: Allen.Chenal at gmail.com (Allen) Date: Tue, 12 Jun 2007 18:44:26 -0700 Subject: In C extension .pyd, sizeof INT64 = 4? In-Reply-To: <1181696426.081185.63170@a26g2000pre.googlegroups.com> References: <1181642594.963433.132750@g37g2000prf.googlegroups.com> <466efcdf$0$13674$9b622d9e@news.freenet.de> <1181696426.081185.63170@a26g2000pre.googlegroups.com> Message-ID: <1181699066.050774.302040@x35g2000prf.googlegroups.com> On 6 13 , 9 00 , Allen wrote: > On 6 13 , 4 06 , "Martin v. Lo"wis" wrote: > > > Allen schrieb: > > > > My C extension works wrong, and debug it, found that sizeof (INT64) = > > > 4, not 8. > > > I compile on Windows XP platform. > > > Please tell me how to fix it to support INT64? > > > What *is* INT64? It's not a builtin type of standard C, it isn't > > defined by Microsoft C, and it isn't predefined by Python. > > > So it must be something that you have defined, and apparently > > incorrectly. How did you define it? > > > Regards, > > Martin > > Thanks for your reply. > > I defined in this way: > > #ifndef WIN32 > typedef long long INT64; > #else > typedef __int64 INT64; > #endif > > I feel it strange that when I use INT64 as local variable, it will run > error. > When I change the local variable to be static or global, it will be > ok. I feel very very sorry. It is my fault. I used INT64 and initialize its value from PyArg_ParseTuple. The code is PyArg_ParseTuple(args, "l", &nValue). It should be PyArg_ParseTuple(args, "L", &nValue). Thanks all of you. Regars, Allen Chen From steve at laniels.org Mon Jun 25 11:38:11 2007 From: steve at laniels.org (Stephen R Laniel) Date: Mon, 25 Jun 2007 11:38:11 -0400 Subject: server wide variables In-Reply-To: <1182785365.877473.298170@q75g2000hsh.googlegroups.com> References: <1182785365.877473.298170@q75g2000hsh.googlegroups.com> Message-ID: <20070625153811.GA23256@slaniel-laptop.itasoftware.com> On Mon, Jun 25, 2007 at 03:29:25PM -0000, Jay Sonmez wrote: > I want to be able to save some server variables as long as Apache runs > on the server (mod_python). > > How is that possible in Python? Would setting environment variables help you? You'd use os.environ. http://docs.python.org/lib/os-procinfo.html -- Stephen R. Laniel steve at laniels.org Cell: +(617) 308-5571 http://laniels.org/ PGP key: http://laniels.org/slaniel.key From goon12 at gmail.com Fri Jun 15 09:51:54 2007 From: goon12 at gmail.com (Joe Riopel) Date: Fri, 15 Jun 2007 09:51:54 -0400 Subject: Want to learn Python In-Reply-To: <1181914734.324919.219830@n2g2000hse.googlegroups.com> References: <1181907696.878873.214760@i13g2000prf.googlegroups.com> <1181914734.324919.219830@n2g2000hse.googlegroups.com> Message-ID: <6a2ccd190706150651w1e620bb5pd6094d70be1d22af@mail.gmail.com> I am still learning and this is a great resource: http://diveintopython.org/index.html You can buy it or read it online for free. From robert.kern at gmail.com Fri Jun 22 14:37:22 2007 From: robert.kern at gmail.com (Robert Kern) Date: Fri, 22 Jun 2007 13:37:22 -0500 Subject: Setuptools, build and install dependencies In-Reply-To: References: <87645gx0qb.fsf@benfinney.id.au> Message-ID: Harry George wrote: > We need to know the dependencies, install them in dependency order, > and expect the next package to find them. "configure" does this for > hundreds of packages. cmake, scons, and others also tackle this > problem. Python's old setup.py seems to be able to do it. No, generic setup.py scripts don't do anything of that kind. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From gagsl-py2 at yahoo.com.ar Sat Jun 23 22:14:42 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 23 Jun 2007 19:14:42 -0700 Subject: Python changing keywords name In-Reply-To: <1182630774.701295.50890@k79g2000hse.googlegroups.com> References: <1182630774.701295.50890@k79g2000hse.googlegroups.com> Message-ID: <1182651282.747106.239720@o61g2000hsh.googlegroups.com> vedrandeko... at v-programs.com wrote: > I on working on windows and Python 2.4. Where can I find and CHANGE > python > grammar. ( I just want to change the keywords ) Instead of changing Python grammar, you could convert your "translated" source into "original" Python using the code below, and compile and run as usual; you can also reverse the process. Also, this lets you use the standard Python library and all other Python code around the world. Unlike a simple "search and replace", it understands the lexical structure of a Python program, and won't replace a keyword inside a quoted string, by example. The core function is simple: def translate_tokens(sourcefile, tdict): for tok_num, tok_val, _, _, _ in tokenize.generate_tokens(sourcefile.readline): if tok_num==token.NAME: tok_val = tdict.get(tok_val, tok_val) yield tok_num, tok_val translated_code = tokenize.untokenize( translate_tokens(StringIO(original_code), translation_dictionary)) Note that you may encounter problems if the original code uses some names matching the translated keywords. (I hope nobody will abuse this technique... Y perd?n a los hispanoparlantes por lo horrible de la traducci?n). --- begin code --- from cStringIO import StringIO import token import tokenize # "spanished" Python source from the SimplePrograms wiki page code_es = r""" BOARD_SIZE = 8 clase BailOut(Exception): pasar def validate(queens): left = right = col = queens[-1] para r en reversed(queens[:-1]): left, right = left-1, right+1 si r en (left, col, right): lanzar BailOut def add_queen(queens): para i en range(BOARD_SIZE): test_queens = queens + [i] intentar: validate(test_queens) si len(test_queens) == BOARD_SIZE: retornar test_queens else: retornar add_queen(test_queens) excepto BailOut: pasar lanzar BailOut queens = add_queen([]) imprimir queens imprimir "\n".join(". "*q + "Q " + ". "*(BOARD_SIZE-q-1) para q en queens) """ # english keyword -> spanish trans_en2es = { 'and': 'y', 'as': 'como', 'assert': 'afirmar', 'break': 'afuera', 'class': 'clase', 'continue': 'siguiente', 'def': 'def', 'del': 'elim', 'elif': 'sinosi', 'else': 'sino', 'except': 'excepto', 'exec': 'ejecutar', 'finally': 'finalmente', 'for': 'para', 'from': 'desde', 'global': 'global', 'if': 'si', 'import': 'importar', 'in': 'en', 'is': 'es', 'lambda': 'lambda', 'not': 'no', 'or': 'o', 'pass': 'pasar', 'print': 'imprimir', 'raise': 'lanzar', 'return': 'retornar', 'try': 'intentar', 'while': 'mientras', 'with': 'con', 'yield': 'producir', } # reverse dict trans_es2en = dict((v,k) for (k,v) in trans_en2es.items()) def translate_tokens(source, tdict): for tok_num, tok_val, _, _, _ in tokenize.generate_tokens(source.readline): if tok_num==token.NAME: tok_val = tdict.get(tok_val, tok_val) yield tok_num, tok_val code_en = tokenize.untokenize(translate_tokens(StringIO(code_es), trans_es2en)) print code_en code_es2= tokenize.untokenize(translate_tokens(StringIO(code_en), trans_en2es)) print code_es2 --- end code --- -- Gabriel Genellina PS: Asking just once is enough. From showell30 at yahoo.com Sun Jun 10 10:46:37 2007 From: showell30 at yahoo.com (Steve Howell) Date: Sun, 10 Jun 2007 07:46:37 -0700 (PDT) Subject: Python in the Mozilla world In-Reply-To: Message-ID: <843644.44155.qm@web33511.mail.mud.yahoo.com> --- "Eric S. Johansson" wrote: > > As a result, I started looking at Python generating > JavaScript and I know there > is pypy but is that really something one can count > on or is it more a good > demonstration of technology? > I would not completely give up on the idea of Python itself running in the browser, although obviously there have been lots of false starts. http://www.voidspace.org.uk/python/weblog/arch_d7_2007_04_28.shtml#e702 Regarding using Python to generate JavaScript, I just get nervous any time code generation happens. While JS is not a perfect language, it's tolerably close to Python in lots of cases, and if you have a Python back end, you can feed it JSON very easily from Python. To the extent that JS code incorporates lots of cross-platform idiosyncracies, I still think the strategy there is to dig into JS and learn how to encapsulate those within JS itself. -- Steve ____________________________________________________________________________________ TV dinner still cooling? Check out "Tonight's Picks" on Yahoo! TV. http://tv.yahoo.com/ From danb_83 at yahoo.com Wed Jun 27 21:42:23 2007 From: danb_83 at yahoo.com (Dan Bishop) Date: Wed, 27 Jun 2007 18:42:23 -0700 Subject: 16bit hash In-Reply-To: References: Message-ID: <1182994943.647492.113490@n2g2000hse.googlegroups.com> On Jun 27, 12:11 pm, Robin Becker wrote: > Josiah Carlson wrote: > > Robin Becker wrote: > >> Is the any way to get an efficient 16bit hash in python? > > > hash(obj)&65535 > > > - Josiah > > yes I thought of that, but cannot figure out if the internal hash really > distributes the bits evenly. Particularly since it seems to treat integers etc > as special cases > > >>> hash(1) > 1 > >>> hash(2) > 2 > >>> hash('1234') > 1723328704 > >>> And then hash(-1) is a SPECIAL special case. >>> hash(-1) -2 From fred at adventistcare.org Tue Jun 5 08:55:27 2007 From: fred at adventistcare.org (Sells, Fred) Date: Tue, 5 Jun 2007 08:55:27 -0400 Subject: Graph plotting module Message-ID: www.vpython.org might be overkill, but it was easy to do simple 2d charts. > -----Original Message----- > From: python-list-bounces+frsells=adventistcare.org at python.org > [mailto:python-list-bounces+frsells=adventistcare.org at python.org]On > Behalf Of Grant Edwards > Sent: Monday, June 04, 2007 11:23 AM > To: python-list at python.org > Subject: Re: Graph plotting module > > > On 2007-06-04, Viewer T. wrote: > > > Is there a python module anywhere out there that can plot straight > > line graphs, curves (quadratic, etc). If anyone knows where I can > > download one, please let me know. > > gnuplot-py > matplotlib > > -- > Grant Edwards grante Yow! BARRY > ... That was > at the most > HEART-WARMING > visi.com rendition > of "I DID IT MY > WAY" I've > ever heard!! > -- > http://mail.python.org/mailman/listinfo/python-list > From newsgroups at debain.org Mon Jun 4 15:46:59 2007 From: newsgroups at debain.org (Samuel) Date: Mon, 4 Jun 2007 19:46:59 +0000 (UTC) Subject: Automating a telnet session with an echo to stdout References: Message-ID: On Sat, 02 Jun 2007 17:41:01 +0000, Samuel wrote: > I am trying to automate a telnet session (currently using Python's > telnetlib) and would like to echo any response of the remote host to > stdout, as soon as it arrives on telnetlib's open TCP socket. For the records: Because I did not find any other solution, I modified telnetlib to provide a callback that let's me see what is going on. The patch is here: http://sourceforge.net/tracker/index.php?func=detail&aid=1730959&group_id=5470&atid=305470 -Samuel From steve at holdenweb.com Fri Jun 29 08:30:46 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 29 Jun 2007 08:30:46 -0400 Subject: equality & comparison by default (was Re: Too many 'self' in python.That's a big flaw in this language.) In-Reply-To: References: <1182942154.185461.89620@e9g2000prf.googlegroups.com> <1i0cy8z.z94q5d1dxgexxN%aleax@mac.com> Message-ID: A.T.Hofkamp wrote: > On 2007-06-29, Steve Holden wrote: >> Just the same there are sound reasons for it, so I'd prefer to see you >> using "counterintuitive" or "difficult to fathom" rather than "broken" >> and "wrong". > > You are quite correct, in the heat of typing an answer, my wording was too > strong, I am sorry. > No problem, I do the same thing myself ... regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From bbxx789_05ss at yahoo.com Fri Jun 15 03:05:15 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: Fri, 15 Jun 2007 00:05:15 -0700 Subject: OS X install confusion In-Reply-To: References: <1hzp0kw.4i0y5i1cqnlwoN%johnmfisher@comcast.net> <6b03b$46717b5e$4275d90a$18801@FUSE.NET> <1181842656.810802.24810@x35g2000prf.googlegroups.com> <1hzpj69.1k6hn46vkidfkN%johnmfisher@comcast.net> Message-ID: <1181891115.527613.169260@q66g2000hsg.googlegroups.com> On Jun 14, 6:25 pm, Paul McNett wrote: > John Fisher wrote: > > Ted wrote: > > >> On Jun 14, 1:31 pm, Kevin Walzer wrote: > >>> John Fisher wrote: > >>>> Hi Groupies, > >>>> I have an Intel Macbook running OS X 10.4. > >>>> It came installed with Python 2.3.5. I have since installed MacPython > >>>> with version 2.4.4, cool. > >>>> When I open a bash terminal session and type python, it brings up > >>>> version 2.3.5. If I type IDLE it brings up version 2.4.4. > >>>> My question: what do I have to do to get it to bring up 2.4.4 with the > >>>> "python" command? > >>>> Thanks for bringing light to my ignorance. > >>>> JF > >>> Sounds like a path problem. Apple's system Python is installed in > >>> /usr/bin. Your installation is probably in /usr/local/bin. Edit your > >>> profile or use the full path. > > >>> -- > >>> Kevin Walzer > >>> Code by Kevinhttp://www.codebykevin.com > >> The default python on tiger (2.3.5) is sym-linked to /usr/bin/python > >> and /usr/bin/pythonw. > > >> I found it easier to relink to the new installation path. This also > >> leaves /usr/bin/python23 and /usr/bin/pythonw23 still linked to the > >> original version if you want to quickly check something. > > >> Cheers, > >> Ted > > > OK, please give a little more information how I can accomplish this > > "re-link". > > Your Python 2.5 is likely installed here: > > /Library/Frameworks/Python.framework/Versions/Current/bin > > But OS X comes with a "system Python", version 2.3.5, likely installed here: > > /usr/bin > > If you look at /usr/bin, you'll see: > > lrwxr-xr-x 1 root wheel 9 Jan 31 17:24 python -> python2.3 > lrwxr-xr-x 1 root wheel 72 Jan 31 17:24 python2.3 -> > ../../System/Library/Frameworks/Python.framework/Versions/2.3/bin/python > lrwxr-xr-x 1 root wheel 10 Jan 31 17:24 pythonw -> pythonw2.3 > -rwxr-xr-x 1 root wheel 29704 Aug 19 2006 pythonw2.3 > > So, python is linked to python2.3, and python2.3 is in turn linked to > /System/Library/Frameworks/Python.framework/Versions/2.3/bin/python > > You need to (warning: watch for line wrap): > > sudo -s > > cd /usr/bin > ln -s /Library/Frameworks/Python.framework/Versions/Current/bin/python > python_current > ln -s /Library/Frameworks/Python.framework/Versions/Current/bin/pythonw > pythonw_current > rm python > rm pythonw > ln -s python python_current > ln -s pythonw pythonw_current > > However, that isn't what I did. I like the system being able to find and > use the system-installed python, but I like my scripts to use the python > version I installed (2.5). To get that, skip the above symlinking and > instead edit your .bash_profile file (hidden file inside your home > directory) and put these lines at the top: > > PATH="/Library/Frameworks/Python.framework/Versions/Current/bin:${PATH} > export PATH > > -- > pkm ~http://paulmcnett.com When I installed macpython 2.4.4, I think the install automatically changed the file: Users/me/.bash_profile. Here is what is says at the bottom of .bash_profile: # Setting PATH for MacPython 2.5 (these lines added by install) # The orginal version is saved in .bash_profile.pysave PATH="/Library/Frameworks/Python.framework/Versions/Current/bin:$ {PATH}" export PATH (Note I installed macpython 2.4.4 but the comment says something about python 2.5.) Ahh, I think I know what happened to the op's install. I don't think imacs come with the file: Users/me/.bash_profile. I had previously created the .bash_profile file in order to alter the bash prompt, so when I installed macpython 2.4.4, the install modified the pre- existing .bash_profile file and added the lines listed above. I bet the op didn't have a .bash_profile file on his system, so the install didn't make the path changes for him/her. From bbxx789_05ss at yahoo.com Wed Jun 13 06:10:23 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: Wed, 13 Jun 2007 03:10:23 -0700 Subject: Dive into Python 5.5 In-Reply-To: <1181724020.770062.286220@o11g2000prd.googlegroups.com> References: <1181724020.770062.286220@o11g2000prd.googlegroups.com> Message-ID: <1181729423.396026.5450@a26g2000pre.googlegroups.com> On Jun 13, 2:40 am, james_027 wrote: > Hi, > > class UserDict: > def __init__(self, dict=None): > self.data = {} > if dict is not None: self.update(dict) > > I just don't understant this code, as it is not also mention in the > book. the update is a method of a dict right? in my understanding the > last statement should be self.data.update(dict). > > someone please explain to me what happen where? > > Thanks > james This is what "Dive" says: --- To explore this further, let's look at the UserDict class in the UserDict module...In particular, it's stored in the lib directory in your Python installation. --- So you can actually locate the file UserDict.py on your computer and look at the code. If you don't want to do that, then the following is an explanation of what's going on with that code. Suppose you have a class like this: class Dog(object): def __init__(self): self.update() When __init__ executes, the only line in __init__ says go look in self for the method update() and execute it. That means the Dog class probably has at least one additional method: class Dog(object): def __init__(self): self.update() def update(self): print "hello" So if you wrote: d = Dog() the output would be: hello Ok, now suppose you add a line to __init__: class Dog(object): def __init__(self): self.data = {} self.update() def update(self): print "hello" Does the new line in __init__ affect the line self.update() in any way? Is there necessarily any connection between self.data and update()? No. However, if you look at the actual code for UserDict, you can see that inside the method update(), items are added to self.data, so there is a connection. Then the question is: why didn't the person who wrote the class just do the following in __init__: self.data.update(dict) Well, as it turns out, adding items to self.data is not that straight forward. self.data is a dict type and dict types have an update() method that requires another dict as an argument. But the 'dict' parameter variable in __init__ could be sent a dict type or it could be sent another instance of UserDict. So, the code to add items to self.data got complicated enough that the writer of the class decided to move the code into its own method. Note that just because the parameter variable is named 'dict' does not mean the argument sent to the function is a dict type. For instance, you could write this: dict = "hello world" As you can see, the variable named 'dict' does not refer to a dict type. Using a python type as a variable name is a horrible and confusing thing to do, so don't do it in your code. In addition, the writer of the class wanted to provide an update() method for the UserDict class, which could be called at any time, so instead of having to write the same code in two places: once in __init__ to initialize an instance with a given dict and a second time inside the update() method, the programmer wrote the code once in its own method and then called the method from __init__. From malaclypse2 at gmail.com Fri Jun 8 18:33:30 2007 From: malaclypse2 at gmail.com (Jerry Hill) Date: Fri, 8 Jun 2007 18:33:30 -0400 Subject: Splitting SAX results In-Reply-To: <1181335953.348151.57540@n15g2000prd.googlegroups.com> References: <1181187340.685296.284850@i38g2000prf.googlegroups.com> <4667A954.8070909@web.de> <1181335953.348151.57540@n15g2000prd.googlegroups.com> Message-ID: <16651e80706081533g2449c7ej9b7eca0b8243b702@mail.gmail.com> On 6/8/07, IamIan wrote: > Well SAX isn't the problem... maybe I should repost this with a > different title. The SAX part works just as I want, but the results I > get back need to be manipulated. No matter what I try I can't split a > result like 'Title 1:Description' on the colon without getting an > IndexError. Ideas anyone? I don't think you've showed us any examples of the code you're having trouble with. I don't see anything in your original post that tries to split strings. If you just want to know how split works, here's an example: >>> t = 'Title1:Description' >>> key, value = t.split(':') >>> print key Title1 >>> print value Description >>> If that doesn't help, show us a sample of some of the data you're working with, what you've tried so far, and what the end result is supposed to look like. -- Jerry From martin at v.loewis.de Fri Jun 1 03:56:18 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Fri, 01 Jun 2007 09:56:18 +0200 Subject: Thread-safety of dict In-Reply-To: References: Message-ID: <465FD122.9030108@v.loewis.de> > So there you have it: if you're using a dict with custom classes (or > anything other than str) across multiple threads, and without locking > it, it's possible (though presumably extremely rare) for a lookup to > fail even through the key was there the entire time. That could be fixed by adding a generation counter to the dictionary, right? Then an adversary would have to arrange for the generation counter to roll over for lookdict to not notice that the dictionary was modified. Regards, Martin From steve at laniels.org Tue Jun 26 11:56:47 2007 From: steve at laniels.org (Stephen R Laniel) Date: Tue, 26 Jun 2007 11:56:47 -0400 Subject: Return name of caller function? In-Reply-To: <652382.50464.qm@web35214.mail.mud.yahoo.com> References: <652382.50464.qm@web35214.mail.mud.yahoo.com> Message-ID: <20070626155646.GA28204@slaniel-laptop.itasoftware.com> On Mon, Jun 25, 2007 at 06:27:29PM -0700, Matthew Peter wrote: > For example, how do I get this to work? > > def func(): > print "This is", __?__ > return __caller__ > > def echo(): > print "This is ", __?__ > return func() inspect is your friend: http://docs.python.org/lib/inspect-stack.html -- Stephen R. Laniel steve at laniels.org Cell: +(617) 308-5571 http://laniels.org/ PGP key: http://laniels.org/slaniel.key From vintermann at gmail.com Fri Jun 22 10:19:09 2007 From: vintermann at gmail.com (Harald Korneliussen) Date: Fri, 22 Jun 2007 14:19:09 -0000 Subject: What was that web interaction library called again? Message-ID: <1182521949.813529.75140@w5g2000hsg.googlegroups.com> Hi, I remember I came across a python library that made it radically simple to interact with web sites, connecting to gmail and logging in with four or five lines, for example. I thought, "that's interesting, I must look into it sometime". Now there's this child I know who asked me about programming, especially programs that could do things like this, how difficult it was, and so on. I mentioned how I though Python was a good intro to programming, and there was a library which was perfect for what he wanted. Only now I've forgotten the name of the library! And try as I might, I can't find it with google. I know there are modules for it in the standard libraries, but this thing was brilliantly simple in comparison. It might have been some sort of research project, I can't remember... but perhaps someone here can remind me what it was? If so, there may be yet another young python programmer in training :-) From darder at gmail.com Mon Jun 11 11:36:42 2007 From: darder at gmail.com (Rafael Darder Calvo) Date: Mon, 11 Jun 2007 12:36:42 -0300 Subject: skip next item in list In-Reply-To: <6faf39c90706110753w7522c4f9q2f912495f56a19a8@mail.gmail.com> References: <1181573389.186279.108590@g37g2000prf.googlegroups.com> <6faf39c90706110753w7522c4f9q2f912495f56a19a8@mail.gmail.com> Message-ID: <4234e23c0706110836y1171dc7djbfc56428d90f610d@mail.gmail.com> On 6/11/07, Andre Engels wrote: > 2007/6/11, ahlongxp : > > list=('a','d','c','d') > > for a in list: > > if a=='a' : > > #skip the letter affer 'a' > > > > what am I supposed to do? > > There might be better ways to do it, but I would do: > > flag_last_a = False > for a in list: > if flag_last_a: > flag_last_a = False > continue > if a=='a': > flag_last_a = True > # Whatever is done when you don't skip > > -- > Andre Engels, andreengels at gmail.com > ICQ: 6260644 -- Skype: a_engels > -- > http://mail.python.org/mailman/listinfo/python-list > another way: def skip_after(l): i = iter(l) for x in i: yield x while x == 'a': x = i.next() depending on what to do in case of consecutive 'a's, change the 'while' for an 'if' list(skip_after('spam aand eggs')) ['s', 'p', 'a', ' ', 'a', 'd', ' ', 'e', 'g', 'g', 's'] From frank at chagford.com Mon Jun 11 10:37:06 2007 From: frank at chagford.com (Frank Millman) Date: Mon, 11 Jun 2007 07:37:06 -0700 Subject: Postpone creation of attributes until needed In-Reply-To: <1181569088.048872.254700@m36g2000hse.googlegroups.com> References: <1181553891.447344.109390@g4g2000hsf.googlegroups.com> <1181559496.911368.219210@p77g2000hsh.googlegroups.com> <1181564855.890242.116840@m36g2000hse.googlegroups.com> <1181569088.048872.254700@m36g2000hse.googlegroups.com> Message-ID: <1181572626.761699.158130@n4g2000hsb.googlegroups.com> On Jun 11, 3:38 pm, George Sakkis wrote: > On Jun 11, 8:27 am, Frank Millman wrote: > > > > Sorry - I made it more explicit above. It is the method that sets up > > all the missing attributes. No matter which attribute is referenced > > first, 'compute' sets up all of them, so they are all available for > > any future reference. > > > To be honest, it feels neater than setting up a property for each > > attribute. > > I don't see why this all-or-nothing approach is neater; what if you > have a hundred expensive computed attributes but you just need one ? > Unless you know this never happens in your specific situation because > all missing attributes are tightly coupled, properties are a better > way to go. It so happens that this is my specific situation. I can have a foreign key column in one table with a reference to a primary key column in another table. I have for some time now had the ability to set up a pseudo-column in the first table with a reference to an alternate key column in the second table, and this requires various attributes to be set up. I have recently extended this concept where the first table can have a pseudo-column pointing to a column in the second table, which is in turn a pseudo-column pointing to a column in a third table. This can chain indefinitely provided that the end of the chain is a real column in the final table. My problem is that, when I create the first pseudo-column, the target column, also pseudo, does not exist yet. I cannot call it recursively due to various other complications. Therefore my solution was to wait until I need it. Then the first one makes a reference to the second one, which in turn realises that in needs a reference to the third one, and so on. So it is recursive, but at execution-time, not at instantiation-time. Hope this makes sense. >The boilerplate code can be minimal too with an appropriate > decorator, something like: > > class A(object): > > def __init__(self,x,y): > self.x = x > self.y = y > > @cachedproperty > def z(self): > return self.x * self.y > > where cachedproperty is > > def cachedproperty(func): > name = '__' + func.__name__ > def wrapper(self): > try: return getattr(self, name) > except AttributeError: # raised only the first time > value = func(self) > setattr(self, name, value) > return value > return property(wrapper) > This is very neat, George. I will have to read it a few more times before I understand it properly - I still have not fully grasped decorators, as I have not yet had a need for them. Actually I did spend a bit of time trying to understand it before posting, and I have a question. It seems that this is now a 'read-only' attribute, whose value is computed by the function the first time, and after that cannot be changed. It would probably suffice for my needs, but how easy would it be to convert it to read/write? Thanks Frank From bruno.42.desthuilliers at wtf.websiteburo.oops.com Wed Jun 20 08:37:33 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Wed, 20 Jun 2007 14:37:33 +0200 Subject: Does altering a private member decouple the property's value? In-Reply-To: References: Message-ID: <46791f80$0$29091$426a74cc@news.free.fr> Ethan Kennerly a ?crit : > Hello, > > There are a lot of Python mailing lists. I hope this is an appropriate one > for a question on properties. It is. > I am relatively inexperienced user of Python. I came to it to prototype > concepts for videogames. Having programmed in C, scripted in Unix shells, > and scripted in a number of proprietary game scripting languages, I'm > impressed at how well Python meets my needs. In almost all respects, it > does what I've been wishing a language would do. So welcome onboard !-) > One example is properties. I really like properties for readonly > attributes, and their ability to make the interface more elegant, by hiding > uninteresting methods (like dumb get/set accessors). FWIW, since Python has properties, you often just don't need the getter/setter pairs. Start with a plain publi attribute, then switch to a computed one (using property or a custom descriptor) if and when needed. > > But a gotcha bit me in the behavior of properties that I didn't expect. > If another function accesses an underlying data member of a property, then > the data member returned by the property is no longer valid. > > Here is a session example. > >>>> class a_class: oops ! properties don't work properly with old-style classes. Use a new-style class instead: class AClass(object): > ... def __init__( self ): self.__p = None > ... def __set_p( self, new_p ): self.__p = new_p Take care, the name mangling invoked by the '__name' scheme may lead to undesired results. This feature should only be used when you want to make sure an attribute will not be accidentally used in a derived class. The idiomatic way to mark an attribute as "implementation" is a single leading underscore, ie: '_name'. > ... def reset( self ): self.__p = None > ... p = property( lambda self: self.__p, __set_p ) > ... (snip) > > I had wanted to access the private data member in the class to avoid > side-effects of the set method. > > Can someone show me how to reference the data member underlying a property > and update the property without calling the property set method? cf above. While we're at it, everything in Python being an object - yes, functions and methods too -, and there's nothing like a "private" modifier in Python. So s/private data member/implementation attribute/ !-) > By the way, I thought maybe that a variable outside of an __init__ method > would be static, An attribute defined in the class body (ie not in a method) becomes a class attribute (shared by all instances). > but as far as I can tell, it is dynamic. For example, the > following class appeared equivalent to the above for tests. > >>>> class a_class: > ... __p = None # No __init__ here, you create a class attribute > ... def __set_p( self, new_p ): self.__p = new_p And here, you create an instance attribute that will shadow the class attribute. > > I preferred not having the __init__ for this example and my prototype, > because I wasn't doing anything fancy, and it meant one less method that the > programmer needed to see. There are other ways to obtain the same result. Like defining the __new__ method (the proper constructor). (snip the rest) I think you should take some time to learn the Python object model - trying to apply C++/Java concepts to Python won't do it. Articles about new-style classes and descriptors on python.org should be a good starting point. My 2 cents... From len-l at telus.net Fri Jun 29 16:27:55 2007 From: len-l at telus.net (Lenard Lindstrom) Date: Fri, 29 Jun 2007 20:27:55 GMT Subject: Python's "only one way to do it" philosophy isn't good? In-Reply-To: References: <7xejjzmk7u.fsf@ruckus.brouhaha.com> <7xy7i7xjl5.fsf@ruckus.brouhaha.com> Message-ID: Douglas Alan wrote: > > [I]n Python, you can be 100% sure that your files > will be closed in a timely manner without explicitly closing them, as > long as you are safe in making certain assumptions about how your code > will be used. Such assumptions are called "preconditions", which are > an understood notion in software engineering and by me when I write > software. > So documenting an assumption is more effective than removing the assumption using a with statement? -- Lenard Lindstrom From steve at REMOVE.THIS.cybersource.com.au Thu Jun 7 08:39:41 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Thu, 07 Jun 2007 22:39:41 +1000 Subject: get a list from a string References: <1181213434.814684.236770@q19g2000prn.googlegroups.com> Message-ID: On Thu, 07 Jun 2007 11:06:54 +0000, simon kagwe wrote: >> exec("distances = [[1,1,1,1],[2,2,2,2]]") > Wow! So simple! > > Thanks a lot. :-) Yes, and when you embed this in your web-application, using data gathered from a web-form, the black-hat hackers will thank you for the security hole too. Surely a much better solution would be NOT to start with a string like "distances = [[1,1,1,1],[2,2,2,2]]" in the first place? Where does that string come from? If it comes from the user, at run-time, using exec is a MAJOR security hole. If it comes from the source code, then WHY??? I wish exec and eval were hidden away in a module so they were harder (but not impossible) to get to. Because I'm paranoid, I wish importing that module would print an warning saying "Are you MAD??? Don't do this!!!". I wish even more that Python would come with a built-in "make a list from a list representation" function, but that at least is fairly easy to create: you can modify Here is a discussion about just how hard (that is, probably impossible) it is to make eval safe: http://effbot.org/zone/librarybook-core-eval.htm From evan at yelp.com Wed Jun 20 00:20:39 2007 From: evan at yelp.com (Evan Klitzke) Date: Tue, 19 Jun 2007 21:20:39 -0700 Subject: stftime %z time conversion character In-Reply-To: <1182293804.305752.243840@w5g2000hsg.googlegroups.com> References: <1182293804.305752.243840@w5g2000hsg.googlegroups.com> Message-ID: On 6/19/07, Paul Boddie wrote: > Evan Klitzke wrote: > > Although it is not present in ANSI C, the GNU version of stftime > > supports the conversion character %z, which is a time offset from GMT. > > The four digit time offset is required in RFC 2822 dates/times, and is > > used by a number of other programs as well. I need to convert times > > that use this convention to python time representations, and because > > Python does not support the %z time conversion character I cannot > > simply use the time.strptime function. > > See this patch for an idea of the scope of this problem: > > https://sourceforge.net/tracker/?func=detail&atid=305470&aid=1667546&group_id=5470 > > > What solutions have people used for this? I'm currently thinking of > > creating a dict that maps four digit time offsets to the time zone > > name and then use the %Z token on that. Is there another (or better) > > way? > > Apart from a patch which would allow the time module functions to > produce the output you desire, an alternative might involve the > datetime module and timezone-aware datetime objects: > > http://groups.google.com/group/comp.lang.python/msg/9848f3054b4f3eae > > I refer indirectly to the pytz module in the above message: > > http://pytz.sourceforge.net/ > > Paul Thanks Paul, your answer was very helpful. -- Evan Klitzke From gagsl-py2 at yahoo.com.ar Thu Jun 14 21:30:38 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 14 Jun 2007 22:30:38 -0300 Subject: Problems with regular expressions References: <37BCDB14F06B98469A85DEC4771763B574C6EF@exch01.medianet.es> Message-ID: En Thu, 14 Jun 2007 21:42:02 -0300, Carlos Luis P?rez Alonso escribi?: > I have the next piece of code: > ------------------------------------------------------------------------ > if re.search('^(taskid|bugid):\\d+',logMessage): > return 0 > else: > sys.stderr.write("El comentario tiene que contener el > taskid:#### o el bugid:####") > return 1 > ------------------------------------------------------------------------- > The regular exprexi?n is "^(taskid|bugid):\\d+" > Mi problem is that if logMessage == "taskid:234" the regular expression > matched teorically, but the result is always "None" and the function > returns 1. For "taskid:234" it matches ok: py> re.search('^(taskid|bugid):\\d+',"taskid:1234") <_sre.SRE_Match object at 0x00ACB1E0> py> re.search('^(taskid|bugid):\\d+',"asdfa fa taskid:1234") py> re.search('^(taskid|bugid):\\d+'," taskid:1234") py> re.search('^(taskid|bugid):\\d+',"taskid:123adfa asfa lkjljlj") <_sre.SRE_Match object at 0x00ACB8A0> Because of the ^, it *only* matches at the start of the line. If you want a match anywhere (as implied by your error message), just remove the ^. -- Gabriel Genellina From see.signature at no.spam Fri Jun 1 03:13:58 2007 From: see.signature at no.spam (Eric Brunel) Date: Fri, 01 Jun 2007 09:13:58 +0200 Subject: pack() and the division of vertical space References: <1180633504.182393.20960@o5g2000hsb.googlegroups.com> Message-ID: On Thu, 31 May 2007 19:45:04 +0200, christopherlmarshall at yahoo.com wrote: > I am trying to figure out how to stack two widgets in a frame > vertically so that they both expand horizontally and during vertical > expansion, the top one sticks to the top of the frame and the bottom > one consumes the remaining vertical space. I thought this would do it > but it doesn't. What am I missing? [snip code] For this kind of stuff, don't use pack; use grid. It will be far easier to get it working, to read afterwards and to maintain, even if it's slightly more verbose. IMHO, pack should only be used to create rows or columns of widgets, without any resizing policy, or to put an entire widget into a container. If you do anything more complicated than that, you'll find grid much easier to handle. HTH -- python -c "print ''.join([chr(154 - ord(c)) for c in 'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])" From fredrik at pythonware.com Mon Jun 11 15:47:41 2007 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 11 Jun 2007 21:47:41 +0200 Subject: with as a reserved word In-Reply-To: <1181589497.399747.185440@z28g2000prd.googlegroups.com> References: <1181574196.682123.291010@a26g2000pre.googlegroups.com> <1181589497.399747.185440@z28g2000prd.googlegroups.com> Message-ID: BBands wrote: > I don't have an opinion, pro or con, on this PEP, but I'll bet that it > breaks a lot of code. that's why you get warnings in 2.5, so you have time to update your code; see: http://www.python.org/dev/peps/pep-0005/ estimating what "a lot" is isn't trivial, but it's worth noting that a search for "lang:python \swith\W" over at google's code search only brings up about 200 cases, and most of those are found in comments and string literals. and in Zope. From walterbyrd at iname.com Thu Jun 28 12:01:37 2007 From: walterbyrd at iname.com (walterbyrd) Date: Thu, 28 Jun 2007 09:01:37 -0700 Subject: Collections of non-arbitrary objects ? In-Reply-To: <4682ca40$0$14981$426a74cc@news.free.fr> References: <1182449993.223262.229500@z28g2000prd.googlegroups.com> <87k5twx4hf.fsf@benfinney.id.au> <1182559502.069773.321620@i38g2000prf.googlegroups.com> <87wsxvrzsj.fsf@benfinney.id.au> <1182620734.940718.196520@e16g2000pri.googlegroups.com> <467ed491$0$27132$426a34cc@news.free.fr> <1182780863.067601.89320@d30g2000prg.googlegroups.com> <46801791$0$32172$426a34cc@news.free.fr> <1182863704.364272.5950@i13g2000prf.googlegroups.com> <46812159$0$24920$426a74cc@news.free.fr> <1182961835.134162.311670@x35g2000prf.googlegroups.com> <4682ca40$0$14981$426a74cc@news.free.fr> Message-ID: <1183046497.377835.125290@e16g2000pri.googlegroups.com> > > Did you try to sort a tuple ? > > >>> (1, "aaa").sort() > Traceback (most recent call last): > File "", line 1, in ? > AttributeError: 'tuple' object has no attribute 'sort' I can do this: >>> x = (3,2,1) >>> x = tuple(sorted(list(x))) Which, although senseless, effectively sorts the x tuple. But, you are right, I am not really sorting the tuple, I'm sorting a list, which has been made from the tuple, then changing it back to a tuple. Actually, I can even do it in one line: x = tuple(sorted(list((3,2,1)))) From claird at lairds.us Sun Jun 10 14:59:18 2007 From: claird at lairds.us (Cameron Laird) Date: Sun, 10 Jun 2007 18:59:18 +0000 Subject: Python, Dutch, English, Chinese, Japanese, etc. References: <1180965224.136341.271180@z28g2000prd.googlegroups.com> Message-ID: <69utj4-0ac.ln1@lairds.us> In article , I asked: >In article <1180965224.136341.271180 at z28g2000prd.googlegroups.com>, >ahlongxp wrote: > . > . > . >>I'm a Chinese. >>Language/English is really a big problem for Chinese programmers. >>If python can be written in Chinese, it may become the most popular >>program language in China(though popular alreay). >>Considering the potential large amount of users in China, the effort >>of internationalization for Chinese will totally worth. > . > . > . >Tcl can be (more-or-less) written in Chinese now. How popular is it >among Chinese-speaking developers? A private correspondent told me it's not at all popular--Tcl, in China, that is. On the other hand, I came across , and, more significantly, . From moishyyehuda at gmail.com Tue Jun 5 12:14:51 2007 From: moishyyehuda at gmail.com (moishyyehuda at gmail.com) Date: Tue, 05 Jun 2007 16:14:51 -0000 Subject: Sending cookies with python. When download with python Message-ID: <1181060091.747809.91520@p47g2000hsd.googlegroups.com> I need to download files off a password protected website. So if I try to download files off the site with python I will be blocked. Is there anyway to send cookies with python. So I will be authenticated. From gagsl-py2 at yahoo.com.ar Tue Jun 12 21:01:48 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 12 Jun 2007 22:01:48 -0300 Subject: Splitting SAX results References: <1181187340.685296.284850@i38g2000prf.googlegroups.com> <4667A954.8070909@web.de> <1181335953.348151.57540@n15g2000prd.googlegroups.com> <1181675805.996632.311070@r19g2000prf.googlegroups.com> Message-ID: En Tue, 12 Jun 2007 16:16:45 -0300, IamIan escribi?: > I do know how split works, but thank you for the response. The end > result that I want is a dictionary made up of the title results coming > through SAX, looking like {'Title1: Description', > 'Title2:Description'}. > > The XML data looks like: > > Title1:Description > Link > Desc > Author > Date > > > Title2:Description > Link > Desc > Author > Date > > > I've tried different approaches, a couple of which I've added to the > code below (only running one option at a time): Forget about SAX. Use ElementTree instead py> import xml.etree.cElementTree as ET py> f = open("x.xml","r") py> tree = ET.parse(f) py> for item in tree.getiterator('item'): ... print item.findtext('title') ... Title1:Description Title2:Description ElementTree is infinitely more flexible and easier to use. See -- Gabriel Genellina From orsenthil at users.sourceforge.net Thu Jun 28 14:22:16 2007 From: orsenthil at users.sourceforge.net (O.R.Senthil Kumaran) Date: Thu, 28 Jun 2007 23:52:16 +0530 Subject: urllib2 : https and proxy In-Reply-To: <1183021663.053143.275090@q69g2000hsb.googlegroups.com> References: <1183021663.053143.275090@q69g2000hsb.googlegroups.com> Message-ID: <20070628182216.GA4332@gmail.com> > Hello all, > > I'm facing a strange behavior of urllib2 trying to access gmail > account behind a proxy (Squid). > First off, your password wont work. See if you can get a new one. :-) Then to setup proxy suppor for urllib2, do the steps: proxy_url = 'http://' + PROXY_USER + ':' + PROXY_PASSWORD + \ '@' + PROXY_IP + ':' + PROXY_PORT proxy_support = urllib2.ProxyHandler({'http': proxy_url}) opener = urllib2.build_opener(proxy_support, urllib2.HTTPHandler) urllib2.install_opener(opener) Substitute PROXY_* with actual values and then do urllib2.urlopen(site) which will go through the proxy. -- O.R.Senthil Kumaran http://uthcode.sarovar.org From mccredie at gmail.com Mon Jun 18 18:31:40 2007 From: mccredie at gmail.com (Matimus) Date: Mon, 18 Jun 2007 22:31:40 -0000 Subject: Making static dicts? In-Reply-To: References: Message-ID: <1182205900.372542.168170@n15g2000prd.googlegroups.com> On Jun 18, 1:46 pm, Ognjen Bezanov wrote: > Hello! > > Just to ask, is it possible to make a static dictionary in python. So > that the keys in the dictionary cannot be removed, changed or new ones > added, but the value pairs can. > > Is this possible with python? > > thanks, > > Ognjen. How much functionality do you need? Something like this might work (though it could use better error messages. [code] class StaticDict: def __init__(self,srcdict): self._srcdict = srcdict def __getitem__(self,idx): return self._srcdict[idx] [/code] Use it like this: >>> sd = StaticDict({'a':'b'}) >>> sd['a'] 'b' >>> sd['b'] Traceback (most recent call last): File "", line 1, in ? File "", line 5, in __getitem__ KeyError: 'b' >>> sd['a'] = "hello" Traceback (most recent call last): File "", line 1, in ? AttributeError: StaticDict instance has no attribute '__setitem__' >>> From Roland.Puntaier at br-automation.com Mon Jun 4 09:31:55 2007 From: Roland.Puntaier at br-automation.com (Roland Puntaier) Date: Mon, 4 Jun 2007 15:31:55 +0200 Subject: c[:]() In-Reply-To: <00b301c7a690$25af37d0$240110ac@Muse> Message-ID: Hi, I have started to look into the last postings. It is funny and sad how people talking the same language cannot understand each other. I have become curious on what exactly you mean. Warren, can you please restate your point. When doing so, please define every identifier or non-plain english word before you use it and be concise. e.g. You cannot use b if it is not clear what it means. When writing "c[:]()" there is no "b". So where does "b" come from? You told us that "b" is a container (*), but where should the python interpreter or the people take it from. People start to guess, as I did: (1) - Might you mean: "b() for b in c". (I use python syntax here) This means c is a container, an undertanding that is supported also by the used slicing ("[:]"). (2) - Let's suppose that by (*) you mean that, in addition to "c", "b" is a container, too. (3) - Now for a standard container "b()" does not make sense. Maybe you mean "b[:]()" according to the guessed interpretation (1). This would then be a recursive evaluation of all functions with no parameters in a tree ("tree" in the informatics sense). (end of my guess) I think somehow it should be possible to convey an idea so that others can grasp it. If it does not work the first time, it is good to clarify the points that one found others to misunderstand. Otherwise one risks to be regarded as esoteric. Thanks, Roland From jeff at taupro.com Thu Jun 7 03:35:57 2007 From: jeff at taupro.com (Jeff Rush) Date: Thu, 07 Jun 2007 02:35:57 -0500 Subject: Calling Usergroup Organizers (and Wannabees) Message-ID: <4667B55D.7040301@taupro.com> We'd like to strengthen and raise the visibility of Python usergroups and foster the creation of new ones, by sharing the valuable experiences of those leaders around the community who make it happen. [1] One step is to make others more aware of what is already happening, perhaps in their own neighborhood re Python meetings. I've created a shared blog and invite organizers of existing groups to send me their email address to get privs to post to it. http://python-groups.blogspot.com/ Because these postings will be distributed far and wide, a posting should be of interest to those who did not attend but are considering doing so, or that might be instructive to organizers in other cities. An overview of what was covered in a past meeting, or an announcement with substance on what an upcoming meeting is going to be about are good postings. A simple date and local address, or that the pizza was good last week, is not. ;-) [2] A second step is to encourage and support new organizers in forming groups in their area. There is a strong demand for such meetings, but many are uncertain how to go about it. Therefore I've created a new mailing list on which experienced and new organizers can share tips on getting started, whether about getting the word out, finding a place to meet or getting interesting speakers. http://mail.python.org/mailman/listinfo/group-organizers Those of us with a history of involvement in a usergroup often forget that many people have never attended a usergroup meeting, or lack experience in running one, so let's help strengthen this aspect of Python. We could use some videos or photos of group meetings as well, posted to youtube.com/flickr.com and the link emailed to me for use. I'd also like to reach out to the existing, successful usergroups and ask them to spread the word about their efforts by being interviewed by Ron Stephens on Python411, and/or writing up an article on how your group got started for Tennessee Leeuwenburg of _The Python Papers_. Even a simple "what a typical meeting is like in my area" is helpful. http://www.awaretek.com/python/index.html http://pythonpapers.cgpublisher.com/ It would be especially interesting to see how usergroups operate in various countries around the world, and perhaps help bring together these regions. In closing, please, for existing usergroups as well as new ones coming online, update the entry for your group on the roster of Python usergroups. http://wiki.python.org/moin/LocalUserGroups Jeff Rush Advocacy Coordinator From gagsl-py2 at yahoo.com.ar Tue Jun 26 21:19:56 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 26 Jun 2007 22:19:56 -0300 Subject: Padding en References: <9e2f512b0706241250x57cc8d40saadfaef794563dc2@mail.gmail.com> <9e2f512b0706261157t750c3117n91c39433256867a3@mail.gmail.com> Message-ID: En Tue, 26 Jun 2007 15:57:33 -0300, Sebastian Bassi escribi?: > Si, pero resulta que lo tuve que complicar un poco porque sha esta en > distintas librerias segun la version de Python y tambien no puedo > hacer un upper() directamente sin verificar que manden un string > primero. Tambien otra diferencia es que el encode64 en Python<2.5 > viene con un EOL mientras que en 2.5, no. Al final queda asi: > > def seguid(seq): > try: > #Python 2.5 sha1 is in hashlib > import hashlib > m = hashlib.sha1() > except: > #For older versions > import sha > m = sha.new() A mi me ponen nervioso los except sin nada :) asi que you usaria: except ImportError: Sino, estarias atrapando tambien *cualquier* otra excepcion, que quizas no tiene nada que ver con hashlib; por ejemplo, apretar Ctrl-C para abortar el programa no sirve cuando esta ejecutando justo esa parte del codigo. > if type(seq)!="str": > seq=seq.tostring().upper() > else: > seq=seq.upper() Aparte de los muy sabios consejos que te dieron sobre *no* testear el tipo explicitamente, hay que notar que as? como est? escrito, nunca se va a usar el tostring() porque "str" no deberia estar escrito entre comillas (deberia decir: if type(seq)!=str) > m.update(seq) > try: > #For Python 2.5 > return base64.b64encode(m.digest()).rstrip("=") > except: > #For older versions > import os > return base64.encodestring(m.digest())\ > .replace(os.linesep,"").rstrip("=") [Aparte del except, que deberia atrapar s?lo AttributeError]. encodestring agrega un '\n', fijo, no usa os.linesep (que en Windows vale '\r\n', y entonces te fallar?a). -- Gabriel Genellina From deets at nospam.web.de Wed Jun 20 04:09:22 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 20 Jun 2007 10:09:22 +0200 Subject: static python classes ? References: <1182254405.901790.189190@p77g2000hsh.googlegroups.com> <5dq518F35ubh4U1@mid.uni-berlin.de> <5dquobF35956oU1@mid.individual.net> Message-ID: <5ds5liF30eueiU1@mid.uni-berlin.de> Bjoern Schliessmann wrote: > Diez B. Roggisch wrote: > >> With other OOP languages you mean Java. Which does have static >> methods because they lack the notion of a function by its own, so >> the shoehorned them into their "everything is inside a >> class"-paradigm. > > ACK, but doesn't C++ have static methods too? Might be, I'm a bit rusty on C++. But they do have "normal" functions as well - so I figured the OP wouldn't have troubles then. Diez From __peter__ at web.de Mon Jun 11 07:44:10 2007 From: __peter__ at web.de (Peter Otten) Date: Mon, 11 Jun 2007 13:44:10 +0200 Subject: Postpone creation of attributes until needed References: <1181553891.447344.109390@g4g2000hsf.googlegroups.com> <1181559496.911368.219210@p77g2000hsh.googlegroups.com> Message-ID: Frank Millman wrote: > I tried that, but I get AttributeError: 'A' object has no attribute > '__dict__'. That's what you get for (ab)using __slots__ without understanding the implications ;) You can instead invoke the __getattr__() method of the superclass: super(A, self).__getattr__(name) Peter From pete.forman at westerngeco.com Wed Jun 20 08:54:13 2007 From: pete.forman at westerngeco.com (Pete Forman) Date: Wed, 20 Jun 2007 13:54:13 +0100 Subject: SimplePrograms challenge References: Message-ID: Steve Howell writes: >> 2) assert is not the simplest example of doctest. >> The style should be >> >> >>> add_money([0.13, 0.02]) >> 0.15 >> >>> add_money([100.01, 99.99]) >> 200.0 >> >>> add_money([0, -13.00, 13.00]) >> 0.0 >> > > That's not clear cut to me. I think vertical > conciseness has an advantage for readability, as it > means you get to keep more "real" code on the screen. What I meant was that doctest should be "type this into the interpreter and you should see that". A doctest is not a unit test, though it may form a subset of the tests. There should only be enough doctests to enclue a human reader. Comprehensive testing should use a larger framework. Doctests in separate files can do this but I would use py.test, or alternatives like nose or Testoob. >>> 2 + 2 4 "assert 2 + 2 == 4" is a concise way of writing a unit test but it is not the best way to use doctest IMHO. >> 3) which fails :-( So both the unittest and doctest >> examples ought to >> be redone to emphasize what they are doing >> without getting bogged >> down by issues of floating point representations. >> > > I was the one who originally posted the floating point > example (with yet another style of unit testing, BTW), > and I agree that the subtleties of floating point do > kind of cloud the issue. I welcome a better example. > What I didn't realize is that there's an actual error. > Are you saying the program fails? On which test? Python 2.5.1 on XP: Failed example: add_money([0.13, 0.02]) Expected: 0.15 Got: 0.14999999999999999 -- Pete Forman -./\.- Disclaimer: This post is originated WesternGeco -./\.- by myself and does not represent pete.forman at westerngeco.com -./\.- the opinion of Schlumberger or http://petef.port5.com -./\.- WesternGeco. From aleax at mac.com Fri Jun 29 10:43:27 2007 From: aleax at mac.com (Alex Martelli) Date: Fri, 29 Jun 2007 07:43:27 -0700 Subject: Set builtin lookups References: Message-ID: <1i0gl4v.1kwitmer3zhkyN%aleax@mac.com> Steve Holden wrote: > Marc 'BlackJack' Rintsch wrote: > > In , Evan Klitzke > > wrote: > > > >> I have a question about the internal representation of sets in Python. > >> If I write some code like > >> > >> if x in some_list: > >> do_something() > >> > >> the lookup for the in statement is O(n), where n is the number of > >> elements in the list. Is this also true if I am using a set or are > >> sets represented by a hash table? > > > > Sets are implemented as hash tables. > > > > Ciao, > > Marc 'BlackJack' Rintsch > > More importantly, no, neither sets nor dictionaries have O(N) lookup > costs. As an experiment or two can show. The exception would be for objects with a bad or unlucky __hash__ that happens to return the same value for every object: class oops(object): def __hash__(self): return 123456 this one you might expect to produce O(N) behavior:-). Alex From max at alcyone.com Fri Jun 1 02:24:19 2007 From: max at alcyone.com (Erik Max Francis) Date: Thu, 31 May 2007 23:24:19 -0700 Subject: c[:]() In-Reply-To: References: <1180504190.055427.173610@h2g2000hsg.googlegroups.com> <1180554872.3356.30.camel@dot.uniqsys.com> <465DF3DE.40404@cc.umanitoba.ca> <1180566831.239580.199300@m36g2000hse.googlegroups.com> <005401c7a31a$136f7fe0$240110ac@Muse> <135tobve86qj808@corp.supernews.com> <135tru124pie2b3@corp.supernews.com> <135tv1bjqgbmsc9@corp.supernews.com> Message-ID: <9qudnbFRU9QHJsLbnZ2dnUVZ_rKvnZ2d@speakeasy.net> Warren Stringer wrote: > As mentioned a while back, I'm now predisposed towards using `do(c)()` > because square brackets are hard with cell phones. The one mitigating factor > for more general use, outside of cell phones, is speed. The speed at which you can type code is almost _never_ a valid reason to make something brief. Code gains readability from verbosity. (That can be taken too far, of course, but that certainly doesn't apply here.) Either way, something like `do(c)()` to do what you want is easily implementable in Python, and always has been. Same thing with your `c()` or `c[:]()` solutions (though the latter makes no semantic sense); just use custom sequence types. > The questions about implementing a working c[:]() are: > 1) Does it break anything? > 2) Does it slow anything down? > 3) Could it speed anything up? > 4) Does it make code easier to read? > 5) What question(s) did I forget to ask? You keep sticking the slice in there. That still makes no sense. The fundamental reason it does not make logical sense to make a list callable (which would then call its elements) is that lists can contain objects that aren't callable. So then, if you want lists to be callable, the question becomes, what should it do with the elements that aren't callable? Choke on the first one? Ignore them? Abort entirely and not call any of them? This kind of a design question can go every possible way depending on what particular application you're using the calling syntax for, so the proper design question from a language perspective is not to choose any. If you want a callable sequence (which calls its elements and has any or all of the above behaviors), it is _trivial_ to make one. There is no need for support for this, because what it should do is not clear. > I use `c[:]()` because it is unambiguous about using a container There are containers that don't support slicing (a stack, for instance), so you're not using the right terminology here. If you do mean general containers, then your slicing violates duck typing since it effectively enforces a constraint that may not be desired. _If_ one were to have callable containers, then callable containers should be usable in _any_ context in which an object is called, not just ones where slices were done. If you intend `c[:]()` to have different semantics than `c()` -- it isn't clear from your comments whether you mean it to or not, but you keep nonsensically mentioning the slicing notation -- then you're _really_ out in left field. Now that requires operations to behave differently in different contexts, which is a huge can of worms and rapidly makes code unreadable. In short, your repeated use of `c[:]()` indicates a fundamental misunderstanding about Pythonic style _and_ substance. >> If you're not willing to do that, but still insisting that `c[:]()` >> makes sense, then perhaps it would be more advisable to learn more about >> Python rather than try to suggest profound changes to the language and >> its conventions. > > You're right. At the same time, version 3 is coming up soon. There is a > short window of opportunity for profound changes. Soon isn't all that soon. Furthermore, it is very unlikely that someone is going to be able to suggest profound and useful changes to Python without first being familiar with it. So stabbing in the dark is not going to be very constructive for either learning Python, or suggesting useful improvements. That's just the way the ball bounces, unfortunately. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM, Y!M erikmaxfrancis To endure what is unendurable is true endurance. -- (a Japanese proverb) From bronger at physik.rwth-aachen.de Tue Jun 26 06:24:46 2007 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Tue, 26 Jun 2007 12:24:46 +0200 Subject: text-mode tree viewer? Message-ID: <873b0fj9n5.fsf@wilson.homeunix.com> Hall?chen! I'm looking for a package/routine that can convert [["Peter", ["Ian", [["Randy", ["Clara"]]]]], "Paul", ["Mary", ["Arthur"]]] into +---> Peter | | | +---> Ian | | | +---> Randy | | | +---> Clara | +---> Paul | +---> Mary | +---> Arthur Neither the input data structure nor the output must be exactly like here but probably you got the idea. Thank you for any hints! Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus Jabber ID: bronger at jabber.org (See http://ime.webhop.org for ICQ, MSN, etc.) From lialie at gmail.com Sun Jun 3 07:31:07 2007 From: lialie at gmail.com (KingMax) Date: Sun, 03 Jun 2007 04:31:07 -0700 Subject: How to control the creation of an instance? In-Reply-To: <1180851453.441872.107890@k79g2000hse.googlegroups.com> References: <1180851453.441872.107890@k79g2000hse.googlegroups.com> Message-ID: <1180870267.645585.59320@a26g2000pre.googlegroups.com> On Jun 3, 2:17 pm, 7stud wrote: > On Jun 2, 10:31 pm, lialie wrote: > > > > > Hi, > > > suppose i have a free_object list[Sample1, Smaple2....]. when create a > > new object sample(*args, **kwds), if free_object_list isn't empty, just > > pop one from free_object_list instead of creating a new instance. > > > any way to do this? > > > I do some work as follows: > > > class Sample(object): > > used_object = [] > > free_object = [] > > > def __init__(self, *args, **kwds): > > pass > > > def __new__(self, *args, **kwds): > > if Sample.free_object: > > obj = Sample.free_object.pop(0) > > else: > > obj = object.__new__(Sample, *args, **kwds) > > Sample.used_object.append(obj) > > return obj > > > ######## still get a new instance :( > > > def Release(self): > > Sample.used_object.remove(self) > > Sample.free_object.append(self) > > return True > > This seems to work for me: > > import collections > > class Sample(object): > > free_objects = collections.deque() > used_objects = [] > > def __new__(cls, *args, **kwds): > if not Sample.free_objects: > temp = object.__new__(Sample, args, kwds) > Sample.used_objects.append(temp) > return temp > else: > return Sample.free_objects.popleft() > > def __init__(self, *args, **kwds): > self.args = args > self.kwds = kwds > > def release(self): > Sample.used_objects.remove(self) > Sample.free_objects.append(self) > > s1 = Sample(10, name="Bob") > print s1 > print s1.args > print s1.kwds > > s2 = Sample("red", name="Bill") > print s2 > print s2.args > print s2.kwds > > s1.release() > s3 = Sample("blue", name="Tim") > print s3 > print s3.args > print s3.kwds Thank you. > def __new__(cls, *args, **kwds): > if not Sample.free_objects: > temp = object.__new__(Sample, args, kwds) > Sample.used_objects.append(temp) > return temp > else: > return Sample.free_objects.popleft() # Here you may lost one object :) The free_objects list doesn't have orders. My sample code seems to work. But follows may create a new instance: class Sample(wx.Image): free_objects = [] used_objects def __int__(self, *args, **kwds): wx.Image.__init__(self, *args, **kwds) #### play tricks with me :) pass def __new__(cls, *args, **kwds): # The same wx.Image always create a new instance. It seems that I have to avoid wx.Image.__init__. From eopadoan at altavix.com Fri Jun 29 14:37:27 2007 From: eopadoan at altavix.com (Eduardo "EdCrypt" O. Padoan) Date: Fri, 29 Jun 2007 15:37:27 -0300 Subject: Voluntary Abstract Base Classes In-Reply-To: <5f56302b0706290838j377ed7dct2cd2807394f791cf@mail.gmail.com> References: <5f56302b0706290838j377ed7dct2cd2807394f791cf@mail.gmail.com> Message-ID: On 6/29/07, Daniel Nogradi wrote: > Hi list, > > Well, the short question is: what are they? I've read Guido's python > 3000 status report on > http://www.artima.com/weblogs/viewpost.jsp?thread=208549 where he > mentions ABC's but don't quite understand what the whole story is > about. The story is at PEP 3119: http://www.python.org/dev/peps/pep-3119/ > Anyone has good use cases? The Rationale in the PEP may help you to imagine one. -- EduardoOPadoan (eopadoan->altavix::com) Bookmarks: http://del.icio.us/edcrypt From jeffrey.rollin at gmail.com Tue Jun 12 06:09:04 2007 From: jeffrey.rollin at gmail.com (Jeff Rollin) Date: Tue, 12 Jun 2007 11:09:04 +0100 Subject: Newsgroup query Message-ID: Hi. You may have just seen that I posted a more-or-less identical message to the group. This was because the message w/ the attached file didn't show up for me - but I also just got a reply which references the message with the attached file. Why do I not see my messages with attached files in the newsgroup, and is there any way to configure this? TIA. Jeff From jfine at pytex.org Fri Jun 22 19:26:30 2007 From: jfine at pytex.org (Jonathan Fine) Date: Sat, 23 Jun 2007 00:26:30 +0100 Subject: Packing a simple dictionary into a string - extending struct? References: <467B7585.5040801@pytex.org> <1182517176.444776.251800@i13g2000prf.googlegroups.com> Message-ID: <467C5AA6.3050706@pytex.org> John Machin wrote: > def unpack(bytes, unpack_entry=unpack_entry): > '''Return dictionary gotten by unpacking supplied bytes. > Both keys and values in the returned dictionary are byte-strings. > ''' > bytedict = {} > ptr = 0 > while 1: > key, val, ptr = unpack_entry(bytes, ptr) > bytedict[key] = val > if ptr == len(bytes): > break > # That's beautiful code -- as pretty as a cane-toad. Well, it's nearly right. It has a transposition error. > # Well-behaved too, a very elegant response to unpack(pack({})) Yes, you're right. An attempt to read bytes that aren't there. > # Try this: > blen = len(bytes) > while ptr < blen: > key, val, ptr = unpack_entry(bytes, ptr) > bytedict[key] = val > > return bytedict I've committed such a change. Thank you. -- Jonathan From gagsl-py2 at yahoo.com.ar Tue Jun 12 05:21:51 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 12 Jun 2007 06:21:51 -0300 Subject: How can I parse False from c extension? References: <1181635633.091625.23100@x35g2000prf.googlegroups.com> Message-ID: En Tue, 12 Jun 2007 05:07:13 -0300, Allen escribi?: >> From python command, I call C extension method >>>> import PyRPC >>>> PyRPC.addBool(False) > > In C extension, I know parse integer value like this: > PyArg_ParseTuple(args, "i", &nValue); > > But, how can I parse the False value? Parse them as integers, with False==0 and True==1. -- Gabriel Genellina From facundo at taniquetil.com.ar Thu Jun 7 11:54:44 2007 From: facundo at taniquetil.com.ar (Facundo Batista) Date: Thu, 7 Jun 2007 15:54:44 +0000 (UTC) Subject: ftplib error- Large file References: <1181147997.268014.50550@i38g2000prf.googlegroups.com> <1181207449.968884.158930@n15g2000prd.googlegroups.com> Message-ID: half.italian at gmail.com wrote: > Why would storbinary throw an exception even when the file transfer > was successful? Why would the exception not be thrown until after the > file was sent? Shouldn't ftplib return something like (104, > "Connection reset by peer") instead of throwing an error? Is my > reasoning off somewhere? There was an error, the connection was reset by peer. The error code is 104. As it *was* an error, an exception is correct. You always can hide it yourself, with try/except... Regards, -- . Facundo . Blog: http://www.taniquetil.com.ar/plog/ PyAr: http://www.python.org/ar/ From steve at REMOVE.THIS.cybersource.com.au Fri Jun 22 21:07:04 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sat, 23 Jun 2007 11:07:04 +1000 Subject: People who reply to spammers [was: Re: I need some cleanings tips and advice.] References: <1182528064.446459.49420@n2g2000hse.googlegroups.com> <467bf4c9@news.nucleus.com> Message-ID: On Fri, 22 Jun 2007 16:11:58 +0000, Colin B. replied to a spammer with: > Let's see if I get this right. > > You create a website for a subject that you know nothing about. Then you > try to solicit content in a bunch of programming language newsgroups. > > Wow, that's pretty pathetic, even for a google-groups poster! > > Begone with you. You know, my ISP did a pretty good job of recognizing the original post as spam, and dropped it, so I never even saw it until your post came along. So I wonder, who is more pathetic -- the spammer, who at least is hoping to make money from his rudeness, or idiots who try to reason with spammers AND include the spam in their reply? Thanks a lot Colin, I really appreciate you finding a way to bypass the spam filtering. Not. (You know, if I were a spammer, I would disguise my spam as an indignant response to spam, thus guaranteeing a vastly greater audience.) Colin, if that doesn't convince you to STOP ENGAGING SPAMMERS IN DISCUSSION, no matter how witty you think your reply is, let me point out that by rudely including the text of the spam in your post, you are associating your name and email address with spam. That might not be such a good thing to do as more and more people use Bayesian filtering. Follow-ups set to comp.lang.python. -- Steven. From jimbomaan at yahoo.com Tue Jun 12 00:25:31 2007 From: jimbomaan at yahoo.com (why?) Date: Tue, 12 Jun 2007 04:25:31 -0000 Subject: Problem with following python code Message-ID: <1181622331.955264.31610@i38g2000prf.googlegroups.com> I've been having problem with the following code. It's supposed to print the prime numbers between 10 and 100. But i'm not getting any output, i.e. i guess the outer 'for' loop is being traversed only once. I would be greatful if you could help me out. Thanx! >>> f=1 >>> for i in range(10,100): ... for j in range(2,i): ... if i%j==0: ... f=0 ... break ... else: continue ... if f==1: ... print i, ... From milton.trachtenburg at gmail.com Sat Jun 16 09:06:23 2007 From: milton.trachtenburg at gmail.com (Milt) Date: Sat, 16 Jun 2007 13:06:23 -0000 Subject: Do U have anything to share with this students In-Reply-To: <1181926856.041008.258770@o11g2000prd.googlegroups.com> References: <1181926856.041008.258770@o11g2000prd.googlegroups.com> Message-ID: <1181999183.047568.44000@m36g2000hse.googlegroups.com> On Jun 15, 1:00?pm, slvsl... at gmail.com wrote: > This is a network of students. Find the people of your kind there > > http://tinyurl.com/33uvla > > Click and register to access millions of students. Your link doesn't work. From kukovec at gmail.com Tue Jun 12 05:27:00 2007 From: kukovec at gmail.com (Rostfrei) Date: Tue, 12 Jun 2007 09:27:00 -0000 Subject: Thunderbird access to this newsgroup Message-ID: <1181640420.561878.224690@x35g2000prf.googlegroups.com> Hello! I'm writing this message over Google web access. I'm trying to access to the comp.lang.python newsgroup trough the Thunderbird, but I just can't configure it properly. What is the news server for this newsgroup. If I ping comp.lang.python it is not resolved. For instance I had no problem configuring Eclipse news server. I just entered news.eclipse.org as a news server address and after it I can browse available groups. Your help will be much appreciated! Regards, Marko Kukovec From vedrandekovic at v-programs.com Thu Jun 21 15:35:59 2007 From: vedrandekovic at v-programs.com (vedrandekovic at v-programs.com) Date: Thu, 21 Jun 2007 12:35:59 -0700 Subject: Changing the names of python keywords and functions In-Reply-To: <1182453504.084126.211450@q69g2000hsb.googlegroups.com> References: <1182452862.872909.206780@u2g2000hsc.googlegroups.com> <1182453504.084126.211450@q69g2000hsb.googlegroups.com> Message-ID: <1182454559.346521.294780@c77g2000hse.googlegroups.com> moegoldb... at gmail.com je napisao/la: > I'm not quite clear on what you are asking, but > you can use the __import__() function to import modules by name. > I want to invent something like my "programming language" like Python with the same keywords just changed, for example if user type in my "programming language": >>> koristiti os This line of code my program must write in some file, and my program (when it run this user file) must read this line of code like: >>> import os (I just want to change names of keywords) From brucecoram at clara.co.uk Sat Jun 2 04:10:14 2007 From: brucecoram at clara.co.uk (Bruce Coram) Date: Sat, 02 Jun 2007 09:10:14 +0100 Subject: c[:]() In-Reply-To: <6faf39c90706012146l551dfe60o6358f48dd5127505@mail.gmail.com> References: <1180504190.055427.173610@h2g2000hsg.googlegroups.com> <135tv1bjqgbmsc9@corp.supernews.com> <9qudnbFRU9QHJsLbnZ2dnUVZ_rKvnZ2d@speakeasy.net> <005f01c7a471$6f4b8b30$240110ac@Muse> <6faf39c90706012146l551dfe60o6358f48dd5127505@mail.gmail.com> Message-ID: <466125E6.5020202@clara.co.uk> I am a relative newbie to Python and certainly to this mailing list. I have watched this thread with interest. After the first few exchanges I thought it would prove interesting and it has. Warren Stringer is one of two things: A joker having some fun at your expense. An intellectually pretentious person who is so self absorbed that he is mentally incapable of seeing the hollowness of his ideas. Either way it's probably not worth spending any more time on him. All that needs to be said has been. This thread is bare. Exit Bruce Coram > 2007/6/1, Warren Stringer : > > >> I am not insisting on anything. I use ``c[:]()`` as shorthand way of saying >> "c() for c in d where d is a container" >> >> Having c() support containers seems obvious to me. It jibes with duck >> typing. Perhaps the title of this thread should have been: "Why don't >> containers quack?" >> >> A change is surprising only if it breaks something. I still haven't seen any >> code that breaks by making such a change. Seeing such code would teach a >> great deal. >> > > I think it very much bites duck typing. Currently, if I try to execute > a string or a list or whatever, I get: > > TypeError: 'str' object is not callable > > But under your proposed semantics, suppose a is a list with some > executable and some non-executable elements. What should > > a() > > now give? It cannot be a TypeError, because a list (in your semantics) > is callable. Whatever error it gives, and whether or not the preceding > executables are executed first, it will not be an existing error > acting the way it normally does - there is no Python error for "you > cannot do this with this object, but you can do it with other objects > of the same type". And that does not seem to be a case of "We have > never needed it yet" - the join method seems to have been specifically > tailored so that no such error is needed. > > > From harry.g.george at boeing.com Fri Jun 22 01:03:27 2007 From: harry.g.george at boeing.com (Harry George) Date: Fri, 22 Jun 2007 05:03:27 GMT Subject: eggs considered harmful References: <87fy4knb1u.fsf@pobox.com> Message-ID: jjl at pobox.com (John J. Lee) writes: > Harry George writes: > [...] > > These are unacceptable behaviors. I am therefore dropping ZODB3, and > > am considering dropping TurboGears and ZSI. If the egg paradigm > > spreads, yet more packages will be dropped (or will never get a chance > > to compete for addition). > > > > I've asked before, and I'll ask again: If you are doing a Python > > project, please make a self-sufficient tarball available as well. You > > can have dependencies, as long as they are documented and can be > > obtained by separate manual download. > > 1. Given the presumptuous tone of your own message, I guess I'm not in > danger of coming across as more rude than you when I point out that > your requirements are just that: your own. The rest of the world > won't *always* bend over backwards to support just exactly what you'd > most prefer. > You deleted the "...at least here", which was intended to make clear I was NOT speaking for the world at large, though possibly for a large chunk of corporate life. Also, this wasn't out of the lbue. I ha ve previously discussed this with several development teasm privately, but the trend appears to be accelerating > 2. You can run your own private egg repository. IIRC, it's as simple > as a directory of eggs and a plain old web server with directory > listings turned on. You then run easy_install -f URL package_name > instead of easy_install package_name . The distutils-sig archives > will have more on this. Again, not speaking for anyone else: With 500 OSS packages, all of which play by the same tarball rules, we don't have resources to handle eggs differently. > > 3. Alternatively, you could create bundled packages that include > dependencies (perhaps zc.buildout can do that for you, even? not sure) > No resources for special handling. > > John -- Harry George PLM Engineering Architecture From scowell at sbcglobal.net Mon Jun 18 06:46:56 2007 From: scowell at sbcglobal.net (Stephen Cowell) Date: Mon, 18 Jun 2007 10:46:56 GMT Subject: Do U have anything to share with this students References: <1181926856.041008.258770@o11g2000prd.googlegroups.com> <1181999183.047568.44000@m36g2000hse.googlegroups.com> Message-ID: "Josh Hill" wrote in message news:ubt773l1a3blmhh7i77eohlp7c0ia3k343 at 4ax.com... > On Sat, 16 Jun 2007 13:06:23 -0000, Milt > wrote: > >>On Jun 15, 1:00?pm, slvsl... at gmail.com wrote: >>> This is a network of students. Find the people of your kind there >>> >>> http://tinyurl.com/33uvla >>> >>> Click and register to access millions of students. >> >>Your link doesn't work. > > Hope you're protected against malware. Yes, the link probably did what it was supposed to, just not what you thought it would do. Please, folks, don't click tinyurls without knowing the person who made them. __ Steve . From evan at yelp.com Wed Jun 13 04:15:10 2007 From: evan at yelp.com (Evan Klitzke) Date: Wed, 13 Jun 2007 01:15:10 -0700 Subject: How to save python codes in files? In-Reply-To: <1181721972.486523.37680@g37g2000prf.googlegroups.com> References: <1181711063.512249.289520@x35g2000prf.googlegroups.com> <1181721972.486523.37680@g37g2000prf.googlegroups.com> Message-ID: On 6/13/07, why? wrote: > > Evan Klitzke wrote: > > On 6/12/07, why? wrote: > > > Im working with Python 2.2 on my red hat linux system. Is there any > > > way to write python codes in separate files and save them so that i > > > can view/edit them in the future? Actually I've just started with > > > python and would be grateful for a response. Thanx! > > > > Of course -- just put the code into a text file (using your favorite > > text editor) and then run the script using the python command, e.g. by > > executing on a command line: > > python my_program.py > > > > Since you're on a Linux system you can also use this as the first line > > of your file and then chmod +x the file to make it into an executable > > script: > > > > #!/usr/bin/env python > > > > -- > Im still unable to follow... :( > See, if i have to save the following code in a file, how should i > proceed? > >>> def sum(x,y): return x+y > ... > >>> If you want to write a program, you need to have some code that actually does something (rather than just containing definitions of functions). Here's a trivial example of a file using your sum function: #!/usr/bin/env python def sum(x, y): return x+y print 'Enter two numbers:' x = int(raw_input()) y = int(raw_input()) print 'The sum is equal to %s + %s = %s' % (x, y, sum(x,y)) -- Evan Klitzke From showell30 at yahoo.com Mon Jun 4 07:51:50 2007 From: showell30 at yahoo.com (Steve Howell) Date: Mon, 4 Jun 2007 04:51:50 -0700 (PDT) Subject: subexpressions (OT: math) In-Reply-To: Message-ID: <603684.3776.qm@web33512.mail.mud.yahoo.com> --- Peter Otten <__peter__ at web.de> wrote: > > I know not much more about Fourier series than that > they do exist, so let me > refer you to > > http://en.wikipedia.org/wiki/Fourier_series > I'd like to try to bring this thread back full circle (or maybe at least 7*pi/4). 1) OP posted an example of sin(x*x) + cos(x*x). 2) I posted the observation (slight paraphrase of myself) that above formula looks like a high school math mistake. 3) I also asked for geometric interpretation of square root of an arc length, not really expecting one, although eventually somebody posted an interesting physical interpretation (noise density). 4) I also asked about units in general. The general consensus is that radians are dimensionless. 5) Any exploration of trigonometry among smart people eventually leads to Fourier Series expansions. Trying to bring this back to Python, I think Fourier Series make a better example of a situation where you end up repeating subexpressions: lambda t: a[0]/2 + sum(a[n]*cos(n*f*t) + b[n]*sin(n*f*t) \ for n in range(1,101)) ____________________________________________________________________________________ Pinpoint customers who are looking for what you sell. http://searchmarketing.yahoo.com/ From martin at v.loewis.de Mon Jun 4 16:15:04 2007 From: martin at v.loewis.de (=?ISO-8859-15?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Mon, 04 Jun 2007 22:15:04 +0200 Subject: Python 2.5.1 broken os.stat module In-Reply-To: References: <466140A6.1090100@v.loewis.de> <-aOdnbFdroD_gP_bnZ2dnUVZ_uKknZ2d@comcast.com> <4662750b$0$29898$9b622d9e@news.freenet.de> <4662F98C.8070709@v.loewis.de> Message-ID: <466472C8.9020003@v.loewis.de> Joe Salmeri schrieb: > There is a conflict with the answers that you and Terry have given. No, there isn't. See some of my earlier replies: both windows and python are correct, despite the fact they give different results. When Windows renders a time stamp, it always uses the current UTC offset. That is the only way to guarantee that a time stamp uniquely identifies points in time: i.e. two files with the same time stamp where also modified at the same time. OTOH, Python's localtime function tries to apply the UTC offset that was likely in force at the time indicated by the time stamp. I say likely, because it probably doesn't know exactly when DST started in what year (I might be wrong - Python defers to some Microsoft API to perform the conversion). While this apparently better matches what you expect, it also is ambiguous: two files authored at 2:15 a.m. might still be an hour apart, if that is on the day when DST switches to standard time. > The original issue I raised was that I Python 2.5.1 and Windows did not have > the same textual represenation for a localize date. > > You have stood true to the statements that Python 2.5.1 is correct and that > previous versions were wrong. Yes - but not because localtime reported the wrong value, but because stat() didn't report UTC times. > I agree with you that Python 2.5.1 is correct which means that Windows is > showing the incorrect dates. And yet, I claim they are both correct - just different. > Since that point in time you and Terry have disagreed with my statements > regarding timezones and DST. I don't see how. Terry claims the Windows result is correct, and so do I. > From that date up until just before DST starts both Windows AND Python 2.5.1 > will report that date as 01/02/2007 07:00 PM. EST, that is. > Once DST starts Python 2.5.1 will still report that date as 01/02/2007 07:00 > PM, however Windows will now report that > date as 01/02/2007 at 08:00 PM. EDT. 01/02/2007 7:00 PM EST == 01/02/2007 8:00 PM EDT So they print indeed the same output, even though the text is different. > I agree and believe that Python 2.5.1 is reporting the correct textual > representation of that timestamp, however, using > *your* logic that a DST change *is a timezone change* that would mean that > Python 2.5.1 is wrong and should be reporting the > date 1 hour later just as Windows is reporting. No. Python prints the stamp according to the time zone that was in force when the file was created. Of course, it can't be sure (since the computer may have lived in an entirely different time zone at the time), but it assumes that the computer has not moved, and it assumes to know when DST started in 2007 (which it probably does know correctly; I wouldn't be so sure about 1981). > You cannot have it both ways. Sure can. > If a DST change is the same as a timezone change then Python 2.5.1 should be > reporting the dates that Windows reports. You are misunderstanding what localtime() does. > If a DST change is NOT the same as a timezone change then Python 2.5.1 > should be reporting the dates that it currently is. You are misunderstanding that Windows does *not* use localtime(), but windows_localtime(). Both consider the current timezone, but in a different way. Regards, Martin From deets at nospam.web.de Tue Jun 5 08:09:24 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 05 Jun 2007 14:09:24 +0200 Subject: how to convert a bitmap file to an array ? References: Message-ID: <5cl23kF30kuprU1@mid.uni-berlin.de> stef wrote: > hello > > I can find all kind of procedures to convert an array to a bitmap > (wxPython, PIL), > but I can't find the reverse, > either > - convert a bitmap to an array > or > - read a bitmap file to an array Not true for PIL, Image.getdata and Image.putdata are your friends. Diez From bignose+hates-spam at benfinney.id.au Fri Jun 22 04:55:49 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 22 Jun 2007 18:55:49 +1000 Subject: "assert" annoyance References: <7xmyys368j.fsf_-_@ruckus.brouhaha.com> Message-ID: <87y7ictlka.fsf@benfinney.id.au> Paul Rubin writes: > So I have some assert statements in my code to verify the absence of > some "impossible" conditions. They were useful in debugging and of > course I left them in place for "real" runs of the program. Umpteen > hours into a run, an assertion failed, and of course since failure > was "impossible", I didn't catch the exception so the whole program > crashed. This is exactly the sort of check which is best done as unit tests. The program has no 'assert' cruft in it, and the tests can be as comprehensive as needed without having any impact on the actual running program. -- \ Legionnaire: "We have their leader captive!" C?r: "Is he | `\ bound?" Legionnaire: "Of his health I know not, sir." -- The | _o__) Goon Show, _The Histories Of Pliny The Elder_ | Ben Finney From http Tue Jun 26 03:26:14 2007 From: http (Paul Rubin) Date: 26 Jun 2007 00:26:14 -0700 Subject: Python's "only one way to do it" philosophy isn't good? References: <7x3b0nmkk6.fsf@ruckus.brouhaha.com> <1182750077.570603.160240@q69g2000hsb.googlegroups.com> <7xir9cbm0g.fsf@ruckus.brouhaha.com> <7xejjzmk7u.fsf@ruckus.brouhaha.com> Message-ID: <7xy7i7xjl5.fsf@ruckus.brouhaha.com> Douglas Alan writes: > > In the Maclisp era functions like mapcar worked on lists, and > > generated equally long lists in memory. > > I'm aware, but there were various different mapping functions. "map", > as opposed to "mapcar" didn't return any values at all, and so you had > to rely on side effects with it. The thing is there was no standard way in Maclisp to write something like Python's "count" function and map over it. This could be done in Scheme with streams, of course. > Right -- I wrote "iterators", not "generators". Python iterators (the __iter__ methods on classes) are written with yield statements as often as not. > > The point is that mapcar (as the name implies) advances down a list > > using cdr, i.e. it only operates on lists, not general iterators or > > streams or whatever. > > Right, but each sequence type had it's own corresponding mapping fuctions. Precisely, I think that's what Alexander was trying to get across, Lisp didn't have a uniform interface for traversing different types of sequence. > they had standardized such things. This would not be particularly > difficult to do, other than the getting everyone to agree on just what > the interfaces should be. But Lisp programmers, are of course, just > as recalcitrant as Python programmers. Python programmers tend to accept what the language gives them and use it and not try to subvert it too much. I don't say that is good or bad. > And in Python's case, the reference manual is just an incomplete > description of the features offered by the implementation, and people > revel in features that are not yet in the reference manual. No I don't think so, unless you count some things that are in accepted PEP's and therefore can be considered part of the reference docs, even though they haven't yet been merged into the manual. > That's not ugly. The fact that CPython has a reference-counting GC > makes the lifetime of object predictable, which means that like in > C++, and unlike in Java, you can use destructors to good effect. This > is one of the huge boons of C++. The predictability of lifespan makes > the language more expressive and powerful. The move to deprecate > relying on this feature in Python is a bad thing, if you ask me, and > removes one of the advantages that Python had over Lisp. No that's wrong, C++ has no GC at all, reference counting or otherwise, so its destructors only run when the object is manually released or goes out of scope. The compiler normally doesn't attempt lifetime analysis and it would probably be against the rules to free an object as soon as it became inaccessible anyway. Python (as of 2.5) does that using the new "with" statement, which finally makes it possible to escape from that losing GC-dependent idiom. The "with" statement handles most cases that C++ destructors normally handle. Python object lifetimes are in fact NOT predictable because the ref counting doesn't (and can't) pick up cyclic structure. Occasionally a cyclic GC comes along and frees up cyclic garbage, so some destructors don't get run til then. Of course you can manually organize your code so that stuff with destructors don't land in cyclic structures, but now you don't really have automatic GC any more, you have (partially) manual storage management. And the refcounts are a performance pig in multithreaded code, because of how often they have to be incremented and updated. That's why CPython has the notorious GIL (a giant lock around the whole interpreter that stops more than one interpreter thread from being active at a time), because putting locks on the refcounts (someone tried in the late 90's) to allow multi-cpu parallelism slows the interpreter to a crawl. Meanwhile 4-core x86 cpu's are shipping on the desktop, and network servers not dependent on the complex x86 architecture are using 16-core MIPS processors (www.movidis.com). Python is taking a beating all the time because of its inability to use parallel cpu's, and it's only going to get worse unless/until PyPy fixes the situation. And that means serious GC instead of ref counting. > And it's not bygone -- it's just nichified. Lisp is forever -- you'll see. Lisp may always be around in some tiny niche but its use as a large-scale systems development language has stopped making sense. If you want to see something really pathetic, hang out on comp.lang.forth sometime. It's just amazing how unaware the inhabitants there are of how irrelevant their language has become. Lisp isn't that far gone yet, but it's getting more and more like that. From steve at laniels.org Wed Jun 27 19:16:28 2007 From: steve at laniels.org (Stephen R Laniel) Date: Wed, 27 Jun 2007 19:16:28 -0400 Subject: PEP 3107 and stronger typing (note: probably a newbie question) In-Reply-To: <4682eddc$0$23164$426a74cc@news.free.fr> References: <1182369568.941307.316260@p77g2000hsh.googlegroups.com> <5dveb4F360un0U1@mid.individual.net> <467a9209$0$22165$426a74cc@news.free.fr> <1182858785.886469.93060@n60g2000hse.googlegroups.com> <46824d8d$0$2324$426a74cc@news.free.fr> <4682eddc$0$23164$426a74cc@news.free.fr> Message-ID: <20070627231628.GA13272@slaniel-laptop.itasoftware.com> On Thu, Jun 28, 2007 at 09:08:16AM +0200, Bruno Desthuilliers wrote: > You said ? I could link again to Mark-Jason Dominus, who writes that people often make the following inference: 1) C is strongly typed. 2) C's typing sucks. 3) Hence strong typing sucks. But I won't. It doesn't need to be a religious war. Why can't people just say "When strong typing is done and used well, it's a useful tool; when it's not, it's not"? -- Stephen R. Laniel steve at laniels.org Cell: +(617) 308-5571 http://laniels.org/ PGP key: http://laniels.org/slaniel.key From simonkagwe at yahoo.com Thu Jun 7 07:06:54 2007 From: simonkagwe at yahoo.com (simon kagwe) Date: Thu, 7 Jun 2007 11:06:54 +0000 (UTC) Subject: get a list from a string References: <1181213434.814684.236770@q19g2000prn.googlegroups.com> Message-ID: > exec("distances = [[1,1,1,1],[2,2,2,2]]") Wow! So simple! Thanks a lot. :-) From cl4proze at cling.gu.se Thu Jun 21 04:20:54 2007 From: cl4proze at cling.gu.se (Pavel) Date: Thu, 21 Jun 2007 10:20:54 +0200 Subject: Error while installing Python2.5.1 References: <1182413023.924197.302390@o11g2000prd.googlegroups.com> Message-ID: On Thu, 21 Jun 2007 10:03:43 +0200, wrote: > checking for --without-gcc... no > checking for gcc... no > checking for cc... no > checking for cc... no > checking for cl... no > configure: error: no acceptable C compiler found in $PATH > See `config.log' for more details. It appears you have no C compiler installed. You should be able to get one of those from your distribution's repositories. If you can't, upgrade to something debian-based. /pavel From paddy3118 at googlemail.com Wed Jun 20 17:02:33 2007 From: paddy3118 at googlemail.com (Paddy) Date: Wed, 20 Jun 2007 21:02:33 -0000 Subject: PEP 3107 and stronger typing (note: probably a newbie question) In-Reply-To: References: Message-ID: <1182373353.633123.83460@c77g2000hse.googlegroups.com> On Jun 20, 7:53 pm, Stephen R Laniel wrote: > Before I ask anything, let me note that this is surely an > old question that has inspired its share of flame wars; I'm > new to Python, but not new to how Internet discussions work. > So if there's a canonical thread or web page that documents > the whole battle, feel free to point me to it. > > Reading [1], I wonder: why isn't the compiler making better > use of (purely optional) type labeling? Why not make a compiler > directive so that > > a) it will check the types of all my arguments and return > values, and maybe even > b) do some type inference up the call stack? > > E.g., > > def( Class1 arg1, Class2 arg2, ..., ClassN argN ): > someStuff() > > would check the types of the arguments, whereas > > def( arg1, arg2, ..., argN): > someStuff() > > would not? I.e., if I *want* strong static > type-checking, why shouldn't I be able to get it? Is it that > allowing this as a compile-time option would mess up too > many knobs to make it optional? > > Again, probably an old debate. I'd like to know why Guido's > decided that not only is strong static typing > productivity-reducing [2], but that it should be *forbidden*. > > [1] -http://www.python.org/dev/peps/pep-3107/ > [2] -http://www.artima.com/intv/strongweakP.html > > -- > Stephen R. Laniel > s... at laniels.org > Cell: +(617) 308-5571http://laniels.org/ > PGP key:http://laniels.org/slaniel.key have you seen language Boo? It adds static typing to Python inspired syntax: http://boo.codehaus.org/ - Paddy. From borud-news at borud.no Fri Jun 22 12:16:20 2007 From: borud-news at borud.no (Bjorn Borud) Date: 22 Jun 2007 18:16:20 +0200 Subject: The Modernization of Emacs References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182370894.001918.36590@k79g2000hse.googlegroups.com> <1182372821.298343.316860@g4g2000hsf.googlegroups.com> <1182375321.067664.190780@o61g2000hsh.googlegroups.com> <86hcp1l6hb.fsf@lola.quinscape.zz> Message-ID: [David Kastrup ] | | The idea is to start Emacs once and use it for everything. ...which is fine as long as you are only fiddling around on one machine or you have emacs windows running on all your machines. for my main use, I do start Emacs just once though. for instance at work my Emacs has been running for as long as the machine has been up. | > so if the context was system administration, I'd vote for vi as | > well. if the context was programming I'd vote Emacs. | | You know you can use something like | C-x C-f /su::/etc/fstab RET | (or /sudo::/etc/fstab) in order to edit files as root in a normal | Emacs session? sure, but often it is just simpler, while you are fiddling around in a shell, to just fire up vi to do some quick editing than to bounce back and forth between windows. it is usually quicker too if you have to navigate deep directory trees -- if you're already in the directory where the file is, it'd be fewer keystrokes to specify the file than opening it in emacs. even with tab-completion. also, I make extensive use of the readline and history features when fiddling about in the shell. shells have a lot of context if you use them effectively. context that isn't easy to transport between the shell and emacs -- and it isn't really easy to explain either. -Bj?rn From http Wed Jun 27 22:57:20 2007 From: http (Paul Rubin) Date: 27 Jun 2007 19:57:20 -0700 Subject: 16bit hash References: Message-ID: <7xodj0n5v3.fsf@ruckus.brouhaha.com> Robin Becker writes: > >> Is the any way to get an efficient 16bit hash in python? > > hash(obj)&65535 > > - Josiah > yes I thought of that, but cannot figure out if the internal hash > really distributes the bits evenly. Particularly since it seems to > treat integers etc as special cases The built-in hash function doesn't attempt even distribution, it tries to make sure that inputs with small differences hash to distinct values. If you want something really near-random, try import sha hash = int(sha.new(repr(obj)).hexdigest()[:4], 16) It won't be super-fast but hey, you're using Python. From kjellmf at gmail.com Wed Jun 27 01:37:25 2007 From: kjellmf at gmail.com (Kjell Magne Fauske) Date: Wed, 27 Jun 2007 05:37:25 -0000 Subject: ANN: YahooQuote 0.1.0 In-Reply-To: <4681ad7f$1@news.unimelb.edu.au> References: <467f9e21$1@news.orcon.net.nz><4681ad7f$1@news.unimelb.edu.au> Message-ID: <1182922645.514309.32910@c77g2000hse.googlegroups.com> On Jun 27, 2:21 am, Maurice LING wrote: > Hi David, > > I can't download from your linkhttp://www.freenet.org.nz/python/yahooquote/YahooQuote-0.1.tar.gz > > Cheers > maurice > The correct download link seems to be: http://www.freenet.org.nz/python/yahooquote/YahooQuote-0.1.0.tar.gz - Kjell Magne Fauske From bruno.42.desthuilliers at wtf.websiteburo.oops.com Thu Jun 28 11:26:35 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Thu, 28 Jun 2007 17:26:35 +0200 Subject: problem with hack using multiple inheritance for plugins In-Reply-To: <1183033834.301669.7220@g4g2000hsf.googlegroups.com> References: <1183026288.857294.91620@q69g2000hsb.googlegroups.com> <1183028051.940679.145680@q69g2000hsb.googlegroups.com> <46839f4c$0$22380$426a74cc@news.free.fr> <1183033834.301669.7220@g4g2000hsf.googlegroups.com> Message-ID: <4683d317$0$26080$426a74cc@news.free.fr> massimo s. a ?crit : > On 28 Giu, 13:45, Bruno Desthuilliers 42.desthuilli... at wtf.websiteburo.oops.com> wrote: >> >> wrt/ this snippet: >> >> for plugin_name in self.config['plugins']: >> try: >> plugin=__import__(plugin_name) >> try: >> print type(self) >> eval('plugin.'+plugin_name+'Commands._plug_init(self)') >> except AttributeError: >> pass >> except ImportError: >> pass >> >> You may want to try this instead: >> >> for plugin_name in self.config['plugins']: >> try: >> plugin=__import__(plugin_name) >> except ImportError: >> # eventually do something like logging the error ? >> continue >> try: >> cmdplug = getattr(plugin, plugin_name+'Commands') >> cmdplug._plug_init(self) >> except AttributeError: >> # eventually do something like logging the error ? >> continue > > Tried, same error as before :( > Sorry, I failed to make clear that this was not suppoed to solve your current problem - just to avoid using eval() when not necessary. From aleax at mac.com Tue Jun 19 11:04:19 2007 From: aleax at mac.com (Alex Martelli) Date: Tue, 19 Jun 2007 08:04:19 -0700 Subject: Python IDE References: <1182249585.535675.143460@m36g2000hse.googlegroups.com> Message-ID: <1hzy3n1.1x9zi0m12zot0qN%aleax@mac.com> Tom Gur wrote: > which IDE would you recommend for a python ? It depends on that python's tastes and preferences. Like many others who have already responded, I prefer an editor (VIM) and a separate commandline/terminal; I know of many others who share another responder's preference for Eclipse+PythonDev; other options that should be mentioned include IDLE, Wing, eric4, Microsoft Visual Studio (Windows-only), Apple's XCode (Mac-only), ... Alex From showell30 at yahoo.com Wed Jun 20 09:26:14 2007 From: showell30 at yahoo.com (Steve Howell) Date: Wed, 20 Jun 2007 06:26:14 -0700 (PDT) Subject: SimplePrograms challenge In-Reply-To: Message-ID: <489118.40808.qm@web33511.mail.mud.yahoo.com> --- Pete Forman wrote: > Steve Howell writes: > > >> 2) assert is not the simplest example of doctest. > > >> The style should be > >> > >> >>> add_money([0.13, 0.02]) > >> 0.15 > >> >>> add_money([100.01, 99.99]) > >> 200.0 > >> >>> add_money([0, -13.00, 13.00]) > >> 0.0 > >> > > > > That's not clear cut to me. I think vertical > > conciseness has an advantage for readability, as > it > > means you get to keep more "real" code on the > screen. > > What I meant was that doctest should be "type this > into the > interpreter and you should see that". A doctest is > not a unit test, > though it may form a subset of the tests. There > should only be enough > doctests to enclue a human reader. Comprehensive > testing should use a > larger framework. Doctests in separate files can do > this but I would > use py.test, or alternatives like nose or Testoob. > > >>> 2 + 2 > 4 > > "assert 2 + 2 == 4" is a concise way of writing a > unit test but it is > not the best way to use doctest IMHO. > > >> 3) which fails :-( So both the unittest and > doctest > >> examples ought to > >> be redone to emphasize what they are doing > >> without getting bogged > >> down by issues of floating point > representations. > >> > > > > I was the one who originally posted the floating > point > > example (with yet another style of unit testing, > BTW), > > and I agree that the subtleties of floating point > do > > kind of cloud the issue. I welcome a better > example. > > What I didn't realize is that there's an actual > error. > > Are you saying the program fails? On which > test? > > Python 2.5.1 on XP: > > Failed example: > add_money([0.13, 0.02]) > Expected: > 0.15 > Got: > 0.14999999999999999 > > Ok, you make a lot of good points. I was the original author of the page, so I'll make a few points. 1) Your attention to detail is greatly appreciated. At the very least, I don't want the examples to be broken. I tested the above on Unix 2.5, and they worked, but it was obviously just luck, as the implementation is clearly broken. (Actually, it's not so much the implementation--it's the interface, which should just return pennies.) 2) Both the unittest and doctest examples are probably broken. 3) I'd like for unittest and doctest example to show up somewhere on the page, but perhaps they merit longer examples. 4) I don't use doctest myself. It never hit my sweet spot, mostly because I prefer external unit tests. So I'm not the best person to judge the most idiomatic way to write them. 5) My biggest goal for the page is that examples are simple and mostly uncontroversial. 6) It was pointed out when I originally wrote this example that the solution to money rounding is, of course, to use a Decimal data type. 7) Feel free to change the page as you see fit, although thanks for discussing it here first. ____________________________________________________________________________________ It's here! Your new message! Get new email alerts with the free Yahoo! Toolbar. http://tools.search.yahoo.com/toolbar/features/mail/ From wolf_tracks at invalid.com Wed Jun 6 22:45:23 2007 From: wolf_tracks at invalid.com (W. Watson) Date: Thu, 07 Jun 2007 02:45:23 GMT Subject: Need a Little Help on Tkinter and Python In-Reply-To: References: <4666b2f8$0$23408$5402220f@news.sunrise.ch> Message-ID: <7jK9i.13016$5j1.10685@newssvr21.news.prodigy.net> Is there a pdf file or downloadable file of the Tkinter material? I like to put stuff in notebooks. W. Watson wrote: > Thanks for your responses. I've located the URL from the post above and > will check out the two books mentioned here. I used to do a lot of > scientific programming, but now just concentrate on science. > > Martin Blume wrote: >> "W. Watson" schrieb >>> I have about a 1600 line Pythron program I'd like to make some simple >>> mods to, but have really just a nodding acquaintance with Python and >>> Tkinter. [...] >>> Let's change that. >> >> The book "Learning Python" from O'Reilly is excellent. >> If you are into scientific programming, the book >> "Python Scripting for Computational Science" >> by Hans Petter Langtangen from Springer is useful. >> >> HTH >> Martin >> >> >> > -- Wayne Watson (Nevada City, CA) Web Page: From grante at visi.com Mon Jun 18 10:40:18 2007 From: grante at visi.com (Grant Edwards) Date: Mon, 18 Jun 2007 14:40:18 -0000 Subject: Binary code References: <1182175391.840851.123150@p77g2000hsh.googlegroups.com> Message-ID: <137d6aip8ggg826@corp.supernews.com> On 2007-06-18, getgroup wrote: > Can python maky a binary code for exemple .hex for microcontrolor. Are you asking if a Python program can be compiled into a binary executable which is to run on a microcontroller? The answer to that is no. Are you asking if a Python program can be written that will create a .hex file given a set of input data? The answer to that is yes. -- Grant Edwards grante Yow! Why are these athletic at shoe salesmen following visi.com me?? From fukazawa at gmail.com Wed Jun 27 03:20:52 2007 From: fukazawa at gmail.com (Andy) Date: Wed, 27 Jun 2007 07:20:52 -0000 Subject: String formatting for complex writing systems Message-ID: <1182928852.730131.323210@a26g2000pre.googlegroups.com> Hi guys, I'm writing a piece of software for some Thai friend. At the end it is supposed to print on paper some report with tables of text and numbers. When I test it in English, the columns are aligned nicely, but when he tests it with Thai data, the columns are all crooked. The problem here is that in the Thai writing system some times two or more characters together might take one single space, for example ?? (u"\u0E07\u0E34"). This is why when I use something like u"%10s" % ..., it just doesn't work as expected. Is anybody aware of an alternative string format function that can deal with this kind of writing properly? Any suggestion is highly appreciated. Thanks! Andy From mhl1983 at gmail.com Thu Jun 21 04:59:06 2007 From: mhl1983 at gmail.com (MaHL) Date: Thu, 21 Jun 2007 08:59:06 -0000 Subject: Can python access windows clipboard Message-ID: <1182416346.377857.103540@z28g2000prd.googlegroups.com> Can I use python to copy something(like a string) to the clipboard, so that I can paste it somewhere else. Is there a way to do this? Thanks very much! From borud-news at borud.no Wed Jun 20 07:48:20 2007 From: borud-news at borud.no (Bjorn Borud) Date: 20 Jun 2007 13:48:20 +0200 Subject: The Modernization of Emacs References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> Message-ID: [Xah Lee ] | | ---------------------------------------- | SIMPLE CHANGES if I were to suggest improvements to Emacs, the things you mention are probably among the last things I'd even consider. the problem with Emacs is not really the nomenclature or the keybindings. the problem is that it needs to do what it already does better. My frustration with Emacs has mostly been that Emacs-Lisp is a bit too limiting. It is too slow and the codebase is a bit messy. or at least it was the last time I tried to do something in Emacs-Lisp a couple of years ago. it would also be beneficial if there was a more proper and well-organized standard library for Emacs to make developing Emacs applications easier. for programmers, Emacs is a pretty good editor already, but there is a bit of a threshold for extending Emacs. -Bj?rn From steve at holdenweb.com Tue Jun 5 08:06:48 2007 From: steve at holdenweb.com (Steve Holden) Date: Tue, 05 Jun 2007 08:06:48 -0400 Subject: c[:]() In-Reply-To: <003901c7a546$679a55d0$240110ac@Muse> References: <1180504190.055427.173610@h2g2000hsg.googlegroups.com><135tv1bjqgbmsc9@corp.supernews.com> <9qudnbFRU9QHJsLbnZ2dnUVZ_rKvnZ2d@speakeasy.net><005f01c7a471$6f4b8b30$240110ac@Muse><6faf39c90706012146l551dfe60o6358f48dd5127505@mail.gmail.com> <003701c7a543$57b09290$240110ac@Muse> <003901c7a546$679a55d0$240110ac@Muse> Message-ID: Warren Stringer wrote: > Oops, forgot to cut and paste the point, to this: > >>> - there is no Python error for "you >>> cannot do this with this object, but you can do it with other objects >>> of the same type". >> Yes there is: >> >> #------------------------ >> def yo(): print "yo" >> def no(): print blah >> yo() >> no() >> >> Starting Python debug run ... >> yo >> Traceback (most recent call last):... >> NameError: global name 'blah' is not defined >> #------------------------ > > The point is that if the object is ill formed, then you get a traceback > regardless. > > But, as this is an addendum to the other post, please read that first. > > Now, I really am out of here. > Say, who *was* that masked man? ... regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From attn.steven.kuo at gmail.com Tue Jun 26 00:11:58 2007 From: attn.steven.kuo at gmail.com (attn.steven.kuo at gmail.com) Date: Mon, 25 Jun 2007 21:11:58 -0700 Subject: regular expressions eliminating filenames of type foo.thumbnail.jpg In-Reply-To: <1182807664.730854.28160@g37g2000prf.googlegroups.com> References: <1182746933.413693.103860@p77g2000hsh.googlegroups.com> <1182747645.092002.68800@x35g2000prf.googlegroups.com> <1182750220.486035.298890@o11g2000prd.googlegroups.com> <1182807664.730854.28160@g37g2000prf.googlegroups.com> Message-ID: <1182831118.983825.289070@j4g2000prf.googlegroups.com> On Jun 25, 2:41 pm, oscartheduck wrote: > I eventually went with: > > #!/usr/bin/env python > from PIL import Image > import glob, os, re > > size = 128, 128 > > def thumbnailer(dir, filenameRx): > for picture in [ p for p in os.listdir(dir) if > os.path.isfile(os.path.join( > dir,p)) and filenameRx.match(p) if 'thumbnail' not in p]: > file, ext = os.path.splitext(picture) (snipped) Or, one can forego regular expressions: prefix = '.thumbnail' for p in os.listdir(dir): root, ext = os.path.splitext(p) if not os.path.isfile(os.path.join(dir, p)) \ or ext.lower() not in ('.jpg', '.jpeg') \ or root[-10:].lower() == prefix: continue if os.path.isfile(os.path.join(dir, "%s%s%s" % (root, prefix, ext))): print "A thumbnail of %s already exists" % p else: print "Making a thumbnail of %s" % os.path.join(dir, "%s%s%s" % (root, prefix, ext)) -- Hope this helps, Steven From Maria.Reinhammar at accalon.com Tue Jun 5 05:01:29 2007 From: Maria.Reinhammar at accalon.com (Maria R) Date: Tue, 05 Jun 2007 02:01:29 -0700 Subject: Who uses Python? In-Reply-To: <1181028719.829671.22230@a26g2000pre.googlegroups.com> References: <1180985830.288414.208850@q69g2000hsb.googlegroups.com> <1181028719.829671.22230@a26g2000pre.googlegroups.com> Message-ID: <1181034089.239173.282900@g4g2000hsf.googlegroups.com> I tend to agree with some earlier poster that if you use Python you are, in a sense, a programmer :o) But seriously, we use Python for controlling fully automated logistics solutions (conveyors and stacker cranes), for generating PLC code etc etc. We are also about to start using FactoryCAD (a thingy from UGS to run on top af AutoCAD) in which we have "intelligent" objects. These objects have action code and FactoryCAD contains an embedded Python interpreter. Our mech engineers thus write (although a bit simple but still..) Python to make things work :o) We further have generators of mechanical assemblies in SolidEdge. We use a rule based approach and both the configuration files and the rule base are in Python. Our Mech engineers maintain that too. My two cent.. From kairosenthal at tiscali.de Tue Jun 19 07:17:10 2007 From: kairosenthal at tiscali.de (Kai Rosenthal) Date: Tue, 19 Jun 2007 04:17:10 -0700 Subject: determine 32 or 64 bit architecture with python 2.2 Message-ID: <1182251830.835902.78210@n2g2000hse.googlegroups.com> Hello, how can I determine the architecture (32 or 64bit) with python 2.2 on Windows or Unix (AIX, Solaris) OS, without the modul platform? Thanks for your hints, Kai From fred at adventistcare.org Thu Jun 28 15:13:55 2007 From: fred at adventistcare.org (Sells, Fred) Date: Thu, 28 Jun 2007 15:13:55 -0400 Subject: Evolution of a pythonistas! Message-ID: this one is fun: http://www.vpython.org/ > -----Original Message----- > From: python-list-bounces+frsells=adventistcare.org at python.org > [mailto:python-list-bounces+frsells=adventistcare.org at python.org]On > Behalf Of swordofrue > Sent: Thursday, June 28, 2007 1:50 PM > To: python-list at python.org > Subject: Re: Evolution of a pythonistas! > > > Thanks everyone for your responses. I am really loving this. Installed > Pygame and playing some of those games. It just amazes me how much > effort some of these games take. I am reading the source and am just > amazed by the effort and organizational ability of the authors. > Perhaps one day I will such mad skills :) > > -- > http://mail.python.org/mailman/listinfo/python-list > From gagsl-py2 at yahoo.com.ar Sun Jun 17 00:09:50 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 17 Jun 2007 01:09:50 -0300 Subject: Is there a way to hook into module destruction? References: Message-ID: En Sat, 16 Jun 2007 17:16:10 -0300, Neal Becker escribi?: > Code at global scope in a module is run at module construction (init). > Is > it possible to hook into module destruction (unloading)? No exactly, but you could try the atexit module. -- Gabriel Genellina From software at ginstrom.com Fri Jun 8 21:27:02 2007 From: software at ginstrom.com (Ryan Ginstrom) Date: Sat, 9 Jun 2007 10:27:02 +0900 Subject: Obtaining hte currently running script under windows In-Reply-To: Message-ID: <20070609012701528.GGKQ.13519.emta104.odn.ne.jp@mta104.odn.ne.jp> > On Behalf Of Sean Farrow > Is there any way to obtain the full path to the currently > running script under win32? > I am using the pythonw.exe file is that helps. > Sean. Current working directory is not always reliable. There is a __file__ variable set if python.exe runs your script. import os import sys module_name = os.path.dirname(unicode(__file__, sys.getfilesystemencoding( ))) If your script is frozen via py2exe, you can use the sys.executable value to get the module directory. import os import sys module_name = os.path.dirname(unicode(sys.executable, sys.getfilesystemencoding( ))) (You need the Unicode stuff if your path may include non-ASCII characters) function module_path() in the alternate solution at http://www.py2exe.org/index.cgi/WhereAmI will give you the module (script/executable) directory whether your script is running normally or frozen. Regards, Ryan -- Ryan Ginstrom translation at ginstrom.com http://ginstrom.com/ From twisted0n3 at gmail.com Wed Jun 20 17:11:59 2007 From: twisted0n3 at gmail.com (Twisted) Date: Wed, 20 Jun 2007 21:11:59 -0000 Subject: The Modernization of Emacs: terminology buffer and keybinding In-Reply-To: <1182372592.803332.288260@u2g2000hsc.googlegroups.com> References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182272495.990807.99110@a26g2000pre.googlegroups.com> <87tzt3ihev.fsf@kobe.laptop> <1182370216.961241.6960@n60g2000hse.googlegroups.com> <85zm2ufjpb.fsf@lola.goethe.zz> <1182372592.803332.288260@u2g2000hsc.googlegroups.com> Message-ID: <1182373919.262388.100740@c77g2000hse.googlegroups.com> On Jun 20, 4:49 pm, Twisted wrote: > On Jun 20, 4:35 pm, David Kastrup wrote: > > Twisted writes: > > > I continue to suspect that there's an ulterior motive for making and > > > keeping certain software actively beginner-hostile; a certain macho > > > elitism also seen with light aircraft pilots and commented on at > > >www.asktog.com(exactURL escapes me; sorry). > > > You are babbling. > > No, I am not. You, however, are being gratuitously insulting. I have that exact URL now -- http://www.asktog.com/columns/027InterfacesThatKill.html The most relevant section is towards the bottom of the page. Curiously, you can jump right to it with a text-find of the word "girls". From Eric_Dexter at msn.com Wed Jun 20 21:28:06 2007 From: Eric_Dexter at msn.com (Eric_Dexter at msn.com) Date: Wed, 20 Jun 2007 18:28:06 -0700 Subject: subprocess.popen question In-Reply-To: References: <1182353267.200998.43900@w5g2000hsg.googlegroups.com> <1182380572.235876.113160@n2g2000hse.googlegroups.com> Message-ID: <1182389286.706352.64780@o61g2000hsh.googlegroups.com> On Jun 20, 7:50 pm, "Gabriel Genellina" wrote: > En Wed, 20 Jun 2007 20:02:52 -0300, Eric_Dex... at msn.com > escribi?: > > > > > > > On Jun 20, 1:46 pm, "Gabriel Genellina" > > wrote: > > >> cmd = ["gawk", "-f", "altertime.awk", "-v", "time_offset=4", "-v", > >> "outfile=testdat.sco", "i1.sco"] > >> Now, what do you want to do with the output? Printing it line by line? > >> output = subprocess.Popen(cmd, stdout=subprocess.PIPE).communicate()[0] > >> lines = output.splitlines() > >> for line in lines: > >> print line > > > C:\dex_tracker\pipe1.py > > Traceback (most recent call last): > > File "C:\dex_tracker\pipe1.py", line 14, in > > last_line = subprocess.Popen([cmd], > > stdout=subprocess.PIPE).communicate()[0] > > File "C:\Python25\lib\subprocess.py", line 593, in __init__ > > errread, errwrite) > > File "C:\Python25\lib\subprocess.py", line 793, in _execute_child > > startupinfo) > > WindowsError: [Error 2] The system cannot find the file specified > > Script terminated. > > > I can write it out as a batch file and then run it but that is a messy > > hack.. > > If cmd is a list of arguments, like the example above, you should use > subprocess.Popen(cmd,...) (like the example above, too). > > -- > Gabriel Genellina- Hide quoted text - > > - Show quoted text - I had cut and pasted the example in to get that error... could it be a problem with ms windows??? (I am at a library computer befour work so that ended my testing) From stuart.tett at gmail.com Mon Jun 18 00:45:38 2007 From: stuart.tett at gmail.com (stuart.tett at gmail.com) Date: Mon, 18 Jun 2007 04:45:38 -0000 Subject: PyRun_String with Py_single_input to stdout? Message-ID: <1182141938.747032.122260@p77g2000hsh.googlegroups.com> I'm using PyRun_String with Py_single_input for a python interpreter embedded in my application. I'm using Py_single_input. Py_single input is what I want, but it seems to output to stdout. Before when I was using Py_eval_input I was able to grab the result so I could print it in a text box: PyObject *resultObject = PyObject_Str( rstring ); if( resultObject != NULL ) { char *string = PyString_AsString( resultObject ); } But Py_eval_input is only for isolated evaluation, not what I want. Py_single_input gives "None" for the string. I wrote a class that redirects std::cout, but this doesn't work for this, I'm guessing because it uses printf to stdout, not cout. Anyone know how I can get the string so I can print it in a text box. From steve at holdenweb.com Thu Jun 28 21:10:03 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 28 Jun 2007 21:10:03 -0400 Subject: equality & comparison by default (was Re: Too many 'self' in python.That's a big flaw in this language.) In-Reply-To: References: <1182942154.185461.89620@e9g2000prf.googlegroups.com> <1i0cy8z.z94q5d1dxgexxN%aleax@mac.com> Message-ID: A.T.Hofkamp wrote: > On 2007-06-28, Alan Isaac wrote: >> A.T.Hofkamp wrote: >> >>>>>> a = Car2(123) >>>>>> b = Car2(123) >>>>>> a == b >>> True >>> >>>>>> set([a,b]) >>> set([Car2(123), Car2(123)]) >>> >>> I get a set with two equal cars, something that never happens with a set >>> my math teacher once told me. >> >> Then your math teacher misspoke. >> You have two different cars in the set, >> just as expected. Use `is`. >> http://docs.python.org/ref/comparisons.html >> >> This is good behavior. > > Hmm, maybe numbers in sets are broken then? > >>>> a = 12345 >>>> b = 12345 >>>> a == b > True >>>> a is b > False >>>> set([a,b]) > set([12345]) > > > Numbers and my Car2 objects behave the same w.r.t. '==' and 'is', yet I get a > set with 1 number, and a set with 2 cars. > Something is wrong here imho. > > The point I intended to make was that having a default __hash__ method on > objects give weird results that not everybody may be aware of. > In addition, to get useful behavior of objects in sets one should override > __hash__ anyway, so what is the point of having a default object.__hash__ ? > > The "one should override __hash__ anyway" argument is being discussed in my > previous post. Hmm, I suspect you'll like this even less: >>> set((1.0, 1, 1+0j)) set([1.0]) Just the same there are sound reasons for it, so I'd prefer to see you using "counterintuitive" or "difficult to fathom" rather than "broken" and "wrong". Such language implies you have thought about this more deeply than the developers (which I frankly doubt) and that they made an inappropriate decision (which is less unlikely, but which in the case you mention I also rather doubt). regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Thu Jun 28 08:42:02 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Thu, 28 Jun 2007 14:42:02 +0200 Subject: PEP 3107 and stronger typing (note: probably a newbie question) References: <1182369568.941307.316260@p77g2000hsh.googlegroups.com> <5dveb4F360un0U1@mid.individual.net> <467a9209$0$22165$426a74cc@news.free.fr> <1182858785.886469.93060@n60g2000hse.googlegroups.com> <46824d8d$0$2324$426a74cc@news.free.fr> <4682eddc$0$23164$426a74cc@news.free.fr> Message-ID: <5ehokpF38ov3jU2@mid.individual.net> Bruno Desthuilliers wrote: > John Nagle a ?crit : >> Actually, static typing is for detecting errors before the >> program is run. > > bruno at bibi ~ $ gcc -ototo toto.c > bruno at bibi ~ $ ./toto > Erreur de segmentation > bruno at bibi ~ $ > > You said ? Did he say that static typing detects all errors? Regards, Bj?rn -- BOFH excuse #198: Post-it Note Sludge leaked into the monitor. From dwahler at gmail.com Sat Jun 2 06:55:27 2007 From: dwahler at gmail.com (David Wahler) Date: Sat, 02 Jun 2007 03:55:27 -0700 Subject: Observer-Pattern by (simple) decorator In-Reply-To: References: Message-ID: <1180781727.519949.172580@q75g2000hsh.googlegroups.com> On Jun 2, 12:27 am, Steven Bethard wrote: > I think you want to define __get__ on your Observable class so that it > can do the right thing when the method is bound to the instance: > > >>> class Observable(object): > ... def __init__(self, func, instance=None, observers=None): > ... if observers is None: > ... observers = [] > ... self.func = func > ... self.instance = instance > ... self.observers = observers > ... def __get__(self, obj, cls=None): > ... if obj is None: > ... return self > ... else: > ... func = self.func.__get__(obj, cls) > ... return Observable(func, obj, self.observers) > ... def __call__(self, *args, **kwargs): > ... result = self.func(*args, **kwargs) > ... for observer in self.observers: > ... observer(self.instance) > ... return result > ... def add_callback(self, callback): > ... self.observers.append(callback) > ... > >>> class SomeActor(object): > ... @Observable > ... def meth(self, foo): > ... print foo > ... > >>> def callback(instance): > ... print "Yippie, I've been called on", instance > ... instance.bar = True > ... Is this desired behavior? >>> a = SomeActor() >>> b = SomeActor() >>> a.meth.observers is b.meth.observers True >>> a.meth.add_callback(callback) >>> b.meth(42) 42 Yippie, I've been called on <__main__.SomeActor object at 0x00C23550> -- David From gagsl-py2 at yahoo.com.ar Wed Jun 13 21:48:22 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 13 Jun 2007 22:48:22 -0300 Subject: save class References: <1181784016.454693.42340@o11g2000prd.googlegroups.com> Message-ID: En Wed, 13 Jun 2007 22:20:16 -0300, nik escribi?: > I would like to create a class and then save it for re-use later. I > have tried to use pickle, but am not sure if that is right. I am > sorry, but I am new to python. Do you want to save the *source*code* of your class, or do you want to save created *instances* -objects- of your classes to retrieve them later (like a database)? > Basically, I have a class, Map. I want to be able to create new maps: > MapA, MapB... that have Map as the base class. > > start with- > class Map: > pass > > and then get a different class > > class MapA(Map): > pass > > that can be saved in a .py file for re-use You just create the .py file with any text editor, containing the source code for all your classes. > so far I thought that - > cls = new.classobj('MapA', (Map, ), {}) > file = open('somefile', mode='w') > pickle.dump(cls, file) > > -might work, but it didn't.... can anybody point me in the right > direction? I know that classes must get saved from the interactive > console, so I would think that it would be a standard thing to do. This would try to save the *class* definition, which is usually not required because they reside on your source files. If this is actually what you really want to do, try to explain us exactly why do you think so. Chances are that there is another solution for this. -- Gabriel Genellina From edreamleo at charter.net Sat Jun 23 19:44:31 2007 From: edreamleo at charter.net (Edward K Ream) Date: Sat, 23 Jun 2007 18:44:31 -0500 Subject: Leo 4.4.3 beta 3 released Message-ID: Leo 4.4.3 beta 3 is available at: http://sourceforge.net/project/showfiles.php?group_id=3458&package_id=29106 This release fixes all known bugs and adds several new features. Leo is a text editor, data organizer, project manager and much more. See: http://webpages.charter.net/edreamleo/intro.html The highlights of Leo 4.4.3: ---------------------------- - Added support for chapters in Leo's core. - Added support for zipped .leo files. - Added a leoBridge module that allows full access to all of Leo's capabilities from programs running outside of Leo. - Removed all gui-dependent code from Leo's core. - Better support for the winpdb debugger. - Added support for @enabled-plugins nodes in settings files. - Added support for @open-with nodes in settings files. - Added support for @bool write_strips_blank_lines setting. - The__wx_gui plugin is now functional. - Leo can use aspell on Linux when using Python 2.5 or later. - @test nodes can now be run from any .leo file. - Many minor improvements, new settings, commands and bug fixes. Links: ------ Leo: http://webpages.charter.net/edreamleo/front.html Home: http://sourceforge.net/projects/leo/ Download: http://sourceforge.net/project/showfiles.php?group_id=3458 CVS: http://leo.tigris.org/source/browse/leo/ Quotes: http://webpages.charter.net/edreamleo/testimonials.html -------------------------------------------------------------------- Edward K. Ream email: edreamleo at charter.net Leo: http://webpages.charter.net/edreamleo/front.html -------------------------------------------------------------------- From jmh at physics.ucdavis.edu Sun Jun 24 23:15:37 2007 From: jmh at physics.ucdavis.edu (Michael Hannon) Date: Sun, 24 Jun 2007 20:15:37 -0700 Subject: Python-based event calendar? Message-ID: <20070625031537.GA11888@physics.ucdavis.edu> Greetings. One of the research groups here has been using a PHP application on one of their own computers to publish their list of seminars: http://www.k5n.us/webcalendar.php They're now asking us to support this on our department web server (the guy that set it up is leaving the group). I've looked at the product, and it seems to work well enough, but I'd prefer to have something equivalent that was based on Python. I have the impression that there is something similar available for Zope/Plone, but that seems too big a hammer for this particular problem. Is there some other Python-based event calendar that doesn't require such a heavy-weight framework? Thanks. - Mike -- Michael Hannon mailto:hannon at physics.ucdavis.edu Dept. of Physics 530.752.4966 University of California 530.752.4717 FAX Davis, CA 95616-8677 From bohnenkamp at mevisbreastcare.de Thu Jun 21 03:57:37 2007 From: bohnenkamp at mevisbreastcare.de (Sascha Bohnenkamp) Date: Thu, 21 Jun 2007 09:57:37 +0200 Subject: The Modernization of Emacs In-Reply-To: <2jpok4-ajt.ln1@zoogz.gregorie.org> References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182344981.372713.298580@w5g2000hsg.googlegroups.com> <1182370884.853838.321440@c77g2000hse.googlegroups.com> <2jpok4-ajt.ln1@zoogz.gregorie.org> Message-ID: <5dupbhF35nekiU2@mid.individual.net> > Windows text editors are not normal: most are devoid of all but the most > primitive functions and are further hampered by having an interface that > required frequent time wasting hand transfers from keyboard to mouse > because, if they provide keyboard equivalents at all, these are > remarkably unmemorable and/or undocumented. well ultra-edit, textpad, source-insight etc. pp are better than that (and run on windows) From deets at nospam.web.de Sun Jun 10 08:13:22 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 10 Jun 2007 14:13:22 +0200 Subject: How can I obtain the exception object on a generlized except statement? In-Reply-To: <1181476163.064695.30410@r19g2000prf.googlegroups.com> References: <1181476163.064695.30410@r19g2000prf.googlegroups.com> Message-ID: <5d287bF32u0ciU2@mid.uni-berlin.de> Chris Allen schrieb: > I am confused on one aspect of exception handling. If you specify the > exception object type to match in an except statement it is possible > to also obtain the exception object itself, but I can't figure out how > to get the exception object when I don't specify a match. > > for example: > >>>> try: urlopen('http://www.google.com') >>>> except socket.error, msg: >>>> print str(msg) > > this works and I can do what I like with the exception object (msg). > but I can't do this with a simple except statment. > >>>> except msg: > > this won't work because it will think msg is the type to match > >>>> except ,msg: > > syntax error > >>>> except *,msg: > > syntax error > >>>> except (),msg: > > Hmm I didn't try that one before I started this post. It doesn't give > me a syntax error. I'll experiment. > Even if the above syntax works, is this the way to do this? It seems > sort of funky. > > How do I do this? Thanks. pydoc sys.exc_info Diez From mail at timgolden.me.uk Sun Jun 3 15:29:50 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Sun, 03 Jun 2007 20:29:50 +0100 Subject: monitoring the filesystem for changes In-Reply-To: <1180896861.674525.296550@o11g2000prd.googlegroups.com> References: <1180796900.356829.31050@i13g2000prf.googlegroups.com> <1180839676.119233.199860@x35g2000prf.googlegroups.com> <1180896861.674525.296550@o11g2000prd.googlegroups.com> Message-ID: <466316AE.1080003@timgolden.me.uk> rohit wrote: > hello > well in my implementation of readdirectorychangesw i am using > threading that is multiple programs run simultaneously each program > monitoring one drive for changes. > is their a way around this...one program for all drives? > thanks You could use the ReadDirectoryChangesW in overlapped mode. I've never tried it, so I don't know how robust it would be. Why is it a problem to have "multiple programs" running? And is that simply multiple threads, or multiple processes? TJG From vinay_sajip at yahoo.co.uk Thu Jun 7 13:13:43 2007 From: vinay_sajip at yahoo.co.uk (Vinay Sajip) Date: Thu, 07 Jun 2007 10:13:43 -0700 Subject: open function fail after running a day In-Reply-To: <1181226795.455934.177550@n15g2000prd.googlegroups.com> References: <1181226795.455934.177550@n15g2000prd.googlegroups.com> Message-ID: <1181236423.066991.264260@o5g2000hsb.googlegroups.com> On Jun 7, 3:33 pm, alexteo21 wrote: > I have created a script using python that will batch process data > files every hour > The script is running on Solaris. Python version 2.3.3 > > t=open(filename,'rb') > data=t.read() > #processing data... > t.close() Try the following approach: t=open(filename,'rb') try: data=t.read() #processing data... finally: t.close() and see if that improves matters. If you want to add logging for a quick check, then... import logging t=open(filename,'rb') try: data=t.read() #processing data... except: logging.exception("Failed to process file %r", filename) finally: t.close() Regards, Vinay Sajip From ping.nsr.yeh at gmail.com Thu Jun 14 15:53:38 2007 From: ping.nsr.yeh at gmail.com (Ping) Date: Thu, 14 Jun 2007 12:53:38 -0700 Subject: a_list.count(a_callable) ? Message-ID: <1181850818.567840.251090@x35g2000prf.googlegroups.com> Hi, I'm wondering if it is useful to extend the count() method of a list to accept a callable object? What it does should be quite intuitive: count the number of items that the callable returns True or anything logically equivalent (non-empty sequence, non-zero number, etc). This would return the same result as len(filter(a_callable, a_list)), but without constructing an intermediate list which is thrown away after len() is done. This would also be equivalent to n = 0 for i in a_list: if a_callable(i): n += 1 but with much shorter and easier-to-read code. It would also run faster. This is my first post and please bear with me if I'm not posting it in the right way. Regards, Ping From mkb at incubus.de Wed Jun 20 17:43:04 2007 From: mkb at incubus.de (Matthias Buelow) Date: Wed, 20 Jun 2007 23:43:04 +0200 Subject: The Modernization of Emacs: terminology buffer and keybinding In-Reply-To: <1182375388.814275.227380@n2g2000hse.googlegroups.com> References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182272495.990807.99110@a26g2000pre.googlegroups.com> <87tzt3ihev.fsf@kobe.laptop> <1182370216.961241.6960@n60g2000hse.googlegroups.com> <85zm2ufjpb.fsf@lola.goethe.zz> <1182372592.803332.288260@u2g2000hsc.googlegroups.com> <5dtk4tF34jrimU1@mid.dfncis.de> <1182375388.814275.227380@n2g2000hse.googlegroups.com> Message-ID: <5dtlavF34is51U1@mid.dfncis.de> Twisted wrote: > Emacs does have documentation. The problem is you have to already know > a load of emacs navigation oddities^Wkeyboard commands to get to and > use it. Yes, like hitting the F1 key. > Yeah, and I abhor the elitist systems that are designed with the > philosophy that anyone who hasn't mastered years of arcane > memorization and training in just that one idiosyncratic system is / > ipso facto/ "stupid and unsophisticated". Most of us 6 and a half > billion people have better uses for our time, such as buckling in and > being promptly productive, once we're out of high school or college, > and fully three and a quarter of us are at least as smart as average, > and so /ipso facto/ *not* "stupid and unsophisticated". Noone forces you to use either Unix or emacs (or vi, for that matter). I don't really understand what your problem is. From exhuma at gmail.com Mon Jun 11 10:07:21 2007 From: exhuma at gmail.com (exhuma.twn) Date: Mon, 11 Jun 2007 07:07:21 -0700 Subject: Pasting an image from clipboard in Tkinter? In-Reply-To: <1181569638.924072.25150@k79g2000hse.googlegroups.com> References: <1181569638.924072.25150@k79g2000hse.googlegroups.com> Message-ID: <1181570841.240967.242820@p77g2000hsh.googlegroups.com> On Jun 11, 3:47 pm, kyoso... at gmail.com wrote: > On Jun 11, 7:23 am, "exhuma.twn" wrote: > > > > > As many might know, windows allows to copy an image into the clipboard > > by pressing the "Print Screen" button on the keyboard. Is it possible > > to paste such an image from the clipboard into a "Text" widget in > > Tkinter? Here is my first attempt with just trying to print out the > > image data: > > > ----------------- > > def pasteImg(tgt): > > global clipboardEnabled > > if not clipboardEnabled: return > > > win32clipboard.OpenClipboard(0) > > print win32clipboard.GetClipboardData() > > win32clipboard.CloseClipboard() > > ----------------- > > > This works fine with selecting text, but comes up with the following > > error when trying to paste an image: > > > ----------------- > > Exception in Tkinter callback > > Traceback (most recent call last): > > File "C:\Python25\lib\lib-tk\Tkinter.py", line 1403, in __call__ > > return self.func(*args) > > File "X:\development\testing\tkwiki\tkwiki.py", line 52, in > > Button( root, command=lambda: pasteImg(txt) ).pack() > > File "X:\development\testing\tkwiki\tkwiki.py", line 38, in pasteImg > > print win32clipboard.GetClipboardData() > > TypeError: Specified clipboard format is not available > > ----------------- > > > Obviously the clipboard does not know about that format. Does that > > mean I have to wait until it's implemented or are there other ways to > > access the image data? > > I don't think you can paste to a text widget, but I could be mistaken. > This link talks about pasting an image into a window, but I don't > think it's really what you want...however, it might give you some > ideas: > > http://effbot.org/zone/wck-3.htm (see the "Drawing Images" section) > > This link also talks about some of the same things:http://www.wadsworth.org/spider_doc/spider/docs/python/spipylib/tkint... > > If I understand them correctly, it sounds like you could possibly > catch the the paste operation and convert the image to a TkImage and > then paste it. I think that since it is in the clipboard, then it is a > file object and this may work. I just don't know how you intercept a > paste. > > Mike Unfortunately, when they talk about "pasting" they talk about a PIL method called paste, which (if I understood correctly) deals with blitting one image onto another. Not "pasting" as in copy/paste from clipboard. From martin at v.loewis.de Tue Jun 5 17:17:14 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 05 Jun 2007 23:17:14 +0200 Subject: Getting mount stats for filesystems In-Reply-To: References: <46650e6c$0$25817$9b622d9e@news.freenet.de> <4665a7e9$0$24866$9b622d9e@news.freenet.de> <4665ba45$0$19674$9b622d9e@news.freenet.de> Message-ID: <4665d2db$0$24047$9b622d9e@news.freenet.de> > I am looking at ctypes and it might do what I need but I can't figure > out a way to convert a Python File object to a C FILE pointer (which is > the needed argument for getmntent). > > Any ideas? I think you are supposed to pass the pointer to getmntent that you obtained from setmntent (likely asking for read-only access). Regards, Martin From siddharta at gmail.com Tue Jun 12 02:49:31 2007 From: siddharta at gmail.com (Siddharta .) Date: Tue, 12 Jun 2007 06:49:31 -0000 Subject: Setting the encoding in the basic auth header In-Reply-To: <466E3B25.80304@v.loewis.de> References: <1181627140.208015.256160@q19g2000prn.googlegroups.com> <466E3B25.80304@v.loewis.de> Message-ID: <1181630971.896085.88820@d30g2000prg.googlegroups.com> On Jun 12, 11:20 am, "Martin v. L?wis" wrote: > As a further follow-up, see > > https://bugzilla.mozilla.org/show_bug.cgi?id=41489 > Wow, thanks a lot for the link. Just had a look at it. The thread runs from 2000 to 2007!! 7 years!! What a complete mess :) Guess I'll just have to enforce ASCII usernames and passwords for now. Hope the IETF get around soon to updating the spec. It's really weird that you cant enter non-ascii characters in a basic auth dialog. Thanks again. -- Siddharta From gagsl-py2 at yahoo.com.ar Tue Jun 19 13:21:35 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 19 Jun 2007 14:21:35 -0300 Subject: Windows XMLRPC Service References: <1182137125.879556.319030@g37g2000prf.googlegroups.com> <1182235519.964013.146800@a26g2000pre.googlegroups.com> Message-ID: En Tue, 19 Jun 2007 03:45:19 -0300, escribi?: > I can't quite figure out where to set the "socket timeout". I tried > setting win32event.WAIT_TIMEOUT, but I'm pretty sure that's not the > variable you were talking about. I did manage to make it multi- > threaded by incorporating a different recipe, and I'm beginning to > understand the control flow a bit better, but it doesn't seem to be > doing what I expect. When SvcStop() is executed and calls > win32event.SetEvent(self.hWaitStop), the while loop should break as > win32event.WaitForSingleObject(self.hWaitStop, 0) returns zero at this > point. But it doesn't do that. What am I missing? May be because you didn't set correctly the socket timeout. See the comments below. > > def SvcStop(self): > self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) > win32event.SetEvent(self.hWaitStop) > #print "EVENT:", > win32event.WaitForSingleObject(self.hWaitStop, 0) # returns 0 here That's OK, since you have set the event. > def SvcDoRun(self): > self.server.register_instance(MyClass()) > > #win32event.WAIT_TIMEOUT = 2 --- This just makes the loop > never execute because > # the WaitFor... part always returns 258 WAIT_TIMEOUT is 258. How do you see it is 2? For example, see . Python 2.5.1 + pywin32 210 prints this on my PC: py> import win32event py> win32event.WAIT_TIMEOUT 258 > while win32event.WaitForSingleObject(self.hWaitStop, 0) == > win32event.WAIT_TIMEOUT: > self.server.handle_request() The loop above should keep running until hWaitStop is set, with a maximum wait time (inside handle_request) corresponding to the socket timeout value. You can either: - use socket.setdefaulttimeout() (in __init__, by example) before anything else. This will set a global timeout for all sockets. - modify the socket instance. Just add this method to your AsyncServer: def server_activate(self): SimpleXMLRPCServer.server_activate(self) self.socket.settimeout(15) # for 15 secs -- Gabriel Genellina From cai.haibin at gmail.com Mon Jun 4 23:04:39 2007 From: cai.haibin at gmail.com (james_027) Date: Tue, 05 Jun 2007 03:04:39 -0000 Subject: excel library without COM In-Reply-To: <1180959384.545415.102340@n15g2000prd.googlegroups.com> References: <1180918791.467050.186520@r19g2000prf.googlegroups.com> <1180936346.272773.162540@q66g2000hsg.googlegroups.com> <1180959384.545415.102340@n15g2000prd.googlegroups.com> Message-ID: <1181012679.069496.178870@j4g2000prf.googlegroups.com> On Jun 4, 8:16 pm, John Machin wrote: > On Jun 4, 3:52 pm, yuce wrote: > > > i think this one works pretty nice:http://www.python.org/pypi/xlrd > > Sure does :-) However the "rd" in "xlrd" is short for "ReaD". As > Waldemar suggested, "xlwt" ("wt" as in WriTe) is more like what the OP > needs. > > Cheers, > John Thanks to all who have contributed. I have one concern though. Many of the module seems to be not active anymore? or updated? It is because it really stable and has most of the features needed? Thanks james From larry.bates at websafe.com Thu Jun 7 14:26:00 2007 From: larry.bates at websafe.com (Larry Bates) Date: Thu, 07 Jun 2007 13:26:00 -0500 Subject: Where can I suggest an enchantment for Python Zip lib? In-Reply-To: References: Message-ID: <46684DB8.6080900@websafe.com> durumdara wrote: > Hi! > > Where can I ask it? > > I want to ask that developers change the Python's Zip lib in the next > versions. > The Zip lib not have a callback procedure. When I zip something, I don't > know, what is the actual position of the processing, and how many bytes > remaining. > It is simply rewriteable, but when I get new Python, it is forget this > thing again... > > So some callback needed for it, if possible. With this I can abort > processing and I can show the actual state when I processing a large file. > > See this thread: > http://groups.google.com.kh/group/comp.lang.python/browse_thread/thread/c6069d12273025bf/18b9b1c286d9af7b?lnk=st&q=python+zip+callback&rnum=1#18b9b1c286d9af7b > > > Thanks for your help: > dd > > You can easily find out roughly how many bytes are in your .ZIP archive by using following: zipbytes=Zobj.fp.tell() Where Zobj is your zipfile instance. You don't need a callback. Problem is ill defined for a better solution. You don't know how much the "next" file will compress. It may compress a lot, not at all or in some situations actually grow. So it is difficult (impossible?) to know how many bytes are remaining. I have a rough calculation where I limit the files to 2Gb, but you must set aside some space for the table of contents that gets added at the end (whose size you don't actually know either). So I use: maxzipbytesupperlimit=int((1L<<31)-(8*(1<<20))) That is 2Gb-8Mb maximum TOC limit of a zip file. I look at zipbytes add the uncompressed size of the next file, if it exceeds maxzipbytesupperlimit, I close the file and move to the next zip archive. If it is smaller, I add the file to the archive. Hope this helps. -Larry From half.italian at gmail.com Fri Jun 8 16:46:47 2007 From: half.italian at gmail.com (half.italian at gmail.com) Date: Fri, 08 Jun 2007 20:46:47 -0000 Subject: launching default browser In-Reply-To: References: Message-ID: <1181335607.939361.230420@x35g2000prf.googlegroups.com> On Jun 8, 8:41 am, alf wrote: > Hi, > > I wonder how to launch from python default Windows browser? In fact I > have the same question for Linux. > > thx in advancve, > -- > alf For posterity... On a mac [sean:~] sean% open http://www.google.com ~Sean From facundo at taniquetil.com.ar Mon Jun 11 09:32:45 2007 From: facundo at taniquetil.com.ar (Facundo Batista) Date: Mon, 11 Jun 2007 13:32:45 +0000 (UTC) Subject: Santa Fe Python Day report Message-ID: It was very succesful, around +300 people assisted, and there were a lot of interesting talks (two introductory talks, Turbogears, PyWeek, Zope 3, security, creating 3D games, Plone, automatic security testings, concurrency, and programming the OLPC). I want to thanks the PSF for the received support. Python is developing interestingly in Argentina, and this Python Days are both a prove of that, and a way to get more Python developers. Some links: Santa Fe Python Day: http://www.python-santafe.com.ar/ Python Argentina: http://www.python.com.ar/moin Regards, -- . Facundo . Blog: http://www.taniquetil.com.ar/plog/ PyAr: http://www.python.org/ar/ From skip.montanaro at gmail.com Thu Jun 7 11:14:28 2007 From: skip.montanaro at gmail.com (Skip Montanaro) Date: Thu, 7 Jun 2007 10:14:28 -0500 Subject: Lack of += and -= operators in Pyrex? In-Reply-To: <60bb7ceb0706070657y5fadb720ha2165e56ecf25ae4@mail.gmail.com> References: <60bb7ceb0706070657y5fadb720ha2165e56ecf25ae4@mail.gmail.com> Message-ID: <60bb7ceb0706070814y7187f44v385068e82c5cf25d@mail.gmail.com> > ... I noticed it complains > about the use of the += and -= assignment operators. The fix is > obviously pretty trivial. I didn't notice any mention in the Pyrex > docs as a difference between Python and Pyrex though. Was I mistaken? Never mind. I missed the bit where it said they haven't yet been implemented. Sorry for the noise... Skip From doug at alum.mit.edu Fri Jun 15 16:58:56 2007 From: doug at alum.mit.edu (Douglas Alan) Date: Fri, 15 Jun 2007 16:58:56 -0400 Subject: Python's "only one way to do it" philosophy isn't good? References: <1181368143.874341.273140@r19g2000prf.googlegroups.com> <1181385768_30305@sp12lax.superfeed.net> Message-ID: "Terry Reedy" writes: > My only point was that Sussman is an odd person to be criticizing > (somewhat mistakingly) Python for being minimalist. I think that being a language minimalist is very different from believing that there should be exactly one obvious way to do everything. For instance, I believe that Python is now too big, and that much of what is in the language itself should be replaced with more general Scheme-like features. Then a good macro mechanism should be implemented so that all the conveniences features of the language can be implemented via macro definitions in the standard library. Macros, however, are typically claimed in these parts to violate the "only one way" manifesto. |>oug From You don't need it Wed Jun 20 18:40:42 2007 From: You don't need it (Daniel Dyer) Date: Wed, 20 Jun 2007 23:40:42 +0100 Subject: The Modernization of Emacs References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182344981.372713.298580@w5g2000hsg.googlegroups.com> <86y7ieoiv7.fsf@lola.quinscape.zz> <1182378809.880265.314150@o61g2000hsh.googlegroups.com> Message-ID: On Wed, 20 Jun 2007 23:33:29 +0100, Dave Hansen wrote: > On Jun 20, 8:28 am, David Kastrup wrote: >> Actually, the "E" in "Emacs" stands for "extensible". Part of the >> appeal of Emacs is that you can change it to accommodate you. > > Actually, though Emacs is the epitome of extensibility, the "E" stands > for "Editor." "EMACS" is simply short for Editor MACroS, and was > originally implemented as a set of TECO macros. > > There's also the joke that EMACS stands for Esc Meta Alt Ctrl Shift, > due to it's (often overwhelmingly) large and sometimes complex set of > keystroke combinations used to invoke various editing functions. This > view is usually put forth by the vi camp during editor wars. > There are dozens of alternative interpretation for "EMACS". http://www.gnu.org/fun/jokes/gnuemacs.acro.exp.html My favourite: Elsewhere Maybe All Commands are Simple Dan. -- Daniel Dyer http//www.uncommons.org From duncan.booth at invalid.invalid Mon Jun 11 02:58:01 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 11 Jun 2007 06:58:01 GMT Subject: How can I obtain the exception object on a generlized except statement? References: <1181476163.064695.30410@r19g2000prf.googlegroups.com> Message-ID: Chris Allen wrote: > I am confused on one aspect of exception handling. If you specify the > exception object type to match in an except statement it is possible > to also obtain the exception object itself, but I can't figure out how > to get the exception object when I don't specify a match. In most cases you can just catch Exception. If you want to be sure to catch deprecated string exceptions also then use sys.exc_info(). try: ... something ... except Exception, e: print e Also what you want to do with it when you've caught it makes a difference: If you are planning on logging a stack backtrace then you'll want the traceback as well as the exception, so sys.exc_info() might be indicated except that in that case you'll be better off using logging.exception() instead. try: ... something ... except: logging.exception("Unexpected error") If you are just planning on swallowing the exception then you don't want any of these: you want to catch the specific exceptions that you expect to be raised. > >>> except (),msg: Using an empty tuple for the exception specification won't catch any exceptions. Not very useful if the tuple is a literal, but it could be useful in some obscure situations (e.g. an except clause to handle exceptions declared in a specific DLL which might not always be present). From http Fri Jun 22 11:05:29 2007 From: http (Paul Rubin) Date: 22 Jun 2007 08:05:29 -0700 Subject: "assert" annoyance References: <7xmyys368j.fsf_-_@ruckus.brouhaha.com> Message-ID: <7xmyysyqpy.fsf@ruckus.brouhaha.com> Thomas Heller writes: > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65287 Thanks! This looks very useful. From steve at laniels.org Thu Jun 21 10:11:57 2007 From: steve at laniels.org (Stephen R Laniel) Date: Thu, 21 Jun 2007 10:11:57 -0400 Subject: PEP 3107 and stronger typing (note: probably a newbie question) In-Reply-To: <5dveb4F360un0U1@mid.individual.net> References: <1182369568.941307.316260@p77g2000hsh.googlegroups.com> <5dveb4F360un0U1@mid.individual.net> Message-ID: <20070621141156.GG6145@slaniel-laptop.itasoftware.com> On Thu, Jun 21, 2007 at 03:55:48PM +0200, Bjoern Schliessmann wrote: > I agree. I also notice that (rather newbie-) OPs with not-so-simple > questions are easily offended by technical answers. I'd love to > know why. One doesn't like to get meta on such things, as so often happens, so I'll be brief. The way I read my original post was like so: "I know lots of people have probably had a similar question, so please point me to a canonical answer is there is one. So here's the question...". To me, an appropriate answer there is, "That's a good question, and many people have asked it. Here's why it's unlikely that static type-checking makes sense in the context of Python, and why it couldn't just be added in pieces." We got there eventually, but only after what seemed to me to be a bout of rudeness. Now, maybe my own followup clarified something that I should have included in the original. "Use another language" is not a technical answer. "Python could not adopt static typing without substantially changing the language and destroying what everyone loves about it, and here are examples of where the problem shows up" is. But I've just gone meta, so I'll stop. -- Stephen R. Laniel steve at laniels.org Cell: +(617) 308-5571 http://laniels.org/ PGP key: http://laniels.org/slaniel.key From bruno.desthuilliers at gmail.com Sun Jun 17 17:05:13 2007 From: bruno.desthuilliers at gmail.com (bruno.desthuilliers at gmail.com) Date: Sun, 17 Jun 2007 14:05:13 -0700 Subject: global destructor not called? In-Reply-To: References: <4672b53f$0$31597$426a74cc@news.free.fr> Message-ID: <1182114313.259817.185670@m36g2000hse.googlegroups.com> On Jun 15, 7:07 pm, Neal Becker wrote: > Bruno Desthuilliers wrote: > > Neal Becker a ?crit : > >> To implement logging, I'm using a class: > > > If I may ask : any reason not to use the logging module in the stdlib ? > > Don't exactly recall, but needed some specific behavior and it was just > easier this way. > Ok, that's was just in case you didn't know about this module... > > > > >> class logger (object): > >> def __init__ (self, name): > >> self.name = name > >> self.f = open (self.name, 'w') > >> def write (self, stuff): > >> self.f.write (stuff) > >> def close (self): > >> self.f.close() > >> def flush (self): > >> self.f.flush() > >> def reopen (self): > >> self.f.flush() > >> self.f.close() > >> os.rename (self.name, self.name + '.old') > >> self.f = open (self.name, 'w') > >> def __del__ (self): > >> try: > >> os.remove (self.name + '.old') > >> except: > >> pass > > >> And setting: > >> sys.stderr = logger(...) > > >> It seems my cleanup (__del__) is never called, > > > What makes you think so ? > > Cleanup should remove file file '.old', > and it wasn't removed. > Adding > atexit.register (self.__del__) to the logger constructor DID fix it. > Mmm... If I read the language's references, I see this: """ It is not guaranteed that __del__() methods are called for objects that still exist when the interpreter exits. """ http://docs.python.org/ref/customization.html Hopefully you fuond the right way to ensure correct clean-up !-) (damn, I knew I rembered something special about destructors... but I couldn't remember exactly what.) From ppaterson at gmail.com Wed Jun 6 12:17:44 2007 From: ppaterson at gmail.com (Paul Paterson) Date: Wed, 06 Jun 2007 09:17:44 -0700 Subject: Can os.remove followed by os.path.isfile disagree? In-Reply-To: <5co2l6F31fu1eU2@mid.uni-berlin.de> References: <1181140547.279974.83550@q66g2000hsg.googlegroups.com> <5co2l6F31fu1eU2@mid.uni-berlin.de> Message-ID: <1181146664.092851.143880@w5g2000hsg.googlegroups.com> > > Is the file on a network drive by any chance? > > Diez No, but the server is actually a VMWare VM and the drive is a virtual drive. I'm thinking that this may be significant as it may be that the VMWare VHD driver is the "flashy software running which intercepts OS file- manipulation calls" that Tim Golden suggested. Paul From fabiofz at gmail.com Fri Jun 29 14:40:06 2007 From: fabiofz at gmail.com (Fabio Zadrozny) Date: Fri, 29 Jun 2007 15:40:06 -0300 Subject: Pydev 1.3.6 Released Message-ID: Hi All, Pydev and Pydev Extensions 1.3.6 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: ----------------------------------------------------------------- * Bug-Fixes Release Highlights in Pydev: ---------------------------------------------- * Bug Fix: Builtins were not correctly used after specifying interpreter (so, the builtins would not be available in completions/code-analysis). * Patch (from Carl Robinson): PyLint severities can now be specified. 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 -------------- next part -------------- An HTML attachment was scrubbed... URL: From mitko at qlogic.com Mon Jun 4 21:28:35 2007 From: mitko at qlogic.com (Mitko Haralanov) Date: Mon, 4 Jun 2007 18:28:35 -0700 Subject: Getting mount stats for filesystems Message-ID: <20070604182835.390c142d@opal.pathscale.com> Hi, I am trying to find a way to figure out whether a certain remote filesystem is mounted using tcp vs. udp in Python. I've looked at the statvfs call and module but they don't give me anything useful (the F_FLAGS field for both a tcp and a udp filesystem is the same. I could, of course, get the output of mount and parse that but I would prefer something more elegant. Thanks for your help! -- Mitko Haralanov mitko at qlogic.com Senior Software Engineer 650.934.8064 System Interconnect Group http://www.qlogic.com ========================================== Remember, UNIX spelled backwards is XINU. -- Mt. From pelonpelon at gmail.com Thu Jun 21 04:58:46 2007 From: pelonpelon at gmail.com (pelon) Date: Thu, 21 Jun 2007 08:58:46 -0000 Subject: SimplePrograms challenge In-Reply-To: References: Message-ID: <1182416326.653651.157540@m36g2000hse.googlegroups.com> *** New Thread #5 has been bothering me. def greet(name): print 'hello', name greet('Jack') greet('Jill') greet('Bob') Using greet() three times is cheating and doesn't teach much and doesn't have any real world use that #1 can't fulfill. I offer this replacement: def greet(name): """ This function prints an email signature """ #optional doc string highly recommended print name + " can be reached at", #comma prevents newline from being printed print '@'.join([name, "google.com"]) greet('Jill') I think it's important to teach new pythonistas about good documentation from the start. A few new print options are introduced. And as far as functionality goes, at least it does something. From tokyo246 at gmail.com Fri Jun 22 14:50:45 2007 From: tokyo246 at gmail.com (Kenji Noguchi) Date: Fri, 22 Jun 2007 11:50:45 -0700 Subject: Tailing a log file? In-Reply-To: References: Message-ID: <2ba587f0706221150v3461d23dt3eafa4a408240f01@mail.gmail.com> something like this? unix tail command does more fancy stuff like it waits for timeout, and check if the file is truncated or depending on incoming data it sleeps seconds , etc etc. #!/usr/bin/env python import sys, select while True: ins, outs, errs = select.select([sys.stdin],[],[]) for i in ins: print i.readline() 2007/6/22, Evan Klitzke : > On 6/22/07, Evan Klitzke wrote: > > Everyone, > > > > I'm interested in writing a python program that reads from a log file > > and then executes actions based on the lines. I effectively want to > > write a loop that does something like this: > > > > while True: > > log_line = log_file.readline() > > do_something(log_line) > > > > Where the readline() method blocks until a new line appears in the > > file, unlike the standard readline() method which returns an empty > > string on EOF. Does anyone have any suggestions on how to do this? > > Thanks in advance! > > I checked the source code for tail and they actually poll the file by > using fstat and sleep to check for changes in the file size. This > didn't seem right so I thought about it more and realized I ought to > be using inotify. So I guess I answered my own question. > > -- > Evan Klitzke > -- > http://mail.python.org/mailman/listinfo/python-list > From dak at gnu.org Sat Jun 23 04:05:15 2007 From: dak at gnu.org (David Kastrup) Date: Sat, 23 Jun 2007 10:05:15 +0200 Subject: The Modernization of Emacs References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182370894.001918.36590@k79g2000hse.googlegroups.com> <1182372821.298343.316860@g4g2000hsf.googlegroups.com> <1182375321.067664.190780@o61g2000hsh.googlegroups.com> <86hcp1l6hb.fsf@lola.quinscape.zz> <1182552254.233679.180790@o11g2000prd.googlegroups.com> Message-ID: <85r6o3gkp0.fsf@lola.goethe.zz> nebulous99 at gmail.com writes: > PS you'll have to stop posting such a high volume here. I'm getting > BS from Google Groups about posting limits being exceeded again. Oh, but that just means that _YOU_ will have to stop posting such a high volume here. Others are not affected. Though I have no doubt they'll welcome a thinning out of this thread (followups directed to comp.emacs for that reason). > Apparently they've lowered it still further, from 25 in a 24 hour > period to 12 or so in a 24 hour period. Fuckers. How about making _summary_ answers then? Your whole contributions boil down to "You must be lying. This can't be Emacs you are talking about, since I know Emacs intimately because of having looked at an old version of it for half an hour about 10 years ago." anyway. You don't need to post this 12 times per day. You don't even need to post this at all. It does not get any less stupid by repetition. What _is_ sort of amusing is that years ago you already accused me of forgery when I pointed you to the Emacs screenshots on the preview-latex page. It appears that you still have not bothered educating yourself, years after you were pretty much universally derided in comp.text.tex for making a spectacle of your self-chosen ignorance. -- David Kastrup, Kriemhildstr. 15, 44793 Bochum From python at jayloden.com Thu Jun 14 21:15:15 2007 From: python at jayloden.com (Jay Loden) Date: Thu, 14 Jun 2007 21:15:15 -0400 Subject: Problems with regular expressions In-Reply-To: <37BCDB14F06B98469A85DEC4771763B574C6EF@exch01.medianet.es> References: <37BCDB14F06B98469A85DEC4771763B574C6EF@exch01.medianet.es> Message-ID: <4671E823.1040302@jayloden.com> Carlos Luis P?rez Alonso wrote: > I have the next piece of code: > > ------------------------------------------------------------------------ > if re.search('^(taskid|bugid):\\d+',logMessage): > return 0 > else: > sys.stderr.write("El comentario tiene que contener el taskid:#### o el bugid:####") > return 1 > ------------------------------------------------------------------------- > > The regular exprexi?n is "^(taskid|bugid):\\d+" > > Mi problem is that if logMessage == "taskid:234" the regular expression matched teorically, but the result is always "None" and the function returns 1. > > ?Does anybody has an idea of what is happening here? > > Thanks I'm pretty sure it's the escaping on your regular expression. You should use the raw string operator: ----- #!/usr/bin/python import re,sys def checkLogMsg(logMessage): if re.search(r'^(taskid|bugid):\d+', logMessage): return 0 else: sys.stderr.write("El comentario tiene que contener el taskid:#### o el bugid:####") return 1 print checkLogMsg('taskid:234') print checkLogMsg('doesnotmatch') ----- Outputs: $ python test_reg.py 0 El comentario tiene que contener el taskid:#### o el bugid:####1 HTH, -Jay From ppaterson at gmail.com Wed Jun 6 11:46:29 2007 From: ppaterson at gmail.com (Paul Paterson) Date: Wed, 06 Jun 2007 08:46:29 -0700 Subject: Can os.remove followed by os.path.isfile disagree? In-Reply-To: References: <1181140547.279974.83550@q66g2000hsg.googlegroups.com> Message-ID: <1181144789.976534.310470@n4g2000hsb.googlegroups.com> Thanks for the quick and detailed response! > The most likely bet would seem to be a race condition > as you suggest below. Doesn't have to be from a thread > in your program, although I assume you know best about > your own filesystem ;) My first thought, after discounting the os.remove early return, was that it has to be from a thread in our application. But, a) it is highly unlikely due to the way tasks are scheduled b) even if it did occur I don't see a code path that ends with the file not there But, until I read the next part of your note, it was still the only credible explanation ... > > Don't suppose you've got some kind of flashy software > running which intercepts OS file-manipulation calls for > Virus or Archiving purposes? > ... I'm wondering if this is the culprit. I now recall that the Spambayes project saw a weird error due to Google Desktop Search where GDS would intervene at such a low level that some file system level "invariants" ... aren't! I don't remember the details but I think you delete or create a file and GDS jumps in to backup / index it and you don't have the access you thought you had moments ago. I don't think GDS is running on this server but it is running a lot of other enterprise monitoring apps and maybe they are doing a similar thing. I'm off to investigate more on this front! Thanks, Paul From steve at holdenweb.com Sat Jun 2 16:21:39 2007 From: steve at holdenweb.com (Steve Holden) Date: Sat, 02 Jun 2007 16:21:39 -0400 Subject: Detecting an active exception In-Reply-To: References: Message-ID: <4661D153.4060101@holdenweb.com> Duncan Booth wrote: > "NeBlackCat (lists)" wrote: > >> Depending on what you read, sys.exc_info() is supposed to return >> (None,None,None) when there is no active exception, but it seems that >> it returns info about the last exception when there isn't one >> currently active. >> >> For example: >> >> try: >> a = a + 1 >> except: >> pass >> >> print sys.exc_info() >> >> produces: >> , > instance at 0x00B5E508>, >> >> Where the traceback object identifies the offending a=a+1 line (of >> course). >> >> Is there another way of doing this? Note that I can't rely on using >> sys.exc_clear() in any solution, unfortunately. > > I think you have misunderstood the definition of when an exception is > 'currently active'. When an exception is caught, it remains currently > active so long as you are in the same function, or in a function which it > calls (i.e. so long as the current scope is still active). When you return > from that function the exception is no longer active and the previous > exception becomes active (or None if there has not been one or you have > used sys.exc_clear()). > > Try this: > --------- t.py ------------- > import sys > > def f(): > try: > a = a + 1 > except: > pass > > g() > print "f", sys.exc_info() > > def g(): > print "g", sys.exc_info() > > def h(): > f() > print "h", sys.exc_info() > > h() > ---------------------------- > The output is: > > g (, UnboundLocalError("local variable > 'a' referenced before assignment",), ) > f (, UnboundLocalError("local variable > 'a' referenced before assignment",), ) > h (None, None, None) > > As you can see the exception remains 'currently active' only until the > function in which it was caught returns. Duncan, that's a great description that should go in the docs (I suspect you aren't just quoting from them here). Kristj?n V. J?nsson has also raised some great points about this issue in a multi-threaded multi-processing application architecture both simplified and complicated by the presence of Stackless, though I can't lay my hands on any summary of his findings right now. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden ------------------ Asciimercial --------------------- Get on the web: Blog, lens and tag your way to fame!! holdenweb.blogspot.com squidoo.com/pythonology tagged items: del.icio.us/steve.holden/python All these services currently offer free registration! -------------- Thank You for Reading ---------------- From dfabrizio51 at gmail.com Mon Jun 4 10:25:12 2007 From: dfabrizio51 at gmail.com (chewie54) Date: Mon, 04 Jun 2007 14:25:12 -0000 Subject: python for EE CAD program In-Reply-To: <5cik0mF30e4avU1@mid.uni-berlin.de> References: <1180964104.685598.21330@n4g2000hsb.googlegroups.com> <5cik0mF30e4avU1@mid.uni-berlin.de> Message-ID: <1180967112.693545.64270@p77g2000hsh.googlegroups.com> On Jun 4, 9:56 am, "Diez B. Roggisch" wrote: > chewie54 wrote: > > Hi All, > > > I have read some posts on this subject but I haven't been able to make > > a decision whether to use Python or not. > > > I'm considering converting a Java CAD program to Python/C with > > wxWdigets for the GUI. > > > I don't have good answers for: > > > 1) Can I use py2exe or pyinstaller to produce an executable for > > Linux, Windows, and Mac? If not, is there a way it can be done? > > > 2) Is there any way to protect the source code, like obfuscation? > > > 3) Memory footprint of application seems large for python demo. Is > > this typical for large python applications? > > > I guess the best thing to do is convert a little portion of the Java > > program and see how it works out with respect to the concerns above. > > > Suggestions and comments appreciated. > > Look at python-cad, that might give you an idea how such a thing is to be > accomplished using python. > > Diez Hello Diez, I did look at PythonCad but the distribution and install methods for Windows is not user freindly. Since the public domain software, I don't think they protect the source code either. From "sergio\" at (none) Tue Jun 19 10:28:19 2007 From: "sergio\" at (none) (none) Date: Tue, 19 Jun 2007 15:28:19 +0100 Subject: HTMLParser.HTMLParseError: EOF in middle of construct In-Reply-To: References: <1182195498.16548.5.camel@localhost.localdomain> Message-ID: <4677e7de$0$2840$a729d347@news.telepac.pt> Gabriel Genellina wrote: > En Mon, 18 Jun 2007 16:38:18 -0300, Sergio Monteiro Basto > escribi?: > >> Can someone explain me, what is wrong with this site ? >> >> python linkExtractor3.py http://www.noticiasdeaveiro.pt > test >> >> HTMLParser.HTMLParseError: EOF in middle of construct, at line 1173, >> column 1 >> >> at line 1173 of test file is perfectly normal . > > That page is not valid HTML - http://validator.w3.org/ finds 726 errors > in it. ok but my problem is not understand what is the specific problem at line 1173 > HTMLParser expects valid HTML - try a different tool, like > BeautifulSoup, which is specially designed to handle malformed pages. > > --Gabriel Genellina > From siddeshone at gmail.com Fri Jun 1 00:08:45 2007 From: siddeshone at gmail.com (siddeshone at gmail.com) Date: Fri, 01 Jun 2007 04:08:45 -0000 Subject: Ergonomic Mobile Computing Message-ID: <1180670925.799134.148460@i38g2000prf.googlegroups.com> I'm sharing with you my secret of the ultimate comfort using a laptop. Working with a laptop desk helps cool my laptop and it's a lot more easier to handle. The painful experience of aching wrists, strained neck and back is a story of the past with ergonomic typing and viewing angles. I feel more at ease with the wide mousing area and raised screen. It only pops-up one question in my mind "Why didn't I buy it earlier?". From martin at v.loewis.de Fri Jun 22 01:25:42 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Fri, 22 Jun 2007 07:25:42 +0200 Subject: Internationalised email subjects In-Reply-To: <1182417823.793678.323530@a26g2000pre.googlegroups.com> References: <1182337500.638044.63470@e9g2000prf.googlegroups.com> <46791592$0$5719$edfadb0f@dread14.news.tele.dk> <1182346499.123234.279880@e9g2000prf.googlegroups.com> <1182417604.446766.47660@e9g2000prf.googlegroups.com> <1182417823.793678.323530@a26g2000pre.googlegroups.com> Message-ID: <467B5D56.7060208@v.loewis.de> bugmagnet at gmail.com schrieb: > That's really strange. The chinese characters I am inputing into the > post are not being displayed. Basically, what I am doing is this: > > h = Header('(Some Chinese characters inserted here', 'GB2312') What encoding do "Some Chinese characters" have at that point? 1. Don't try this at the interactive prompt. It will completely confuse you. Instead, use IDLE. 2. In IDLE, put # -*- coding: utf-8 -*- into the top of the source code file. 3. Write the header as a Unicode string, i.e. with a u prefix 4. Explicitly encode it, such as h = Header(u'(Some Chinese characters inserted here'.encode('GB2312'), 'GB2312') If you are *not* inserting the characters from the Python source code directly, go back to my original question: What are the characters encoded in? HTH, Martin From gagsl-py2 at yahoo.com.ar Tue Jun 12 14:55:36 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 12 Jun 2007 15:55:36 -0300 Subject: for ... else ? References: <1181622331.955264.31610@i38g2000prf.googlegroups.com> <1181640889.439145.60020@g37g2000prf.googlegroups.com> <4866bea60706120641j2fa1fb09r89f937d75f5bd1b6@mail.gmail.com> Message-ID: En Tue, 12 Jun 2007 10:41:28 -0300, Chris Mellon escribi?: > On 6/12/07, Gabriel Genellina wrote: >> for x in iterable: >> do something with x >> else: >> do something when there are no more x >> >> >> You can think the above as: >> >> while there are still values in iterable: >> do something with the next value >> else: >> do something when there are no more items >> > > This is a good way of phrasing it and I hope I can remember it, > because for..else always gives me trouble. To me, "else" indicates the > negative condition and I intuitively associate it with executing the > loop early, not normal exit. Personally, I think a different keyword > (maybe "after"?) would have done a better job of clarifying this. Yes, maybe, but it's hard to find a keyword equally applicable to "for" and "while" and creating two new keywords for essencially the same thing would be too much... Anyway it's too late to be changed now. -- Gabriel Genellina From chris.lasher at gmail.com Sat Jun 16 10:52:45 2007 From: chris.lasher at gmail.com (Chris Lasher) Date: Sat, 16 Jun 2007 14:52:45 -0000 Subject: Priority Queue with Mutable Elements In-Reply-To: References: <1181939158.688317.207790@o61g2000hsh.googlegroups.com> Message-ID: <1182005565.861790.102360@q75g2000hsh.googlegroups.com> On Jun 15, 5:52 pm, Josiah Carlson wrote: > See this implementation of a "pair heap": > http://mail.python.org/pipermail/python-dev/2006-November/069845.html > ...which offers the ability to update the 'priority' of an entry in the > heap. It requires that the 'value' in (priority, value) pairs be unique > (to the heap) and hashable. > > - Josiah Hmm. I won't be able to use that heap, as I can guarantee that the value will be identical for two nodes when they have edges to each other and no other nodes. Any suggestions on structures that can accompany identical priority values? Thanks, Chris From datulaida.ali at gmail.com Fri Jun 22 04:04:11 2007 From: datulaida.ali at gmail.com (datulaida ali) Date: Fri, 22 Jun 2007 16:04:11 +0800 Subject: Apple Pie Parser with Python? Message-ID: <3b927740706220104o58bf3b51k304cf5924424251b@mail.gmail.com> Hi, How to integrate Apple Pie Parser with Python? Any suggestion to parsed text with Python? -------------- next part -------------- An HTML attachment was scrubbed... URL: From wildemar at freakmail.de Sat Jun 2 12:42:04 2007 From: wildemar at freakmail.de (Wildemar Wildenburger) Date: Sat, 02 Jun 2007 18:42:04 +0200 Subject: Observer-Pattern by (simple) decorator In-Reply-To: References: <1180781727.519949.172580@q75g2000hsh.googlegroups.com> Message-ID: <46619DDC.4000303@freakmail.de> Steven Bethard wrote: > Wildemar Wildenburger wrote: > >>>>> class Observable(object): >>>>> >> ... def __init__(self, func, instance=None, observers=None): >> ... self.func = func >> ... self.instance = instance >> ... self.observers = observers or [] >> > > Unless you also changed code in __get__, this means you'll get a new > list every time you access the "meth" attribute since the __get__ method > is called anew for every attribute access:: > > > Man! Nothing is easy ... ;) /W From jjl at pobox.com Mon Jun 25 17:33:51 2007 From: jjl at pobox.com (John J. Lee) Date: Mon, 25 Jun 2007 21:33:51 GMT Subject: What was that web interaction library called again? References: <1182521949.813529.75140@w5g2000hsg.googlegroups.com> Message-ID: <87fy4fu3b4.fsf@pobox.com> Harald Korneliussen writes: > Hi, > > I remember I came across a python library that made it radically > simple to interact with web sites, connecting to gmail and logging in > with four or five lines, for example. I thought, "that's interesting, > I must look into it sometime". Now there's this child I know who asked > me about programming, especially programs that could do things like > this, how difficult it was, and so on. I mentioned how I though Python > was a good intro to programming, and there was a library which was > perfect for what he wanted. > > Only now I've forgotten the name of the library! And try as I might, I > can't find it with google. I know there are modules for it in the > standard libraries, but this thing was brilliantly simple in > comparison. It might have been some sort of research project, I can't > remember... but perhaps someone here can remind me what it was? If so, > there may be yet another young python programmer in training :-) Be warned that all the web scraping tools I know of expose a fairly leaky abstraction. One has to know obscure and tiresome details fairly often. One common culprit is lack of JavaScript support. Another is HTML parsing problems. Still, it's fun when it works. Test-first development is good thing, IMHO -- make sure you don't actually have to do network stuff to test your parsing code, for example, or the delays will get irritating pretty fast. John From michael at jedimindworks.com Wed Jun 6 08:44:03 2007 From: michael at jedimindworks.com (Michael Bentley) Date: Wed, 6 Jun 2007 07:44:03 -0500 Subject: subprocess leaves child living In-Reply-To: References: <1181052375.551083.117390@p47g2000hsd.googlegroups.com> <874plmgogn.fsf@merkury.smsnet.pl> Message-ID: On Jun 6, 2007, at 7:11 AM, Thomas Dybdahl Ahle wrote: > Den Tue, 05 Jun 2007 17:41:47 -0500 skrev Michael Bentley: > >> On Jun 5, 2007, at 5:13 PM, Michael Bentley wrote: >> >> >>> On Jun 5, 2007, at 4:17 PM, Thomas Dybdahl Ahle wrote: >>> >>>> Den Tue, 05 Jun 2007 15:46:39 -0500 skrev Michael Bentley: >>>> >>>>> But actually *that* is an orphan process. When a parent >>>>> process dies >>>>> and the child continues to run, the child becomes an orphan and is >>>>> adopted by init. Orphan processes can be cleaned up on most >>>>> Unices >>>>> with >>>>> 'init q' (or something very similar). >>>> >>>> Is it not possible to tell python that this process should not be >>>> adopted >>>> by init, but die with its parrent? >>>> Just like terminals seem to do it.. >>> >>> Well, the way you posed the original question: >>> >>>> from subprocess import Popen >>>> popen = Popen(["ping", "google.com"]) from time import sleep >>>> sleep(100) >>> >>> is really what adoption by init is designed to handle. Here you've >>> created a child but have not waited for its return value. Like a >>> good >>> adoptive parent, init will wait(2) for the child. >>> >>> I think if you really looked into it you'd find that the terminal >>> had >>> called wait(2) before it was killed. Similarly, if you start a >>> long- >>> running subprocess in python and wait for it to return -- killing >>> the >>> parent will slaughter the child as well. >> >> I guess I should have verified my suspicions before speaking up -- >> I was >> worng -- even if you are waiting for a return code, the child will >> persist as a child of init. > > Bugger. > I know that if you use forkpty, the child get slaughtered, but > using the > subprocess module just seems much easier than forking. Yeah, and if there is some way (there may be, but I don't know) to make your python script the head of a process group (or session -- I'm not very clear on the distinction) -- children would be automatically slain. That's how a terminal session manages to get its children cleaned up I think... If it is important that children get terminated upon death of a parent, you probably do have to fork. g'luck! Michael --- "Neurons are far more valuable than disk space, screen lines, or CPU cycles." - Ben Finney From arshamshirvani at gmail.com Sun Jun 3 12:40:20 2007 From: arshamshirvani at gmail.com (Arsham Shirvani) Date: Sun, 03 Jun 2007 20:10:20 +0330 Subject: Why Python? In-Reply-To: References: Message-ID: <4662EEF4.4080606@gmail.com> > > > > > What is it about Python that makes it such a suitable language for > you? For instance, why would you use it over something similarly > portable as Java, or PHP? > > I know personally, in my small exposure to Python, I can see it as a > great learning tool for a basic introduction to programming and even > OOP. It's wonderful how your .py file can simply start making > expressions without any overhead, import/using statements, class > declarations, etc. > > -- > Chris Stewart > compiledmonkey at gmail.com > http://www.compiledmonkey.com For me is its simplicity and usability Python forces you to write clean codes There are a lot of modules available in web-wide that you can use IMO Python is a powerful language and a fast-develop one. Regards -------------- next part -------------- An HTML attachment was scrubbed... URL: From duncan.booth at invalid.invalid Fri Jun 1 05:51:13 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 1 Jun 2007 09:51:13 GMT Subject: Thread-safety of dict References: Message-ID: "Adam Olsen" wrote: > So there you have it: if you're using a dict with custom classes (or > anything other than str) across multiple threads, and without locking > it, it's possible (though presumably extremely rare) for a lookup to > fail even through the key was there the entire time. Nice work. It would be an interesting exercise to demonstrate this in practice, and I think it should be possible without resorting to threads (by putting something to simulate what the other thread would do into the __cmp__ method). I don't understand your reasoning which says it cannot stay in ma_smalltable: PyDict_SetItem only calls dictresize when at least 2/3 of the slots are filled. You can have 5 items in the small (8 slot) table and the dictionary will resize to 32 slots on adding the 6th,the next resize comes when you add the 22nd item. From mistabean at gmail.com Tue Jun 5 03:12:25 2007 From: mistabean at gmail.com (mistabean at gmail.com) Date: Tue, 05 Jun 2007 00:12:25 -0700 Subject: Embedding Python in C In-Reply-To: <1181025679.979188.52960@h2g2000hsg.googlegroups.com> References: <1180969118.795850.15160@w5g2000hsg.googlegroups.com> <1181025679.979188.52960@h2g2000hsg.googlegroups.com> Message-ID: <1181027545.180197.162650@m36g2000hse.googlegroups.com> now then... where's the edit button...? oh well, double-posting. Problem solved, thanks for pointing out that I am needing a numeric array built instead of building a normal list/ tuple. For those who are curious, steps to solving: ... #include "libnumarray.h" /*from numpy*/ ... ... ... void CallSnake(...) { ... ... Py_Initialize(); import_libnumarray(); /*badgered me to call this one... where i don't know*/ ... ... pArray = NA_InputArray(pArgs, tFloat32, NUM_C_ARRAY); /*instead of making a pArg and calling PyList_SetItem(pArg, 0, pArgs); */ /*Check for NULL on pArray*/ pValue = PyObject_CallFunctionObjArgs(pFunc,pArray,NULL); /*error checking, cleaning up, Finalizing etc etc*/ } From matthieutc at yahoo.com Wed Jun 13 01:11:10 2007 From: matthieutc at yahoo.com (Matthieu TC) Date: Tue, 12 Jun 2007 22:11:10 -0700 (PDT) Subject: for ... else ? Message-ID: <614073.37625.qm@web50106.mail.re2.yahoo.com> > > > On 6/12/07, Gabriel Genellina wrote: > > >> for x in iterable: > > >> do something with x > > >> else: > > >> do something when there are no more x > > > > >> You can think the above as: > > > > >> while there are still values in iterable: > > >> do something with the next value > > >> else: > > >> do something when there are no more items Also, if the for loop ends because of a break statement, the else part will never be executed.. -mats From jadestar at idiom.com Thu Jun 7 23:19:16 2007 From: jadestar at idiom.com (James T. Dennis) Date: Fri, 08 Jun 2007 03:19:16 -0000 Subject: How Can I Increase the Speed of a Large Number of Date Conversions References: <1181266113.100863.174410@q19g2000prn.googlegroups.com> Message-ID: <1181272756.711298@smirk> Some Other Guy wrote: > vdicarlo wrote: >> I am a programming amateur and a Python newbie who needs to convert >> about 100,000,000 strings of the form "1999-12-30" into ordinal dates >> for sorting, comparison, and calculations. Though my script does a ton >> of heavy calculational lifting (for which numpy and psyco are a >> blessing) besides converting dates, it still seems to like to linger >> in the datetime and time libraries. (Maybe there's a hot module in >> there with a cute little function and an impressive set of >> attributes.) > ... >> dateTuple = time.strptime("2005-12-19", '%Y-%m-%d') >> dateTuple = dateTuple[:3] >> date = datetime.date(dateTuple[0], dateTuple[1], >> dateTuple[2]) >> ratingDateOrd = date.toordinal() > There's nothing terribly wrong with that, although strptime() is overkill > if you already know the date format. You could get the date like this: > date = apply(datetime.date, map(int, "2005-12-19".split('-'))) > But, more importantly... 100,000,000 individual dates would cover 274000 > years! Do you really need that much?? You could just precompute a > dictionary that maps a date string to the ordinal for the last 50 years > or so. That's only 18250 entries, and can be computed in less than a second. > Lookups after that will be near instantaneous: For that matter why not memoize the results of each conversion (toss it in a dictionary and precede each conversion with a check like: if this_date in datecache: return datecache[this_date] else: ret=convert(this_date); datecache[this_date]=ret; return ret) (If you don't believe that will help, consider that a memo-ized implementation of a recursive Fibonacci function runs about as quickly as iterative approach). -- Jim Dennis, Starshine: Signed, Sealed, Delivered From DustanGroups at gmail.com Fri Jun 15 11:17:25 2007 From: DustanGroups at gmail.com (Dustan) Date: Fri, 15 Jun 2007 15:17:25 -0000 Subject: a_list.count(a_callable) ? In-Reply-To: <1181916937.648267.163070@z28g2000prd.googlegroups.com> References: <1181850818.567840.251090@x35g2000prf.googlegroups.com> <1181853479.914070.217270@i13g2000prf.googlegroups.com> <1181855184.511137.100870@z28g2000prd.googlegroups.com> <1181916937.648267.163070@z28g2000prd.googlegroups.com> Message-ID: <1181920645.597497.133930@m36g2000hse.googlegroups.com> On Jun 15, 9:15 am, Ping wrote: > > sum(1 for i in a_list if a_callable(i)) > > > -- > > Carsten Haesehttp://informixdb.sourceforge.net > > This works nicely but not very intuitive or readable to me. > > First of all, the generator expression makes sense only to > trained eyes. Secondly, using sum(1 ...) to mean count() > isn't very intuitive either. Then wrap it in a function: def count(a_list, a_function): return sum(1 for i in a_list if a_function(i)) And call the function. You can also give it a different name (although I can't think of a concise name that would express it any better). > I would still prefer an expression like a_list.count(a_callable), > which is short, clean, and easy to understand. :) However, > it does produce ambiguities if a_list is a list of callables. > Should the count() method match values or check return values > of a_callable? There are several possible designs but I'm not > sure which is better. Indeed, the ambiguity in that situation would be a reason *not* to introduce such behavior, especially since it would break older programs that don't recognize that behavior. Just stick with writing the function, as shown above. From lucaberto at libero.it Thu Jun 14 12:41:18 2007 From: lucaberto at libero.it (luca72) Date: Thu, 14 Jun 2007 09:41:18 -0700 Subject: qt4 setFlags Message-ID: <1181839278.482947.97230@j4g2000prf.googlegroups.com> Hello I make this code: row = self.tableWidget.rowCount() for a in range(row): self.tableWidget.item(row, 0).setFlags(Qt.IsSelectable) i have this erroror : global name Qt is not definied Regards Luca From v.davis2 at cox.net Sat Jun 9 12:59:25 2007 From: v.davis2 at cox.net (v.davis2) Date: Sat, 9 Jun 2007 09:59:25 -0700 Subject: DAO and Access97 WHERE clause fails References: Message-ID: Hello all. Thanks for the help! John pointed out to me the flaw in my code: Change: sSQL3 = 'SELECT * FROM T_Index2DirName WHERE iIndex = hsDB' to: sSQL3 = 'SELECT * FROM T_Index2DirName WHERE iIndex = %ld' % hsDB That did the trick. I had looked at the statement so often that it was *obviously* correct. John also pointed me to the DAO help file that I had not been able to find. Dennis also pointed out the correction, but went on to educate me much more on what I was trying to do. BTW, I had searched extensivly on line for the answer before posting, but was missing the obvious, stupid coding error. Thanks to all for getting me back on track! --Vic "v.davis2" wrote in message news:Okmai.403919$7g3.312911 at newsfe14.phx... > Hi all, > > I am attempting to use Access97 as the database to hold the results of a > python script. I seem to be able to make simple SELECT clauses work (like > SELECT * FROM TableName), but have not been able to figure out how to add > a WHERE clause to that (e.g., SELECT * FROM TableName WHERE myFieldName = > 34) This fails complaining that the wrong number of parameters are > present. > I haved tried DAO36 and I have tried the ADO version with the same > results. Therefore I have to conclude it is my screwup! > Help in the forum or via email would sure be appreciated! > (v.davis2 at cox.net) > > Here is the skeleton code: > > import win32com.client > daoEngine = win32com.client.Dispatch('DAO.DBEngine.35') > sDBname = 'vpyAnalyzeDirectorySize.mdb' > sDB = 'c:\\documents and settings\\vic\\my > documents\\tools\\python25\\_myscripts\\'+sDBname > daoDB = daoEngine.OpenDatabase(sDB) > > sSQL1 = 'SELECT * FROM T_Index2DirName' > daoRS = daoDB.OpenRecordset(sSQL1) # this works FINE and I can > play with the record set > > # > > hsDB = hash(sDB) > sSQL3 = 'SELECT * FROM T_Index2DirName WHERE iIndex = hsDB' # names are > all correct in mdb file > daoRStest = daoDB.OpenRecordset(sSQL3) # this FAILS, even though the > record is there > > daoRS.Close() > > > Traceback (most recent call last): > File "C:\Documents and Settings\Vic\My > Documents\Tools\python25\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py", > line 310, in RunScript > exec codeObject in __main__.__dict__ > File "C:\Documents and Settings\Vic\My > Documents\Tools\python25\_MyScripts\TestForPosting01.py", line 14, in > > daoRStest = daoDB.OpenRecordset(sSQL3) # this FAILS, even though > record is there > File "C:\Documents and Settings\Vic\My > Documents\Tools\python25\lib\site-packages\win32com\gen_py\00025E01-0000-0000-C000-000000000046x0x5x0.py", > line 523, in OpenRecordset > , Type, Options, LockEdit) > com_error: (-2147352567, 'Exception occurred.', (0, 'DAO.Database', 'Too > few parameters. Expected 1.', 'jeterr35.hlp', 5003061, -2146825227), None) > From esj at harvee.org Sun Jun 10 10:02:28 2007 From: esj at harvee.org (Eric S. Johansson) Date: Sun, 10 Jun 2007 10:02:28 -0400 Subject: Python editors again (it's not the same old request) Message-ID: I upgraded to version 9.5 and all of my tools which enabled me to program by voice in Emacs are broken. it's one of those dagnabbit a moment's of life. What I am looking for is a Windows based Python Smart editor that uses specific rich text edit controls as specified here: http://knowledgebase.nuance.com/view.asp?tnID=5104&sQuery=4247 Quoting from the article: """ A window is considered standard if its window class name is one of the following: Edit RichEdit RichEdit20A RichEdit20W RichEdit50W If the name is not one of those, then an edit control is still considered standard if its window class name and window styles are similar to those of standard edit controls. """ There is some other stuff in there about other classes that may be able to work in so far, they haven't yield anything useful to me. Doesn't mean I won't keep trying but it's more than a tad frustrating trying to root out some of these magic numbers. Any help would be most appreciated. Actually, it would be really nice if wxwindows and gtk used the standard classes underneath so accessibility would be there semiautomatically on Windows but that's a different conversation. From cam.ac.uk at mh391.invalid Fri Jun 22 05:43:12 2007 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Fri, 22 Jun 2007 10:43:12 +0100 Subject: Indenting in Emacs In-Reply-To: <87bqf8nagp.fsf@pobox.com> References: <1182415666.423187.274240@u2g2000hsc.googlegroups.com> <87bqf8nagp.fsf@pobox.com> Message-ID: John J. Lee wrote: > Eugene Morozov writes: > >> Steven W. Orr ?????: >> > Ok. I'm not stupid but I do not see a 4.78 anywhere even though I >> see refs >>> from google. I have 4.75 The SVN tree doesn't seem to even have >>> that. >>> >>> I checked the latest copy out from sourceforge and that was 4.75 too. >>> >>> Can someone please tell me where to find the latest? >>> >> It's from Emacs 22. > > Note that's a different python-mode to the old one that lives on SF. > Yes, there are now two of them. Which one is better? -- Michael Hoffman From martin at v.loewis.de Tue Jun 12 02:05:47 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 12 Jun 2007 08:05:47 +0200 Subject: Setting the encoding in the basic auth header In-Reply-To: <1181627140.208015.256160@q19g2000prn.googlegroups.com> References: <1181627140.208015.256160@q19g2000prn.googlegroups.com> Message-ID: <466E37BB.9000003@v.loewis.de> > When I enter character \xf1 as the username which is outside ascii but > within iso-8859-1 > > Firefox 2.0 sends this as \xf1 > IE 7 also sends this as \xf1 > But the utf-8 encoding is \xc3\xb1 > > If I enter character 0BA4 (TAMIL LETTER TA) which is outside > iso-8859-1 > > Firefox 2 sends this as \xa4 (seems to drop the high byte) > IE 7 sends this as ? > > It seems that both browsers are using the iso-8859-1 charset. Is there > any way I can get them to encode the data with utf-8 instead? Looking at your results, the answer seems to be "no". They don't use Latin-1, instead, they use Unicode and just drop the row byte, sending only the cell byte (independent on whether the input was Latin-1). RFC 2617 specifies userid as *TEXT, without ever specifying what TEXT is. Most likely, the authors of that specification did not consider encodings. Regards, Martin From doug at alum.mit.edu Sat Jun 30 15:23:50 2007 From: doug at alum.mit.edu (Douglas Alan) Date: Sat, 30 Jun 2007 15:23:50 -0400 Subject: Python's "only one way to do it" philosophy isn't good? References: <7xejjzmk7u.fsf@ruckus.brouhaha.com> <7xy7i7xjl5.fsf@ruckus.brouhaha.com> Message-ID: Lenard Lindstrom writes: > Explicitly clear the exception? With sys.exc_clear? Yes. Is there a problem with that? |>oug From sjdevnull at yahoo.com Fri Jun 8 03:24:52 2007 From: sjdevnull at yahoo.com (sjdevnull at yahoo.com) Date: Fri, 08 Jun 2007 00:24:52 -0700 Subject: howto obtain directory where current (running) py-file is placed? In-Reply-To: <1181198387.952428.163120@q75g2000hsh.googlegroups.com> References: <1181198387.952428.163120@q75g2000hsh.googlegroups.com> Message-ID: <1181287492.673956.157920@e65g2000hsc.googlegroups.com> dmitrey wrote: > Hi all, > I guess this question was asked many times before, but I don't know > keywords for web search. > > Thank you in advance, D. In the future, please ask your question in the body of your message (not just in the subject line). This question has no answer in general. There are some things like __file__ that may be "good enough" depending on your usage, but keep in mind in general that: 1. __file__ may be altered directly by the program and give an answer that has no past or current relationship to any filename for the file that contains the code currently being run. 2. Even if you make no changes, it can contain arbitrary results in not uncommon situations (e.g. in my local install, an interactive python session--or one from a here-document in the shell--lists ~/.pythonrc or "" in __file__, even though in neither case was I running my .pythonrc or a file named "" 3. Without that, any file may have 0, 1, or many names; those names may differ now from what they were when the file was first accessed. So __file__ may refer to an unlinked name (even in the case where at least one name that existed when you first executed the file is still valid), or may even e the name of another, different file that was created (or linked/renamed) after you started running things. Depending on your needs, those factors may or may not matter. They're certainly worth being aware of, and for some applications they may have massive security implications. From siona at chiark.greenend.org.uk Wed Jun 27 09:50:03 2007 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 27 Jun 2007 14:50:03 +0100 (BST) Subject: Too many 'self' in python.That's a big flaw in this language. References: <1182942154.185461.89620@e9g2000prf.googlegroups.com> Message-ID: <3Uk*cRjOr@news.chiark.greenend.org.uk> Neil Cerutti wrote: >On 2007-06-27, hide1713 at gmail.com wrote: >> From My point,I think this only help python interpreter to >> deside where to look for. Is there anyone know's how to make >> the interpreter find instance name space first? Or any way to >> make programmer's life easier? >Try thinking of "self." as a notation that provides vital >information to you, the programmer. And it provides even more vital information to *other* programmers dealing with your code ("other" including "you in six months time"). I've just confused the socks off a cow-orker by writing in a C++ method kill(SIGTERM); -- confusion which would have been avoided if I'd used an explicit this->kill(SIGTERM); . But amongst C++'s many flaws, such disambiguation is frowned on as non-idiomatic. Explicit self *is a good thing*. -- \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 doulos05 at gmail.com Tue Jun 5 08:46:02 2007 From: doulos05 at gmail.com (JonathanB) Date: Tue, 05 Jun 2007 05:46:02 -0700 Subject: *args and **kwargs In-Reply-To: <46655ac1$0$2892$6e1ede2f@read.cnntp.org> References: <1181046478.824231.117300@q75g2000hsh.googlegroups.com> <46655ac1$0$2892$6e1ede2f@read.cnntp.org> Message-ID: <1181047562.136896.281200@p47g2000hsd.googlegroups.com> > I hope this example code will help you understand: >>Code Snipped<< OOH!! That makes perfect sense, thanks!, *args are passed as a turple, **kwargs are passed as a dictionary. That means **kwargs is probably what I want. JonathanB From andreas_eder at gmx.net Mon Jun 25 13:23:06 2007 From: andreas_eder at gmx.net (Andreas Eder) Date: Mon, 25 Jun 2007 19:23:06 +0200 Subject: The Modernization of Emacs: terminology buffer and keybinding References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182272495.990807.99110@a26g2000pre.googlegroups.com> <87tzt3ihev.fsf@kobe.laptop> <1182370216.961241.6960@n60g2000hse.googlegroups.com> <85zm2ufjpb.fsf@lola.goethe.zz> <1182372592.803332.288260@u2g2000hsc.googlegroups.com> <5dtk4tF34jrimU1@mid.dfncis.de> <1182375388.814275.227380@n2g2000hse.googlegroups.com> <87645h73ei.fsf@W0053328.mgh.harvard.edu> <1182548563.561252.82480@i13g2000prf.googlegroups.com> Message-ID: <86abuoaqyt.fsf@eder.homelinux.net> Hi Twisted, >>>>> "Twisted" == Twisted writes: Twisted> That's entirely orthogonal to the issue of interface learning curve OR Twisted> interface ease-of-use. Emacs has deficiencies in both areas, if Twisted> principally the former. (For an example of the latter, consider Twisted> opening a file. Can't remember the exact spelling and capitalization Twisted> of the file name? Sorry, bud, you're SOL. Wrong, ever heard about input completion? Twisted> Go find it in some other app Twisted> and memorize the name, then return to emacs. Wrong. Do you know dired? For even more ease of use use someting like ido, or icicles. It runs rings about Editors like Notepad. Twisted> Now THAT is what I call Twisted> disruptive context switching. Meanwhile even the lowly Notepad Twisted> responds to "open" by displaying a list of text files and tools to Twisted> navigate the folder hierarchy without having to do it blind, while Twisted> still letting you blind-type a path if you remember it. And you can Twisted> also paste the path in from the clipboard. You can do so in emacs as well. Twisted> Unix systems don't even Twisted> *have* a proper system-wide clipboard and copy/paste capability. Under Twisted> X there's a weak, text-only imitation, which doesn't help you much Twisted> when you want to copy a selection from an image in a paint program and Twisted> paste it into a CAD or web-design or specialized image-manipulation Twisted> tool or whatever...you have to save it to a file and load it, which is Twisted> a pain in the butt and slowly clutters your hard drive with Twisted> "temporary" files you occasionally forget to delete. You obviously have no clue about working under Unix either. 'Andreas -- Wherever I lay my .emacs, there's my $HOME. From knipknap at gmail.com Fri Jun 22 02:54:12 2007 From: knipknap at gmail.com (Samuel) Date: Thu, 21 Jun 2007 23:54:12 -0700 Subject: Retrieving a stacktrace from an exception object / forwarding an exception Message-ID: <1182495252.513035.96890@m36g2000hse.googlegroups.com> Hi, I am trying to wrap a function that throws an exeption in such a way that the stacktrace is logged into a file and the exception is forwarded after that. For example: ------------------- def my_func(): raise Exception("hello") def wrapper(): try: my_func() except Exception, e: f = open("logfile", 'a') f.write(e.stacktrace()) raise e wrapper() # should throw the exception with a stacktrace showing my_func() ------------------- Any idea if and how this can be done? -Samuel From hg at nospam.org Sat Jun 9 20:38:34 2007 From: hg at nospam.org (hg) Date: Sat, 09 Jun 2007 19:38:34 -0500 Subject: pyexe "format" References: Message-ID: hg wrote: > Hi, > > Is there a clean way to figure out that a .exe was actually generated by > pyexe ? > > hg I should gave writtent "definite" instead of "clean" hg From dummy666 at mail.ru Fri Jun 22 17:20:04 2007 From: dummy666 at mail.ru (askel) Date: Fri, 22 Jun 2007 21:20:04 -0000 Subject: Python plain-text database or library that supports joins? In-Reply-To: <1182532691.182581.110940@m37g2000prh.googlegroups.com> References: <1182532691.182581.110940@m37g2000prh.googlegroups.com> Message-ID: <1182547204.703919.62440@x35g2000prf.googlegroups.com> On Jun 22, 1:18 pm, felciano wrote: > Hello -- > > Is there a convention, library or Pythonic idiom for performing > lightweight relational operations on flatfiles? I frequently find > myself writing code to do simple SQL-like operations between flat > files, such as appending columns from one file to another, linked > through a common id. For example, take a list of addresses and append > a 'district' field by looking up a congressional district from a > second file that maps zip codes to districts. > > Conceptually this is a simple database operation with a join on a > common field (zip code in the above example). Other case use other > relational operators (projection, cross-product, etc) so I'm really > looking for something SQL-like in functionality. However, the data is > in flat-files, the file structure changes frequently, the files are > dynamically generated from a range of sources, are short-lived in > nature, and otherwise not warrant the hassle of a database setup. So > I've been looking around for a nice, Pythonic, zero-config (no > parsers, no setup/teardown, etc) solution for simple queries that > handles a database of csv-files-with-headers automatically. There are > number of solutions that are close, but in the end come up short: > > - KirbyBase 1.9 (latest Python version) is the closest that I could > find, as it lets you keep your data in flatfiles and perform > operations using the field names from those text-based tables, but it > doesn't support joins (the more recent Ruby version seems to). > - Buzhug and Sqlite have their data structures w no automatic .tab > or .csv parsing (unless sqlite includes a way to map flatfiles to > sqlite virtual tables that I don't know about). > -http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/159974is > heading in the right direction, as it shows how to perform relational > operations on lists and are index based rather than field-name based. > -http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/498130andhttp://furius.ca/pubcode/pub/conf/common/bin/csv-db-import.html > provide ways of automatically populating DBs but not the reverse > (persist changes back out to the data files) > > The closest alternatives I've found are the GNU textutils that support > join, cut, merge, etc but I need to add additional logic they don't > support, nor do they allow field-level write operations from Python > (UPDATE ... WHERE ...). Normally I'd jump right in and start coding > but this seems like something so common that I would have expected > someone else to have solved, so in the interest of not re-inventing > the wheel I thought I'd see if anyone had any other suggestions. Any > thoughts? > > Thanks! > > Ramon ramon, i don't think that using flat text files as a database is common these days. if you need relational database features what stops you from using rdbms? if the only reason for that is some legacy system then i'd still use in-memory sqlite database for all relational operations. import, process, export back to text if you need to. From cp.finances.gouv at gmail.com Thu Jun 28 05:07:43 2007 From: cp.finances.gouv at gmail.com (cp.finances.gouv at gmail.com) Date: Thu, 28 Jun 2007 02:07:43 -0700 Subject: urllib2 : https and proxy Message-ID: <1183021663.053143.275090@q69g2000hsb.googlegroups.com> Hello all, I'm facing a strange behavior of urllib2 trying to access gmail account behind a proxy (Squid). The following works perfectly : wget --save-cookies cookies --keep-session-cookies --post- data="Email=externe.finances.gouv at gmail.com&Passwd=cpfinances" --no- check-certificate -O - https://www.google.com/accounts/ServiceLoginBoxAuth While the following urllib2 code fail with an error 501 : In [18]: import urllib2 In [19]: r=urllib2.urlopen("https://www.google.com/accounts/ ServiceLoginBoxAuth", "Email=externe.finances.gouv at gmail.com&Passwd=cpfinances") --------------------------------------------------------------------------- urllib2.HTTPError Traceback (most recent call last) /home/maric/ /home/maric/urllib2.py in urlopen(url, data) 128 if _opener is None: 129 _opener = build_opener() --> 130 return _opener.open(url, data) ... /home/maric/urllib2.py in http_error_default(self, req, fp, code, msg, hdrs) 478 class HTTPDefaultErrorHandler(BaseHandler): 479 def http_error_default(self, req, fp, code, msg, hdrs): --> 480 raise HTTPError(req.get_full_url(), code, msg, hdrs, fp) 481 482 class HTTPRedirectHandler(BaseHandler): HTTPError: HTTP Error 501: Not Implemented I understood it's a response from the proxy about incompatible protocols and queries but this seem rather strange in this case. Could there be a bug in the ProxyHandler class ? Any idea about what could cause this error on the proxy ? From joswig at corporate-world.lisp.de Sun Jun 24 19:00:17 2007 From: joswig at corporate-world.lisp.de (joswig at corporate-world.lisp.de) Date: Sun, 24 Jun 2007 16:00:17 -0700 Subject: The Modernization of Emacs: terminology buffer and keybinding In-Reply-To: References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182272495.990807.99110@a26g2000pre.googlegroups.com> <87tzt3ihev.fsf@kobe.laptop> <1182370216.961241.6960@n60g2000hse.googlegroups.com> <85zm2ufjpb.fsf@lola.goethe.zz> <1182372592.803332.288260@u2g2000hsc.googlegroups.com> <5dtk4tF34jrimU1@mid.dfncis.de> <1182375388.814275.227380@n2g2000hse.googlegroups.com> <87645h73ei.fsf@W0053328.mgh.harvard.edu> <1182548563.561252.82480@i13g2000prf.googlegroups.com> <1182666078.511962.280030@w5g2000hsg.googlegroups.com> Message-ID: <1182726017.459967.67280@m36g2000hse.googlegroups.com> On 25 Jun., 00:52, Robert Uhl wrote: You guys are all in the wrong newsgroups. Please stay in comp.emacs when discussing Emacs. Don't cross post. Not everyone is interested in Emacs discussions. Thanks. Follow-up set to comp.emacs. From stefan.sonnenberg at pythonmeister.com Tue Jun 19 16:50:51 2007 From: stefan.sonnenberg at pythonmeister.com (Stefan Sonnenberg-Carstens) Date: Tue, 19 Jun 2007 22:50:51 +0200 Subject: How can I know the name of "caller" In-Reply-To: <1182285024.048003.310120@n2g2000hse.googlegroups.com> References: <1182285024.048003.310120@n2g2000hse.googlegroups.com> Message-ID: <467841AB.10406@pythonmeister.com> billiejoex schrieb: > Hi there, > unfortunately, I'm compelled to apply a sort of monkey patching at the > code of an existing libreary that I can't modify directly. > Here's my question > Having such code: > > class test: > > def caller(self): > self.b() > > def called(self): > pass > > ...(if it is possible) how can I get, from method "called", the name > of function/method that called it (in this case "caller")? > > Thanks in advance > > inspect.stack is your friend ;-) From sjdevnull at yahoo.com Thu Jun 28 04:43:13 2007 From: sjdevnull at yahoo.com (sjdevnull at yahoo.com) Date: Thu, 28 Jun 2007 01:43:13 -0700 Subject: PEP 3107 and stronger typing (note: probably a newbie question) In-Reply-To: References: <1182369568.941307.316260@p77g2000hsh.googlegroups.com> <5dveb4F360un0U1@mid.individual.net> <467a9209$0$22165$426a74cc@news.free.fr> <1182858785.886469.93060@n60g2000hse.googlegroups.com> <46824d8d$0$2324$426a74cc@news.free.fr> <4682eddc$0$23164$426a74cc@news.free.fr> Message-ID: <1183020193.278917.297050@c77g2000hse.googlegroups.com> Stephen R Laniel wrote: > On Thu, Jun 28, 2007 at 09:08:16AM +0200, Bruno Desthuilliers wrote: > > You said ? > > I could link again to Mark-Jason Dominus, who writes that > people often make the following inference: > > 1) C is strongly typed. > 2) C's typing sucks. > 3) Hence strong typing sucks. > > But I won't. > > It doesn't need to be a religious war. Why can't people just > say "When strong typing is done and used well, it's a > useful tool; when it's not, it's not"? Python already has strong typing, much stronger than C and arguably stronger than Java. What it doesn't have is static typing, which is good--that's one of the defining characteristics of the language, and dynamic languages have a lot to recommend them. ML and Haskell are also great languages, but they're great in a very different way. Lisp probably comes closest to a useful dynamic/static hybrid, but there the static annotations are pretty much only for the compiler's benefit, not the programmer's. From phil at riverbankcomputing.co.uk Wed Jun 6 04:39:11 2007 From: phil at riverbankcomputing.co.uk (Phil Thompson) Date: Wed, 6 Jun 2007 09:39:11 +0100 Subject: qpushbutton In-Reply-To: <1181118779.537727.27640@q69g2000hsb.googlegroups.com> References: <1181118779.537727.27640@q69g2000hsb.googlegroups.com> Message-ID: <200706060939.11260.phil@riverbankcomputing.co.uk> On Wednesday 06 June 2007 9:32 am, luca72 wrote: > hello again > i have another stupid question. > How i can set a qpushbutton invisible? > thanks Luca Call its hide() method. Phil From jritter at prairiegames.com Thu Jun 7 15:33:41 2007 From: jritter at prairiegames.com (Josh Ritter) Date: Thu, 7 Jun 2007 14:33:41 -0500 Subject: Python 2.5.1 - sqlite3.dll issue Message-ID: <004401c7a93a$c1912260$0400000a@spooge> A number of our Windows customers have an issue with the sqlite3 module included with Python 2.5.1 We've tracked the problem down to the sqlite3.dll included with the Python 2.5.1 distrubtion. It is stripped and thus cannot be relocated. This causes the following exception on computers where something is already loaded into the address the sqlite3.dll wants to use: File "sqlite3\__init__.pyc", line 24, in File "sqlite3\dbapi2.pyc", line 27, in ImportError: DLL load failed: Invalid access to memory location. I downloaded the latest sqlite3.dll from http://www.sqlite.org and this fixes the problem. (This dll isn't stripped) ------------------------------------ -Josh Ritter President Prairie Games, Inc http://www.prairiegames.com From sturlamolden at yahoo.no Mon Jun 4 07:32:42 2007 From: sturlamolden at yahoo.no (sturlamolden) Date: Mon, 04 Jun 2007 04:32:42 -0700 Subject: another thread on Python threading In-Reply-To: References: <1180906374.041535.296410@k79g2000hse.googlegroups.com> Message-ID: <1180956762.091381.274750@p47g2000hsd.googlegroups.com> On Jun 4, 3:10 am, Josiah Carlson wrote: > cgwalt... at gmail.com wrote: > > I've recently been working on an application[1] which does quite a bit > > of searching through large data structures and string matching, and I > > was thinking that it would help to put some of this CPU-intensive work > > in another thread, but of course this won't work because of Python's > > GIL. > > If you are doing string searching, implement the algorithm in C, and > call out to the C (remembering to release the GIL). > > > There's a lot of past discussion on this, and I want to bring it up > > again because with the work on Python 3000, I think it is worth trying > > to take a look at what can be done to address portions of the problem > > through language changes. > > Not going to happen. All Python 3000 PEPs had a due-date at least a > month ago (possibly even 2), so you are too late to get *any* > substantial change in. > > > I remember reading (though I can't find it now) one person's attempt > > at true multithreaded programming involved adding a mutex to all > > object access. The obvious question though is - why don't other true > > multithreaded languages like Java need to lock an object when making > > changes? > > From what I understand, the Java runtime uses fine-grained locking on > all objects. You just don't notice it because you don't need to write > the acquire()/release() calls. It is done for you. (in a similar > fashion to Python's GIL acquisition/release when switching threads) The problem is CPython's reference counting. Access to reference counts must be synchronized. Java, IronPython and Jython uses another scheme for the garbage collector and do not need a GIL. Changing CPython's garbage collection from reference counting to a generational GC will be a major undertaking. There are also pros and cons to using reference counts instead of 'modern' garbage collectors. For example, unless there are cyclic references, one can always know when an object is garbage collected. One also avoids periodic delays when garbage are collected, and memory use can be more modest then a lot of small temporary objects are being used. Also beware that the GIL is only a problem for CPU bound code. IO bound code is not slowed by the GIL. The Python runtime itself is a bigger problem for CPU bound code. In C or Fortran, writing parallell algorithms for multiprocessor systems typically involves using OpenMP or MPI. Parallelizing algorithms using manual threading should be discouraged. It is far better to insert a compiler directive (#pragma omp) and let an OpenMP compiler to the job. There are a number of different options for exploiting multiple CPUs from CPython, including: - MPI (e.g. mpi4py or PyMPI) - PyPar - os.fork() on Linux or Unix - subprocess.Popen - C extensions that use OpenMP - C extensions that spawn threads (should be discouraged!) > They also have a nice little decorator-like thingy (I'm not a Java guy, > so I don't know the name exactly) called 'synchronize', which locks and > unlocks the object when accessing it through a method. A similar Python 'synchronized' function decorator may look like this: def synchronized(fun): from threading import RLock rl = RLock() def decorator(*args,**kwargs): with rl: retv = fun(*args,**kwargs) return retv return decorator It is not possible to define a 'synchronized' block though, as Python do not have Lisp macros :( > > - Josiah > > > == Why hasn't __slots__ been successful? == > > > I very rarely see Python code use __slots__. I think there are > > several reasons for this. The first is that a lot of programs don't > > need to optimize on this level. The second is that it's annoying to > > use, because it means you have to type your member variables *another* > > time (in addition to __init__ for example), which feels very un- > > Pythonic. > > > == Defining object attributes == > > > In my Python code, one restriction I try to follow is to set all the > > attributes I use for an object in __init__. You could do this as > > class member variables, but often I want to set them in __init__ > > anyways from constructor arguments, so "defining" them in __init__ > > means I only type them once, not twice. > > > One random idea is to for Python 3000, make the equivalent of > > __slots__ the default, *but* instead gather > > the set of attributes from all member variables set in __init__. For > > example, if I write: > > > class Foo(object): > > def __init__(self, bar=None): > > self.__baz = 20 > > if bar: > > self.__bar = bar > > else: > > self.__bar = time.time() > > > f = Foo() > > f.otherattr = 40 # this would be an error! Can't add random > > attributes not defined in __init__ > > > I would argue that the current Python default of supporting adding > > random attributes is almost never what you really want. If you *do* > > want to set random attributes, you almost certainly want to be using a > > dictionary or a subclass of one, not an object. What's nice about the > > current Python is that you don't need to redundantly type things, and > > we should preserve that while still allowing more efficient > > implementation strategies. > > > = Limited threading = > > > Now, I realize there are a ton of other things the GIL protects other > > than object dictionaries; with true threading you would have to touch > > the importer, the garbage collector, verify all the C extension > > modules, etc. Obviously non-trivial. What if as an initial push > > towards real threading, Python had support for "restricted threads". > > Essentially, restricted threads would be limited to a subset of the > > standard library that had been verified for thread safety, would not > > be able to import new modules, etc. > > > Something like this: > > > def datasearcher(list, queue): > > for item in list: > > if item.startswith('foo'): > > queue.put(item) > > queue.done() > > > vals = ['foo', 'bar'] > > queue = queue.Queue() > > threading.start_restricted_thread(datasearcher, vals, queue) > > def print_item(item): > > print item > > queue.set_callback(print_item) > > > Making up some API above I know, but the point here is "datasearcher" > > could pretty easily run in a true thread and touch very little of the > > interpreter; only support for atomic reference counting and a > > concurrent garbage collector would be needed. > > > Thoughts? > > > [1]http://submind.verbum.org/hotwire/wiki From showell30 at yahoo.com Fri Jun 1 07:00:21 2007 From: showell30 at yahoo.com (Steve Howell) Date: Fri, 1 Jun 2007 04:00:21 -0700 (PDT) Subject: file reading by record separator (not line by line) In-Reply-To: <465ff8d3$0$79139$e4fe514c@news.xs4all.nl> Message-ID: <762531.46409.qm@web33509.mail.mud.yahoo.com> --- Tijs wrote: > > Yes, or a single one that takes a wide range of > construction possibilities, > like strings, lambdas or regexes in various keyword > parameters. > > BlockReader(f, start='>') > BlockReader(f, start=re.compile('>|<'), end='---') > BlockReader(f, start=lambda x: x.startswith('>')) > Definitely. I like your idea for regexes that you just pass the method in, rather than the regex. It means fewer variations, and it also leads to slightly more explicit code from the user, without being too cumbersome. Do you have any free time on your hands? It seems like it would be fairly straightforward to do a quick prototype implementation of this. I'm off to work soon, so I can't do it today, but maybe Sunday. ____________________________________________________________________________________ Take the Internet to Go: Yahoo!Go puts the Internet in your pocket: mail, news, photos & more. http://mobile.yahoo.com/go?refer=1GNXIC From cai.haibin at gmail.com Tue Jun 5 21:24:33 2007 From: cai.haibin at gmail.com (james_027) Date: Wed, 06 Jun 2007 01:24:33 -0000 Subject: excel library without COM In-Reply-To: <1181038622.683273.268460@x35g2000prf.googlegroups.com> References: <1180918791.467050.186520@r19g2000prf.googlegroups.com> <1180936346.272773.162540@q66g2000hsg.googlegroups.com> <1180959384.545415.102340@n15g2000prd.googlegroups.com> <1181012679.069496.178870@j4g2000prf.googlegroups.com> <1181038622.683273.268460@x35g2000prf.googlegroups.com> Message-ID: <1181093073.839020.14390@r19g2000prf.googlegroups.com> On Jun 5, 6:17 pm, John Machin wrote: > On Jun 5, 1:04 pm, james_027 wrote: > > > > > On Jun 4, 8:16 pm, John Machin wrote: > > > > On Jun 4, 3:52 pm, yuce wrote: > > > > > i think this one works pretty nice:http://www.python.org/pypi/xlrd > > > > Sure does :-) However the "rd" in "xlrd" is short for "ReaD". As > > > Waldemar suggested, "xlwt" ("wt" as in WriTe) is more like what the OP > > > needs. > > > > Cheers, > > > John > > > Thanks to all who have contributed. I have one concern though. Many of > > the module seems to be not active anymore? or updated? It is because > > it really stable and has most of the features needed? > > xlwt is active, stable enough for heavy use, and will get a public > outing Real Soon Now (after xlrd 0.6.1 final, which is expected Truly > Rooly Real Soon Now). Thanks a John Now my searching is over From gagsl-py2 at yahoo.com.ar Mon Jun 25 22:17:03 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 25 Jun 2007 23:17:03 -0300 Subject: regular expressions eliminating filenames of type foo.thumbnail.jpg References: <1182746933.413693.103860@p77g2000hsh.googlegroups.com> <1182747645.092002.68800@x35g2000prf.googlegroups.com> <1182750220.486035.298890@o11g2000prd.googlegroups.com> <1182807664.730854.28160@g37g2000prf.googlegroups.com> <1182811952.103263.107720@g37g2000prf.googlegroups.com> Message-ID: En Mon, 25 Jun 2007 19:52:32 -0300, oscartheduck escribi?: > Well, darn. > > I just discovered that the computer this is going to run on only has > python version 2.2 installed on it, which apparently doesn't support > checking a whole word, but instead checks a single letter against > other single letters. 2.4 and, presumably 2.5 though I've actually not > used it much, has such huge leaps forwards relative to 2.2 that it's > frightening thinking about where the language is going. > > But for now, I'm going to have to work on this problem again from > scratch, it seems. You can still use a regular expression: thumbnailRx = re.compile(r"\.thumbnail\.") for picture in [... and filenameRx.match(p) and not thumbnailRx.search(p)]: >> >> def thumbnailer(dir, filenameRx): >> for picture in [ p for p in os.listdir(dir) if >> os.path.isfile(os.path.join( >> dir,p)) and filenameRx.match(p) if 'thumbnail' not in p]: >> file, ext = os.path.splitext(picture) -- Gabriel Genellina From showell30 at yahoo.com Sat Jun 2 12:12:54 2007 From: showell30 at yahoo.com (Steve Howell) Date: Sat, 2 Jun 2007 09:12:54 -0700 (PDT) Subject: file reading by record separator (not line by line) Message-ID: <948292.40489.qm@web33504.mail.mud.yahoo.com> --- Steve Howell wrote: > > Can I suggest a minor optimization? > > Instead of this... > > def get_predicate(arg): > return arg if callable(arg) else ( > arg.__eq__ if hasattr(arg,'__eq__') > else > lambda item: item == arg) > Never mind, I understand what you're doing now. The "arg" variable through me off, so I'll make the even more minor suggestion that a better variable name might help here. Perhaps "delim"? ____________________________________________________________________________________ Get the free Yahoo! toolbar and rest assured with the added security of spyware protection. http://new.toolbar.yahoo.com/toolbar/features/norton/index.php From jo at durchholz.org Tue Jun 12 03:50:14 2007 From: jo at durchholz.org (Joachim Durchholz) Date: Tue, 12 Jun 2007 09:50:14 +0200 Subject: The Concepts and Confusions of Prefix, Infix, Postfix and Fully Functional Notations In-Reply-To: <1181616725.678833.104690@n15g2000prd.googlegroups.com> References: <1179936917.652372.24780@q69g2000hsb.googlegroups.com> <1180508453.226022.44230@q19g2000prn.googlegroups.com> <1181335574.107472.229370@x35g2000prf.googlegroups.com> <1181358616.792797.97720@k79g2000hse.googlegroups.com> <1181414625.121073.203940@g4g2000hsf.googlegroups.com> <0uHai.176367$nh4.13819@newsfe20.lga> <1181448558.120521.63250@g4g2000hsf.googlegroups.com> <0G_ai.1970$xg4.809@trnddc08> <1181525392.369255.138460@h2g2000hsg.googlegroups.com> <1181545345.788665.191690@q66g2000hsg.googlegroups.com> <1181597817.867161.10510@h2g2000hsg.googlegroups.com> <1181616725.678833.104690@n15g2000prd.googlegroups.com> Message-ID: Twisted schrieb: > On Jun 11, 5:36 pm, Tim Bradshaw wrote: >> I think it's just obvious that this is the case. What would *stop* >> you writing maintainable Perl? > > For starters, the fact that there are about six zillion obscure > operators represented by punctuation marks, instead of a dozen or so. > More generally, the fact that it comes out looking like modem barf, > and modem barf is unmaintainable. ;) You can write Perl that uses just a dozen or so punctuation marks, so that doesn't stop you (or anybody else) from writing maintainable Perl. You haven't looked into the Webmin code that I gave for an example, have you? You'd have seen code that's quite far from line noise. (But sticking with prejudice can be more fun, I know...) If anything, the real criticism is that it's easy to write unmaintainable Perl, so there's too much of unmaintainable Perl around. The other criticism is that Perl's learning curve is needlessly prolonged because you need time to pick up all those idioms that are possible - nice for those who're doing Perl and just Perl, horror for those who usually work in other languages. I don't know of any other serious design flaws in the language, given its design goals. (When designing a scripting/glue language today, I'd set up slightly different design goals, of course. Perl is far from the optimum that should be used today, its main merits are its ubiquity and completeness, not the language qualities.) Regards, Jo From showell30 at yahoo.com Sun Jun 10 18:57:56 2007 From: showell30 at yahoo.com (Steve Howell) Date: Sun, 10 Jun 2007 15:57:56 -0700 (PDT) Subject: Python in the Mozilla world In-Reply-To: Message-ID: <695961.59234.qm@web33503.mail.mud.yahoo.com> --- "Eric S. Johansson" wrote: > Steve Howell wrote: > > --- "Eric S. Johansson" wrote: > > > http://www.voidspace.org.uk/python/weblog/arch_d7_2007_04_28.shtml#e702 > >> interesting. Very interesting but I suspect the > >> message is "don't hold your > >> breath but don't give up hope." > >> > > > > Exactly. :) > > This is one of those things where a foundation, with > a smart person for making > really simple things should get some money from the > foundation and get it built. Well, this is a case where smart people (including Jim Hugunin) are getting some money from Microsoft, which probably still has more dollars to spend than the average foundation. And some really smart people in the open source world (Miguel de Icaza, etc.) are tracking to it, according to the article. As far as "really simple things" goes, it doesn't really fit in that category. As much as I love Python, though, I still think the future of browser-side programming for the next five or ten years is Javascript, and I think the real productivity gains are going to come when Javascript libraries mature, it becomes more common knowledge which libraries are best of breed, etc. ____________________________________________________________________________________ Luggage? GPS? Comic books? Check out fitting gifts for grads at Yahoo! Search http://search.yahoo.com/search?fr=oni_on_mail&p=graduation+gifts&cs=bz From mccredie at gmail.com Thu Jun 14 11:13:58 2007 From: mccredie at gmail.com (Matimus) Date: Thu, 14 Jun 2007 15:13:58 -0000 Subject: Method much slower than function? In-Reply-To: <1371gc8ghsjj8bb@corp.supernews.com> References: <1181781612.939800.238890@q19g2000prn.googlegroups.com> <1371gc8ghsjj8bb@corp.supernews.com> Message-ID: <1181834038.053328.239760@g37g2000prf.googlegroups.com> > The first time you read the file, it has to read it from disk. > The second time, it's probably just reading from the buffer > cache in RAM. I can verify this type of behavior when reading large files. Opening the file doesn't take long, but the first read will take a while (multiple seconds depending on the size of the file). When the file is opened a second time, the initial read takes significantly less time. Matt From steveo at syslang.net Thu Jun 21 08:47:42 2007 From: steveo at syslang.net (Steven W. Orr) Date: Thu, 21 Jun 2007 08:47:42 -0400 (EDT) Subject: Indenting in Emacs In-Reply-To: References: <1182415666.423187.274240@u2g2000hsc.googlegroups.com> Message-ID: On Thursday, Jun 21st 2007 at 10:11 +0100, quoth Michael Hoffman: =>eugene.morozov at gmail.com wrote: =>> Hello, =>> Does anyone know how to make python-mode correctly indent nested lists =>> and dictionaries. I hate indenting Django url patterns and Zope =>> Archetypes schemas by hand, because python-mode indents them in =>> incorrect and ugly way. =>> =>> Here's how it should be: =>> StringField('reference', =>> widget=StringWidget( =>> description='Position reference' =>> )), =>> =>> Here's how python-mode indents this code: =>> schema = BaseSchema.copy() + Schema(( =>> StringField('reference', =>> widget=StringWidget( =>> description='Position reference' =>> )), => =>I get: => =>schema = BaseSchema.copy() + Schema(( => StringField('reference', => widget=StringWidget( => description='Position reference' => )), => =>I'm using py-version "$Revision$." Oops! Anyway, try to install the =>latest python-mode, whatever that is, if it isn't 4.78. Ok. I'm not stupid but I do not see a 4.78 anywhere even though I see refs from google. I have 4.75 The SVN tree doesn't seem to even have that. I checked the latest copy out from sourceforge and that was 4.75 too. Can someone please tell me where to find the latest? -- Time flies like the wind. Fruit flies like a banana. Stranger things have .0. happened but none stranger than this. Does your driver's license say Organ ..0 Donor?Black holes are where God divided by zero. Listen to me! We are all- 000 individuals! What if this weren't a hypothetical question? steveo at syslang.net From http Sat Jun 9 22:02:29 2007 From: http (Paul Rubin) Date: 09 Jun 2007 19:02:29 -0700 Subject: urllib2 - iteration over non-sequence References: <1181427526.996101.75230@m36g2000hse.googlegroups.com> <466B2AA7.3040704@websafe.com> <1181429903.533207.105730@p77g2000hsh.googlegroups.com> Message-ID: <7x3b10pnwq.fsf@ruckus.brouhaha.com> Erik Max Francis writes: > This is really wasteful, as there's no point in reading in the whole > file before iterating over it. To get the same effect as file > iteration in later versions, use the .xreadlines method:: > > for line in aFile.xreadlines(): > ... Ehhh, a heck of a lot of web pages don't have any newlines, so you end up getting the whole file anyway, with that method. Something like for line in iter(lambda: aFile.read(4096), ''): ... may be best. From steve at holdenweb.com Fri Jun 1 07:18:21 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 01 Jun 2007 07:18:21 -0400 Subject: HTML Form/Page and Navigation with multiple buttons In-Reply-To: <465fcb6d$0$29304$426a34cc@news.free.fr> References: <1180617750.709628.180070@p77g2000hsh.googlegroups.com> <465edbfa$0$784$426a34cc@news.free.fr> <1180624671.896662.174390@m36g2000hse.googlegroups.com> <465fcb6d$0$29304$426a34cc@news.free.fr> Message-ID: Bruno Desthuilliers wrote: > Steve Holden a ?crit : >> mosscliffe wrote: > (snip) >>> Why is a link better than a button ? >>> >> Beats me why you got that advice. Buttons are perfectly adequate for >> that purpose. > > Call me a purist if you want, but I don't think forms and buttons are > "perfectly adequate" for normal navigation, which should be handled by > links. And FWIW, except for one of the worsts PHP portal in the world, > everybody uses links for navigation. > >> However, you can if you want use links with "javascript: ..." href >> values to accomplish local scripting which can do funky stuff like >> setting form field values and submitting the form. > > Yuck. Anyone doing such a thing should be fired immediatly. > > Steve, I'm not sure you quite got what it's all about : the OP wants to > *paginate* search results. Not to submit data to the server. It's just > normal navigation, and there is absolutely *no* reason to use anything > else than plain old links here. > > My 2 cents. > You're right, the English was contorted enough for me to miss the point. Buttons do seem a bit unnecessary, even to someone who hasn't drunk the REST Kool-Aid. Yet. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden ------------------ Asciimercial --------------------- Get on the web: Blog, lens and tag your way to fame!! holdenweb.blogspot.com squidoo.com/pythonology tagged items: del.icio.us/steve.holden/python All these services currently offer free registration! -------------- Thank You for Reading ---------------- From http Tue Jun 26 15:14:42 2007 From: http (Paul Rubin) Date: 26 Jun 2007 12:14:42 -0700 Subject: Internals and complexity of types, containers and algorithms References: <468034b8$0$22922$9b622d9e@news.freenet.de> Message-ID: <7x4pkuil3x.fsf@ruckus.brouhaha.com> "Martin v. L?wis" writes: > Amortized O(1) for inserting into lists. I think you mean amortized O(1) for appending to lists. From gluckj at gmail.com Sat Jun 30 22:31:28 2007 From: gluckj at gmail.com (gluckj at gmail.com) Date: Sat, 30 Jun 2007 19:31:28 -0700 Subject: shelve crashing under Win ME In-Reply-To: References: <1183193535.127098.299840@a26g2000pre.googlegroups.com> <200706301007.29992.inq1ltd@verizon.net> Message-ID: <1183257088.085647.280010@z28g2000prd.googlegroups.com> Hi Jim, Thanks for your messages -- however, py2exe is NOT the issue -- as you can see with my example above, shelve is crashing even just by calling it from IDLE (latest PC version of IDLE & Python), running on a Win ME machine. Anyone else out there having access to a Win ME PC willing to try it? Thanks for checking! In the meantime, I may replace shelve with a simpler workaround using cPickle & basic flat file operations. -- Joel p.s. -- Jim, I too had to import dbhash in my program to make it work using py2exe, so you are right on, there. From cor at clsnet.nl Wed Jun 20 17:56:17 2007 From: cor at clsnet.nl (Cor Gest) Date: 20 Jun 2007 21:56:17 +0000 Subject: The Modernization of Emacs: terminology buffer and keybinding References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182272495.990807.99110@a26g2000pre.googlegroups.com> <87tzt3ihev.fsf@kobe.laptop> <1182370216.961241.6960@n60g2000hse.googlegroups.com> Message-ID: <87wsxyffy6.fsf@telesippa.clsnet.nl> Some entity, AKA Twisted , wrote this mindboggling stuff: (selectively-snipped-or-not-p) > On the other hand, being actively beginner-hostile leads to nobody > adopting the tool. Then again, if you don't mind being the last > generation that'll ever use it, then I guess you're okay with that. If > it suits its existing users, the rest of us will just continue to use > something else. > I continue to suspect that there's an ulterior motive for making and > keeping certain software actively beginner-hostile; a certain macho > elitism also seen with light aircraft pilots and commented on at > www.asktog.com (exact URL escapes me; sorry). Of course! real tools are not for wannabees. Just like there are a lot of people that have a shed full off the most modern power-tools that money can buy from the local DIY-Market, but cannot build a chickencoop if their life depended on it. If you are to lazy to learn how to use any tool, it will not serve you in any usefull manner. But if you are to dumb to grok it, it's useless anyway. Cor -- (defvar MyComputer '((OS . "GNU/Emacs") (IPL . "GNU/Linux"))) The biggest problem LISP has, is that it does not appeal to dumb people If that fails to satisfy read the HyperSpec, woman frig or Tuxoharata mailpolicy @ http://www.clsnet.nl/mail.php From kw at codebykevin.com Sat Jun 2 14:16:07 2007 From: kw at codebykevin.com (Kevin Walzer) Date: Sat, 02 Jun 2007 14:16:07 -0400 Subject: Non-blocking subprocess call Message-ID: <442be$4661b3e7$4275d90a$6641@FUSE.NET> I'm currently using os.popen in an application of mine, which calls for non-blocking data, in this fashion: self.file = os.popen('echo %s | sudo -S /sw/bin/fink -y install %s' % (self.passtext, self.packagename), 'r', os.O_NONBLOCK) What is the equivalent/comparable call in the new subprocess module? I can't find any reference in the Python docs to non-blocking streams. -- Kevin Walzer Code by Kevin http://www.codebykevin.com From Allen.Chenal at gmail.com Tue Jun 12 05:54:06 2007 From: Allen.Chenal at gmail.com (Allen) Date: Tue, 12 Jun 2007 02:54:06 -0700 Subject: How can I parse False from c extension? In-Reply-To: References: <1181635633.091625.23100@x35g2000prf.googlegroups.com> Message-ID: <1181642046.850984.74930@z28g2000prd.googlegroups.com> On 6 12 , 5 21 , "Gabriel Genellina" wrote: > En Tue, 12 Jun 2007 05:07:13 -0300, Allen > escribi?: > > >> From python command, I call C extension method > >>>> import PyRPC > >>>> PyRPC.addBool(False) > > > In C extension, I know parse integer value like this: > > PyArg_ParseTuple(args, "i", &nValue); > > > But, how can I parse the False value? > > Parse them as integers, with False==0 and True==1. > > -- > Gabriel Genellina Thanks! It does work. From vinay_sajip at yahoo.co.uk Wed Jun 13 14:17:12 2007 From: vinay_sajip at yahoo.co.uk (Vinay Sajip) Date: Wed, 13 Jun 2007 11:17:12 -0700 Subject: logging module and threading In-Reply-To: <1181694483.996767@smirk> References: <1181694483.996767@smirk> Message-ID: <1181758632.869050.299260@j4g2000prf.googlegroups.com> On Jun 13, 1:28 am, "James T. Dennis" wrote: > This sounds like a job for the Queue class/module to me. > Could you create a Queue such that all your worker threads > are producers to it and you have one dedicated thread as a > consumer that relays log entries from the Queue into your loggers? Or, use a SocketHandler to serialize the events over a socket, and de- mux them on the receiving end. The docs have an example: http://docs.python.org/lib/network-logging.html Regards, Vinay Sajip From spamspam at spam.eggs Thu Jun 14 17:30:43 2007 From: spamspam at spam.eggs (Ben C) Date: Thu, 14 Jun 2007 16:30:43 -0500 Subject: MS Word parser References: <1181693045.105981.169500@q19g2000prn.googlegroups.com> <1181753268.002789.138000@i38g2000prf.googlegroups.com> Message-ID: On 2007-06-13, kenicheema at gmail.com wrote: > On Jun 13, 1:28 am, Tim Golden wrote: >> keniche... at gmail.com wrote: >> > Hi all, >> > I'm currently using antiword to extract content from MS Word files. >> > Is there another way to do this without relying on any command prompt >> > application? >> >> Well you haven't given your environment, but is there >> anything to stop you from controlling Word itself via >> COM? I'm no Word expert, but looking around, this >> seems to work: >> >> >> import win32com.client >> word = win32com.client.Dispatch ("Word.Application") >> doc = word.Documents.Open ("c:/temp/temp.doc") >> text = doc.Range ().Text >> >> open ("c:/temp/temp.txt", "w").write (text.encode ("UTF-8")) >> >> >> TJG > > Tim, > I'm on Linux (RedHat) so using Word is not an option for me. Any > other suggestions? There is OpenOffice which has a Python API to it (called UNO). But piping through antiword is probably easier. From bruno.42.desthuilliers at wtf.websiteburo.oops.com Thu Jun 21 03:10:04 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Thu, 21 Jun 2007 09:10:04 +0200 Subject: Split file into several and reformat In-Reply-To: References: Message-ID: <467a243b$0$23944$426a74cc@news.free.fr> bomber71 at aapt.net.au a ?crit : > Hi, > > I want to take read an input file (sels.txt) that looks like: > (snip) > > And turn it into an output file for each of the "sels" in the input file, i.e > sel1.txt: > (snip) > and sel2.txt: > (snip) > And so on. Yes, fine. All this is documented here: http://www.catb.org/~esr/faqs/smart-questions.html#before > Many thanks, You're welcome. From m.re at sesyt.com Wed Jun 6 14:19:31 2007 From: m.re at sesyt.com (Marco) Date: Wed, 06 Jun 2007 11:19:31 -0700 Subject: generating a wm5 executable Message-ID: <1181153971.483189.183610@x35g2000prf.googlegroups.com> Hi, I'm quite a newbee on Python and have started developing apps on PythonCE. My .pyc files are running fine under windows mobile 5 but I'm a bit stuck on how to generate single file executable packages under such platform, nor I've found a lot of reference about it - seems to be quite a niche. Can I run py2exe runs under wm5? Any other suggestion? Thanks in advance Marco From bj_666 at gmx.net Wed Jun 6 06:34:38 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Wed, 06 Jun 2007 12:34:38 +0200 Subject: overriding setting References: Message-ID: In , Francesco Guerrieri wrote: > Now the question is this: > I would like to initialize such an object in this way: > a = myList() > a = [[1, 2, 3], [4, 5, 6, 7]] > a.pad() > # and now a _should_ contain [[1, 2, 3, ""], [4, 5, 6, 7]] > > > Obviously this doesn't work, because when at the second line I do the > initialization, type(a) becomes , and so I get the > expected AttributeError since pad cannot be found. You don't initialize in the second line, you just rebind `a` to a completely different object. Names don't have types in Python, objects do. `list()` takes an optional argument. Just make sure your derived type does to and passes this to the base class `__init__()`. Then you can create an instance like this: a = MyList([[1, 2, 3], [4, 5, 6, 7]]) Ciao, Marc 'BlackJack' Rintsch From attn.steven.kuo at gmail.com Wed Jun 27 19:52:57 2007 From: attn.steven.kuo at gmail.com (attn.steven.kuo at gmail.com) Date: Wed, 27 Jun 2007 16:52:57 -0700 Subject: log caller In-Reply-To: References: Message-ID: <1182988377.964202.213790@g37g2000prf.googlegroups.com> On Jun 27, 2:42 pm, Matthew Peter wrote: > Is it possible to print the function calls to a module? Like: > > test.py > import mymod > print mymod.x() > > mymod.py > # each time a function is called we print out the called function and module > print 'Func call: %s from %s' % (???, ???) > > def x(): > return 'hello' > > Where would I pick up the ??? variables? A brief example would be nice too :) Thanks > in advance! You can use a decorator to wrap the function. You can use sys._getframe or inspect.stack to get information about the caller. The examples from the decorator module are very useful: http://www.phyast.pitt.edu/~micheles/python/documentation.html If for some reason you can't edit mymod.py to add the decorators, you can still wrap the function: import mymod import inspect try: from functools import update_wrapper except ImportError: def decorator_trace(f): def newf(): caller = inspect.stack()[1] print 'Caller is line %d of %s' % (caller[2], caller[1]) print 'Calling: %s from %s' % (f.__name__, f.__module__) return f() newf.__name__ = f.__name__ newf.__dict__.update(f.__dict__) newf.__doc__ = f.__doc__ newf.__module__ = f.__module__ return newf else: def decorator_trace(f): def newf(): caller = inspect.stack()[1] print 'Caller is line %d of %s' % (caller[2], caller[1]) print 'Calling: %s from %s' % (f.__name__, f.__module__) return f() return update_wrapper(newf, f) mymod.x = decorator_trace(mymod.x) greetings = mymod.x() print greetings but this approach has the shortcoming mentioned in the article. -- Hope this helps, Steven From doug at alum.mit.edu Fri Jun 29 00:44:31 2007 From: doug at alum.mit.edu (Douglas Alan) Date: Fri, 29 Jun 2007 00:44:31 -0400 Subject: Python's "only one way to do it" philosophy isn't good? References: <7xejjzmk7u.fsf@ruckus.brouhaha.com> <7xy7i7xjl5.fsf@ruckus.brouhaha.com> Message-ID: "Chris Mellon" writes: > Obviously. But theres nothing about the with statement that's > different than using smart pointers in this regard. Sure there is -- smart pointers handle many sorts of situations, while "with" only handles the case where the lifetime of the object corresponds to the scope. >> But I don't typically wish for this sort of intent to be made >> explicit. TMI! I used "with" for *many* years in Lisp, since this >> is how non-memory resource deallocation has been dealt with in Lisp >> since the dawn of time. I can tell you from many years of >> experience that relying on Python's refcounter is superior. > I question the relevance of your experience, then. Gee, thanks. > Refcounting is fine for memory, but as you mention below, memory is > only one kind of resource and refcounting is not necessarily the > best technique for all resources. I never said that it is the best technique for *all* resources. Just the most typical ones. >> This just isn't true. For many years I have not had to explicitly >> close files in Python. Nor have I had to do so in C++. They have >> been closed for me implicitly. "With" is not implicit -- or at least >> not nearly as implicit as was previous practice in Python, or as is >> current practice in C++. > You still don't have to manually close files. But you cannot, and > never could, rely on them being closed at a given time unless you > did so. You could for most intents and purposes. > If you need a file to be closed in a deterministic manner, then you > must close it explicitly. You don't typically need them to be closed in a completely fool-proof deterministic fashion. If some other code catches your exceptions and holds onto the traceback then it must know that can be delaying a few file-closings, or the like. > The with statement is not implicit and never has been. Implicit > resource management is *insufficient* for the general resource > management case. It works fine for memory, it's okay for files > (until it isn't), it's terrible for thread locks and network > connections and database transactions. Those things require > *explicit* resource management. Yes, I agree there are certain situations in which you certainly want "with", or something like it. I've never disagreed with that assertion at all. I just don't agree that for most Python code this is the *typical* case. > To the extent that your code ever worked when you relied on this > detail, it will continue to work. I've written plenty of Python code that relied on destructors to deallocate resources, and the code always worked. > There are no plans to replace pythons refcounting with fancier GC > schemes that I am aware of. This is counter to what other people have been saying. They have been worrying me by saying that the refcounter may go away and so you may not be able to rely on predictable object lifetimes in the future. > Nothing about Pythons memory management has changed. I know I'm > repeating myself here, but you just don't seem to grasp this > concept. Python has *never* had deterministic destruction of > objects. It was never guaranteed, and code that seemed like it > benefited from it was fragile. It was not fragile in my experience. If a resource *positively*, *absolutely* needed to be deallocated at a certain point in the code (and occasionally that was the case), then I would code that way. But that has been far from the typical case for me. >> Purify tells me that I know more about the behavior of my code than >> you do: I've *never* had any memory leaks in large C++ programs that >> used refcounted smart pointers that were caused by cycles in my data >> structures that I didn't know about. > I'm talking about Python refcounts. For example, a subtle resource > leak that has caught me before is that tracebacks hold references to > locals in the unwound stack. Yes, I'm aware of that. Most programs don't hold onto tracebacks for long. If you are working with software that does, then, I agree, that sometimes one will have to code things more precisely. > If you relied on refcounting to clean up a resource, and you needed > exception handling, the resource wasn't released until *after* the > exception unwound, which could be a problem. Also holding onto > tracebacks for latter processing (not uncommon in event based > programs) would artificially extend the lifetime of the resource. If > the resource you were managing was a thread lock this could be a > real problem. Right -- I've always explicitly managed thread locks. >> I really have no desire to code in C, thank you. I'd rather be coding >> in Python. (Hence my [idle] desire for macros in Python, so that I >> could do even more of my work in Python.) > In this particular conversation, I really don't think that theres much > to say beyond put up or shut up. I think your attitude here is unPythonic. > The experts in the field have said that it's not practical. Guido has occasionally said that he might consider a macro facility for a future version of Python. Do these so-called experts know something that he doesn't? > If you think they're wrong, you're going to need to prove it with > code, not by waving your hand. I have existence proofs for them working well in a number of other languages. >> > There's no particular reason why Lisp is any better for AI research >> > than anything. >> Yes, there is. It's a very flexible language that can adapt to the >> needs of projects that need to push the boundaries of what computer >> programmers typically do. > That doesn't make Lisp any better at AI programming than it is for > writing databases or spreadsheets or anything else. Well, Lisp is also good for those things too. Lisp is good for just about everything. Except that it wasn't for scripting when I first learned Python, as the start-up times on the Lisp-based competition was painfully slow. Guile seems to start up quickly enough these days, but it doesn't seem to be very widely used. >> And where are you getting this from? I don't know anyone who claims >> that any commonly used dialect of Lisp isn't *really* Lisp. > The language of the future will not be Common Lisp, Yes, that's for sure. > and it won't be a well known dialect of Lisp. It won't be *any* dialect that exists today, though, it is likely to be derived from an existing one, and may share its name. > It will have many Lisp like features, Yes, definitely. > and "true" Lispers will still claim it doesn't count, just as they > do about Ruby and Python today. I'm a true Lisper (I haven't programmed much in Lisp in some time, but I still think in Lisp, it being the one true language of programming thought after all), and I claim that Python and Ruby are tantamount to dialects of Lisp. Dialects that are sadly missing macros. |>oug From max at alcyone.com Sun Jun 3 21:18:57 2007 From: max at alcyone.com (Erik Max Francis) Date: Sun, 03 Jun 2007 18:18:57 -0700 Subject: subexpressions (OT: math) In-Reply-To: References: <4662675b$1_5@news.bluewin.ch> <1180890214.317409.85100@w5g2000hsg.googlegroups.com> Message-ID: Gary Herron wrote: > Of course not! Angles have units, commonly either degrees or radians. ... > I don't know of any name for the units of "sqrt of angle", but that > doesn't invalidate the claim that the value *is* a dimensioned > quantity. In lieu of a name, we'd have to label such a quantity as > "sqrt of degrees" or "sqrt of radians". After all, we do the same > thing for measures of area. We have some units of area like "acre", but > usually we label areas with units like "meters squared" or "square > meters". That's really no stranger than labeling a quantity as "sqrt > of degrees". What he (probably) means is that the only proper unit of angle is dimensionless, i.e., the radian. All the rest are different ways of measuring things that technically violate rules of dimensional analysis. In practice, it doesn't much matter, since angles are usually nicely stuffed inside trigonometric functions, e.g., r = A sin theta. The problem occurs when, via calculus, angles get pulled out of trigonometric substitution. This can happen via the chain rule easily enough. For the example r(t) = A sin theta(t) with A constant, the derivative v(t) = dr/dt = A (d/dt) sin theta(t) = A dtheta/dt cos theta. dtheta/dt is the time rate of change of an angle, and since it appears outside of a trigonometric function, must be expressed in units of radians per unit time or you'll get the wrong answers for v(t). Using alternate units (deg, grad, gon, rev, etc.) for expressing the angle here is not an option; you must use radians, which are technically just another name for a dimensionless figure. The radian is defined as the length of the subtended arc divided by the length of the radius, which is a length divided by a length, and thus dimensionless. (Like in a lot of dimensional analysis, you write "rad" when desired to give a helpful hint, not because it's necessary; the radian has the same units as 1.) -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM, Y!M erikmaxfrancis There never was a good war or a bad peace. -- Benjamin Franklin From rpdooling at gmail.com Thu Jun 28 09:26:37 2007 From: rpdooling at gmail.com (BartlebyScrivener) Date: Thu, 28 Jun 2007 13:26:37 -0000 Subject: Evolution of a pythonistas! In-Reply-To: References: Message-ID: <1183037197.730943.148670@q69g2000hsb.googlegroups.com> On Jun 28, 8:02 am, "Sells, Fred" wrote: > concur 100%. > Get a python aware editor. I use Eclipse+PyDev for big jobs, but still use > Emacs with python-mode for quickies. Just when I was thinking we agreed! :) Get Vim! http://www.vim.org And the Cookbook http://www.amazon.com/Python-Cookbook-Alex-Martelli/dp/0596007973/inscape-20 That's all you need. rd From eopadoan at altavix.com Wed Jun 27 19:34:43 2007 From: eopadoan at altavix.com (Eduardo "EdCrypt" O. Padoan) Date: Wed, 27 Jun 2007 20:34:43 -0300 Subject: PEP 3107 and stronger typing (note: probably a newbie question) In-Reply-To: <20070627231628.GA13272@slaniel-laptop.itasoftware.com> References: <5dveb4F360un0U1@mid.individual.net> <467a9209$0$22165$426a74cc@news.free.fr> <1182858785.886469.93060@n60g2000hse.googlegroups.com> <46824d8d$0$2324$426a74cc@news.free.fr> <4682eddc$0$23164$426a74cc@news.free.fr> <20070627231628.GA13272@slaniel-laptop.itasoftware.com> Message-ID: On 6/27/07, Stephen R Laniel wrote: > On Thu, Jun 28, 2007 at 09:08:16AM +0200, Bruno Desthuilliers wrote: > > You said ? > > I could link again to Mark-Jason Dominus, who writes that > people often make the following inference: > > 1) C is strongly typed. > 2) C's typing sucks. > 3) Hence strong typing sucks. AFAIK, Python type system is "stronger" than C. C is just *static* typed. > But I won't. > > It doesn't need to be a religious war. Why can't people just > say "When strong typing is done and used well, it's a > useful tool; when it's not, it's not"? True, why this need to be a religious war instead of everybody agreeing with you? :P -- EduardoOPadoan (eopadoan->altavix::com) Bookmarks: http://del.icio.us/edcrypt From frank at chagford.com Fri Jun 29 10:31:18 2007 From: frank at chagford.com (Frank Millman) Date: Fri, 29 Jun 2007 07:31:18 -0700 Subject: What happens to a thread with an unhandled exception? In-Reply-To: <1183121513.335933.101000@u2g2000hsc.googlegroups.com> References: <1183121513.335933.101000@u2g2000hsc.googlegroups.com> Message-ID: <1183127478.369970.196260@k29g2000hsd.googlegroups.com> On Jun 29, 2:51 pm, Frank Millman wrote: > Hi all > > I am doing something which works, but I have a gut feel that it cannot > be relied upon. Can someone confirm this one way or the other. [...] > My worry is that the thread with the unhandled exception may > eventually get garbage-collected, in which case the cleanup method > will no longer be accessible. Could this happen, or does the thread > stay in memory until termination of the main program? > I just noticed Diez's reply to a related question earlier today, where he suggested wrapping the thread's run() method in a try/finally construct. It works perfectly in my situation - if there is an unhandled exception, my cleanup method is called before the exception is raised. Thanks, Diez (even though you did not realise you were helping me). Frank From truth.to.u at gmail.com Sat Jun 23 06:23:08 2007 From: truth.to.u at gmail.com (the truth seeker) Date: Sat, 23 Jun 2007 03:23:08 -0700 Subject: the truth Message-ID: <1182594188.080856.288620@k79g2000hse.googlegroups.com> Explore the greatest life of the most recognized man in the history of humanity. http://mohammad.islamway.com From claird at lairds.us Thu Jun 7 14:19:06 2007 From: claird at lairds.us (Cameron Laird) Date: Thu, 7 Jun 2007 18:19:06 +0000 Subject: Bragging about Python References: <46681369$0$12126$3b214f66@tunews.univie.ac.at> Message-ID: In article <46681369$0$12126$3b214f66 at tunews.univie.ac.at>, Mathias Panzenboeck wrote: >Steve Howell schrieb: >> --- "pinkfloydhomer at gmail.com" >> wrote: >> >>> Is there a resource somewhere on the net that can be >>> used to quickly >>> and effectively show Python's strengths to >>> non-Python programmers? >>> Small examples that will make them go "Wow, that >>> _is_ neat"? >>> >> >> 15 small programs here: >> >> http://wiki.python.org/moin/SimplePrograms >> > >IMHO a few python goodies are missing there. >e.g. generator functions: > ># generic fibonacci without upper bound: >def fib(): > parent_rabbits, baby_rabbits = 1, 1 > while True: > yield baby_rabbits > parent_rabbits, baby_rabbits = baby_rabbits, parent_rabbits + >baby_rabbits > > ># only calculate and print the first 100 fibonacci numbers: >from itertools import islice > >for baby_rabbits in islice(fib(),100): > print 'This generation has %d rabbits' % baby_rabbits Good point. This example intrigues me. When I saw the first couple of lines, I expected def fib(): generation, parent_rabbits, baby_rabbits = 1, 1, 1 while True: yield generation, baby_rabbits generation += 1 parent_rabbits, baby_rabbits = \ baby_rabbits, parent_rabbits + baby_rabbits for pair in fib(): if pair[0] > 100: break print "Generation %d has %d (baby) rabbits." % pair as more appealing to non-Pythoneers. I'm still suspicious about how they're going to react to itertools.islice(). Now, though, I've begun to question my own sense of style ... From rh00667 at gmail.com Wed Jun 13 10:34:48 2007 From: rh00667 at gmail.com (rhXX) Date: Wed, 13 Jun 2007 14:34:48 -0000 Subject: httplib / connection In-Reply-To: References: <1181650152.610857.70210@i13g2000prf.googlegroups.com> Message-ID: <1181745288.964123.308980@z28g2000prd.googlegroups.com> > The > httplib.HTTP class that you were using is very old and deprecated for > several years now. > > -- > Gabriel Genellina :-( oh ...., tks! i took it from www.ug.it.usyd.edu.au/~comp5315/lec-09.html which class must i use? tks in advance From steven.bethard at gmail.com Tue Jun 12 19:20:36 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 12 Jun 2007 17:20:36 -0600 Subject: SimplePrograms challenge In-Reply-To: References: Message-ID: <_cednbcKePXYt_LbnZ2dnUVZ_u3inZ2d@comcast.com> Steve Howell wrote: > --- Steven Bethard wrote: >> How about we just comment it better? >> >> import itertools >> >> def iter_primes(): >> # an iterator of all numbers between 2 and +infinity >> numbers = itertools.count(2) [snip] > > Actually, just one small caveat--I'd still want the > program to print out the results. I think I've > followed that convention for all the other programs. Good point. Adding something as simple as:: # print the first 100 primes for prime in itertools.islice(iter_primes(), 100): print prime to the end should make it a full-fledged program. STeVe From ramdaz at gmail.com Tue Jun 19 02:41:45 2007 From: ramdaz at gmail.com (Ramdas) Date: Tue, 19 Jun 2007 06:41:45 -0000 Subject: How do I trap errors in win32com.client? Message-ID: <1182235305.461100.197790@e9g2000prf.googlegroups.com> How do I trap errors from win32com.client. I have tried the com_error classes from pywintypes and pythoncom sub modules. It is not catching for all cases. Is there any docs available? From notbob at nothome.com Thu Jun 21 11:30:03 2007 From: notbob at nothome.com (notbob) Date: Thu, 21 Jun 2007 10:30:03 -0500 Subject: The Modernization of Emacs References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182344981.372713.298580@w5g2000hsg.googlegroups.com> <86y7ieoiv7.fsf@lola.quinscape.zz> <1182347061.347199.133480@g4g2000hsf.googlegroups.com> <874pl2eg2j.fsf@W0053328.mgh.harvard.edu> <1182370016.986915.202150@u2g2000hsc.googlegroups.com> <87k5tx7444.fsf@W0053328.mgh.harvard.edu> Message-ID: <2cOdnRv-NoXmBOfbnZ2dnUVZ_t2dnZ2d@comcast.com> On 2007-06-21, Lew wrote: > To the claim that "emacs is too hard for the beginner" we have a mounting pile > of steaming evidence that refutes. It may still be true that it is too hard > for some beginners...... I point them to jed. I, too, was overwhelmed by emacs, initially, but can't stand vi so I had to do something. jed was my savior. It uses many standard keys like backspace and the arrows, so newbs aren't so confused. When I finally became comfortable with the std emacs keystrokes I got O'Reilly's great book and ventured into emacs. Love it. But, still a rank newb and still use jed and slrn a lot till I can learn to configure emacs like I want it. vi, the heart of evil! nb From jaywgraves at gmail.com Thu Jun 21 13:12:50 2007 From: jaywgraves at gmail.com (jay graves) Date: Thu, 21 Jun 2007 17:12:50 -0000 Subject: How to hide a program? In-Reply-To: References: <1182347596.414718.117190@w5g2000hsg.googlegroups.com> <1182352921.305431.72290@k79g2000hse.googlegroups.com> Message-ID: <1182445970.136127.169900@n2g2000hse.googlegroups.com> On Jun 20, 10:43 am, Thorsten Kampe wrote: > * jvdb (Wed, 20 Jun 2007 08:22:01 -0700) > http://www.ntwind.com/software/utilities/hstart.html I'm not the OP but this looks very useful to me. Thanks. ... Jay Graves From greg.novak at gmail.com Tue Jun 19 23:48:02 2007 From: greg.novak at gmail.com (greg.novak at gmail.com) Date: Wed, 20 Jun 2007 03:48:02 -0000 Subject: Python Memory Usage Message-ID: <1182311282.752464.143150@g37g2000prf.googlegroups.com> I am using Python to process particle data from a physics simulation. There are about 15 MB of data associated with each simulation, but there are many simulations. I read the data from each simulation into Numpy arrays and do a simple calculation on them that involves a few eigenvalues of small matricies and quite a number of temporary arrays. I had assumed that that generating lots of temporary arrays would make my program run slowly, but I didn't think that it would cause the program to consume all of the computer's memory, because I'm only dealing with 10-20 MB at a time. So, I have a function that reliably increases the virtual memory usage by ~40 MB each time it's run. I'm measuring memory usage by looking at the VmSize and VmRSS lines in the /proc/[pid]/status file on an Ubuntu (edgy) system. This seems strange because I only have 15 MB of data. I started looking at the difference between what gc.get_objects() returns before and after my function. I expected to see zillions of temporary Numpy arrays that I was somehow unintentionally maintaining references to. However, I found that only 27 additional objects were in the list that comes from get_objects(), and all of them look small. A few strings, a few small tuples, a few small dicts, and a Frame object. I also found a tool called heapy (http://guppy-pe.sourceforge.net/) which seems to be able to give useful information about memory usage in Python. This seemed to confirm what I found from manual inspection: only a few new objects are allocated by my function, and they're small. I found Evan Jones article about the Python 2.4 memory allocator never freeing memory in certain circumstances: http://evanjones.ca/python-memory.html. This sounds a lot like what's happening to me. However, his patch was applied in Python 2.5 and I'm using Python 2.5. Nevertheless, it looks an awful lot like Python doesn't think it's holding on to the memory, but doesn't give it back to the operating system, either. Nor does Python reuse the memory, since each successive call to my function consumes an additional 40 MB. This continues until finally the VM usage is gigabytes and I get a MemoryException. I'm using Python 2.5 on an Ubuntu edgy box, and numpy 1.0.3. I'm also using a few routines from scipy 0.5.2, but for this part of the code it's just the eigenvalue routines. It seems that the standard advice when someone has a bit of Python code that progressively consumes all memory is to fork a process. I guess that's not the worst thing in the world, but it certainly is annoying. Given that others seem to have had this problem, is there a slick package to do this? I envision: value = call_in_separate_process(my_func, my_args) Suggestions about how to proceed are welcome. Ideally I'd like to know why this is going on and fix it. Short of that workarounds that are more clever than the "separate process" one are also welcome. Thanks, Greg From cam.ac.uk at mh391.invalid Thu Jun 28 12:56:39 2007 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Thu, 28 Jun 2007 17:56:39 +0100 Subject: Excuse me!! In-Reply-To: <1183045766.315349.251860@n60g2000hse.googlegroups.com> References: <1183045766.315349.251860@n60g2000hse.googlegroups.com> Message-ID: mossab00019 at gmail.com wrote: > Haven't you thought about what is the right religion?! Sure, why do you think I use Python? > Here you will get the answer Agreed. -- Michael Hoffman From twisted0n3 at gmail.com Wed Jun 20 16:06:56 2007 From: twisted0n3 at gmail.com (Twisted) Date: Wed, 20 Jun 2007 20:06:56 -0000 Subject: The Modernization of Emacs In-Reply-To: <874pl2eg2j.fsf@W0053328.mgh.harvard.edu> References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182344981.372713.298580@w5g2000hsg.googlegroups.com> <86y7ieoiv7.fsf@lola.quinscape.zz> <1182347061.347199.133480@g4g2000hsf.googlegroups.com> <874pl2eg2j.fsf@W0053328.mgh.harvard.edu> Message-ID: <1182370016.986915.202150@u2g2000hsc.googlegroups.com> On Jun 20, 12:39 pm, jadam... at partners.org (Joel J. Adamson) wrote: > The point is that the responsibility to customize is on the user. Given that in its out-of-the-box configuration it's well-nigh unusable without a printed-out "cheat sheet" of some kind, of the sort that were supposed to have died out in the 80s, getting it customized poses something of a catch-22 for anyone trying to get started using it. From streamservenl at gmail.com Fri Jun 8 08:03:12 2007 From: streamservenl at gmail.com (jvdb) Date: Fri, 08 Jun 2007 05:03:12 -0700 Subject: how to do reading of binary files? Message-ID: <1181304192.406529.135190@n4g2000hsb.googlegroups.com> Hi all, I need some help on the following issue. I can't seem to solve it. I have a binary (pcl) file. In this file i want to search for specific codes (like <0C>). I have tried to solve it by reading the file character by character, but this is very slow. Especially when it comes to files which are large (>10MB) this is consuming quite some time. Does anyone has a hint/clue/solution on this? thanks already! Jeroen From jan.m.danielsson at gmail.com Wed Jun 27 01:50:08 2007 From: jan.m.danielsson at gmail.com (Jan Danielsson) Date: Wed, 27 Jun 2007 07:50:08 +0200 Subject: ElementTree -- adding one structure to another? In-Reply-To: <4681fa30$1@griseus.its.uu.se> References: <4681fa30$1@griseus.its.uu.se> Message-ID: <4681fa90$1@griseus.its.uu.se> Jan Danielsson wrote: > If have an element tree representing an XML document, and I load > another tree from a file, is there an easy way to stick the second tree > into the first one? > > fooElement = ET.SubElement(...) > > tree = ET.parse(TEMPLDIR + '/welcome.xml') > elem = tree.getroot() > > Now I want to stick elem as a subelement of fooElement. Do I need to > traverse the elem tree manually, or is there a way to just 'stick it in > there'? Found it two seconds after sending the post. fooElement.append(). Obviously. -- Kind regards, Jan Danielsson From apollonius2 at gmail.com Wed Jun 20 15:21:43 2007 From: apollonius2 at gmail.com (apollonius2 at gmail.com) Date: Wed, 20 Jun 2007 12:21:43 -0700 Subject: Help With Better Design In-Reply-To: <467919ca$0$28811$426a74cc@news.free.fr> References: <1182303267.427179.223720@i13g2000prf.googlegroups.com> <467919ca$0$28811$426a74cc@news.free.fr> Message-ID: <1182367303.089441.265180@i13g2000prf.googlegroups.com> > I've written code that looks a lot like that, and it's > a perfectly acceptable pattern IMHO. I don't bother > with the variables ON and OFF, though, as they add no > clarity to simply using 'ON' and 'OFF' for the states. > > [...] > The test portion of the code is actually longer than > the class > itself :-) > > That's usually a good thing! It means your code is > concise, and your tests are exhaustive. (But that > doesn't mean you can't also refactor your tests.) I have a habit of falling into the ole' "re-invent the wheel" trap. As long as I can be thurough without veering too far off course i'm in good shape. --------------------------------------------------------------------------------------------------- > > Better to use newstyle classes: > class LightBulb(object): > > > def __init__(self, initial_state): > > self.state = initial_state > > > def TurnOn(self): > > Pep-08 (naming conventions): > def turn_on(self): > > > if self.state == OFF: > > self.state = ON > > else: > > print "The Bulb Is Already ON!" > > > def TurnOff(self): > > if self.state == ON: > > self.state = OFF > > else: > > print "The Bulb Is Aleady OFF!" Thanks for mentioning that as I have never looked at PEP-08 before (just looked it up) and I bookmarked it for future reference. > What about: > > class LightBulb(object): > def __init__(self, state): > self.state = state > > def switch(self): > self.state = not self.state > > (snip) I never thought about it using a switch. Steven eluded to it (toggle) in his re-write of the code. I plan on using that idea. > > I would like to be able to get a good hold of the concept > > state machines ? Well both state machines and classes (objects). That may be a bit of a tall order to take on all at once but the concepts seem to be quite related. I already have a great deal of material on Classes so good to go there. The state machine idea came from a game tutorial I was reading and it really sparked my interest. > > with this example before I try to model a more complex problem. Would > > someone be willing to give me some feedback on this class and whether > > I am on the right track or how I might better go about it? > > There is a lot to say about OO and state machines. Someone once defined > the use of OO in simulations as "building an big unpredictable state > machine from small predictable state machines". As a matter of fact, > objects are (most of the time) informal state machines (they have state, > and they have behaviour depending on state). Now there are much more > formal state machines (google for "FSM" or "finite state machine") - > which can be implemented in a lot of ways - including the "State" design > pattern. > > Before jumping to implementation, you should probably try to model the > "more complex problem" with something like UML state diagram (one of the > few usable things in UML). > Thanks. Found some good FSM articles, that should help. From showell30 at yahoo.com Fri Jun 1 07:37:46 2007 From: showell30 at yahoo.com (Steve Howell) Date: Fri, 1 Jun 2007 04:37:46 -0700 (PDT) Subject: generating a tree-like structure In-Reply-To: Message-ID: <158385.66483.qm@web33504.mail.mud.yahoo.com> --- "A.T.Hofkamp" wrote: > > I would probably generate a DOT file to get a 2D > visualization. DOT is part of > Graphviz (graphviz.org), and there are quite a few > graphviz front-ends > available in Python to make DOT generation easier > (pydot, yapgvb, and probably > a few others). > +1 on Graphviz/DOT I've used them before (e.g. to display relationships between Python modules). They are very cool tools. ___________________________________________________________________________________ You snooze, you lose. Get messages ASAP with AutoCheck in the all-new Yahoo! Mail Beta. http://advision.webevents.yahoo.com/mailbeta/newmail_html.html From steve at laniels.org Sun Jun 24 15:59:43 2007 From: steve at laniels.org (Stephen R Laniel) Date: Sun, 24 Jun 2007 15:59:43 -0400 Subject: newbie tcp/ip question In-Reply-To: <467ECB79.7010001@gmail.com> References: <467ECB79.7010001@gmail.com> Message-ID: <20070624195943.GA13066@slaniel-laptop.itasoftware.com> On Sun, Jun 24, 2007 at 02:52:25PM -0500, Zachary Manning wrote: > I want to send some hex characters as a string literal to port 7142 and > to a specific ip address. How do I do that in python? Does this cover what you want to do? http://docs.python.org/lib/socket-example.html -- Stephen R. Laniel steve at laniels.org Cell: +(617) 308-5571 http://laniels.org/ PGP key: http://laniels.org/slaniel.key From gagsl-py2 at yahoo.com.ar Tue Jun 26 21:18:58 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 26 Jun 2007 22:18:58 -0300 Subject: Converting Diff Output to XML? References: <110a172d0706260743m10a9aaebt81e072717dbd6582@mail.gmail.com> Message-ID: En Tue, 26 Jun 2007 11:43:32 -0300, Debajit Adhikary escribi?: > What would be the best way to convert the regular (unix) diff output into > XML? > Are there any libraries at all which might help? You can use a SequenceMatcher object (see the difflib module http://docs.python.org/lib/module-difflib.html) and generate the xml file based on the resulting opcodes. -- Gabriel Genellina From ppaterson at gmail.com Wed Jun 6 12:14:21 2007 From: ppaterson at gmail.com (Paul Paterson) Date: Wed, 06 Jun 2007 09:14:21 -0700 Subject: Can os.remove followed by os.path.isfile disagree? In-Reply-To: <4666CEA7.8030301@tundraware.com> References: <1181140547.279974.83550@q66g2000hsg.googlegroups.com> <4666CEA7.8030301@tundraware.com> Message-ID: <1181146461.579368.296560@p77g2000hsh.googlegroups.com> Thanks for the response! > > I'd take the time to really examine the multiple threads of work you're running > to make sure one of them isn't removing the file just as another creates it. > Better still, use a locking semaphore around the code the creates/deletes the file > to guarantee mutual exclusion. The locking-semaphore idea is a good one - it would remove any possibility that this kind of race condition is causing the problem. Thanks, Paul From showell30 at yahoo.com Fri Jun 8 17:54:17 2007 From: showell30 at yahoo.com (Steve Howell) Date: Fri, 8 Jun 2007 14:54:17 -0700 (PDT) Subject: Bragging about Python (8 queens) In-Reply-To: <1181308155.710540.287110@n4g2000hsb.googlegroups.com> Message-ID: <791623.16203.qm@web33513.mail.mud.yahoo.com> --- Paul McGuire wrote: > > > > So I'm throwing down the gauntlet--can somebody > write > > a short program (maybe 10 to 20 lines) where you > solve > > a problem more simply than a similar > > non-generator-using solution would solve it? > Maybe > > something like Eight Queens? > > > > Well, I misread your "gauntlet throwing", and > implemented a brief 8- > queens using recursion and exceptions. Perhaps this > could serve as > the "before" to an "after" using generators. (I note > that neither > recursion nor exceptions are covered in your > examples.) Actually, there was a minor example with exceptions, but agreed re:recursion, and this is just such a classic problem, it belongs on the page. > Also, in > googling about for other 8-queens solutions in > Python, most are quite > complicated - this one uses only 24 lines, and works > for boards of any > size. I also think this line for printing out the > board: > > print "\n".join( "."*q+"Q"+"."*(BOARD_SIZE-q-1) for > q in queens ) > > illustrates a couple of interesting idioms of Python > (joining a list, > generator expression, "."*repetition to give > "...."). Agreed. > > Worthy of your page? > Definitely worthy. Go ahead and add it. FWIW I have been labelling programs by the number of lines of code. So this is program #24, which now creates a gap between #16 and #23. Also, I humbly suggest test_queens instead of testQueens. I don't want to reopen the PEP 8 debate, just a recommendation. I think PEP 8 would also suggest some white space around '+' and '=='. > > BOARD_SIZE = 8 > def validate(queens): > left = right = col = queens[-1] > for r in reversed(queens[:-1]): > left,right = left-1,right+1 > if r in (left, col, right): > raise Exception > > def add_queen(queens): > for i in range(BOARD_SIZE): > testQueens = queens+[i] > try: > validate(testQueens) > if len(testQueens)==BOARD_SIZE: > return testQueens > else: > return add_queen(testQueens) > except: > pass > raise Exception > > queens = add_queen([]) > print queens > print "\n".join( "."*q+"Q"+"."*(BOARD_SIZE-q-1) for > q in queens ) > Very Pythonic solution IMHO. Nicely done. ____________________________________________________________________________________ Looking for a deal? Find great prices on flights and hotels with Yahoo! FareChase. http://farechase.yahoo.com/ From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Wed Jun 27 11:29:40 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Wed, 27 Jun 2007 17:29:40 +0200 Subject: Too many 'self' in python.That's a big flaw in this language. References: <1182942154.185461.89620@e9g2000prf.googlegroups.com> Message-ID: <5efe34F37shinU1@mid.individual.net> hide1713 at gmail.com wrote: > I'm currently using Python. How long have you been using Python? > I find that a instance variable > must confined with self, for example: > class a: > def __init__(self): > self.aa=10 > def bb(self): > print self.aa # > See .if in c++,I could use aa to change that variable Mh, strange, I personally like to use "this.a" in C++, to make clear I use an instance variable. > That's a big inconvenience in coding ,especially when you have lot > of variable NACK, see above. > If you method need 10 variables ,you have to type "self" for 10 > times and that also makes your variable longer. Explicit is better than implicit. > From My point,I think this only help python interpreter to deside > where to look for. IMHO, it's also a great hint for the programmer. With others' C++ code, I'm often confused what kinds of variables (global, instance, static, ...) they access, it's also badly commented. If C++ forced the programmer to write "this.var", the code would be understandable with much less comments. Regards, Bj?rn -- BOFH excuse #13: we're waiting for [the phone company] to fix that line From mail at timgolden.me.uk Fri Jun 8 04:41:28 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Fri, 08 Jun 2007 09:41:28 +0100 Subject: Minimize Bandwidth In-Reply-To: <00e301c7a906$6473ff50$2d5bfdf0$@rawlins@thinkbluemedia.co.uk> References: <00e301c7a906$6473ff50$2d5bfdf0$@rawlins@thinkbluemedia.co.uk> Message-ID: <46691638.4070006@timgolden.me.uk> Robert Rawlins - Think Blue wrote: > I have a python application that hits a web service on a regular basis to > post a string of CSV log data and I'm looking to minimize the amount of > bandwidth that the application uses to send the log data. > > Is there any way to encode the string into base64 or something, that I can > then post and decode at the other end? Is that likely to save me bandwidth > perhaps? I don't really know much about this encoding stuff, but the smaller > I can compress the string the better. You could zip the csv data up first (assuming you control both ends of the conversation). Obviously compression ratios depend on various things. import zlib data = """ BAN X08 001 / 00 01 BAN X08 004 / 00 04 BAN X08 013 / 00 01 BAN X08 016 / 00 01 BAN X08 017 / 00 02 BAN X08 018 / 00 03 BAN X08 010 / 00 01 BAN X08 019 / 00 01 BAN X08 022 / 00 01 BAN X08 025 / 00 01 MAI X01 001 / 00 01 MAI X01 002 / 00 01 MAI X01 003 / 00 01 MAI X01 004 / 00 01 MAI X01 005 / 00 01 MAI X01 006 / 00 01 MAI X01 008 / 00 01 MAI X01 009 / 00 01 MAI X01 010 / 00 01 MAI X01 011 / 00 01 MAI X01 012 / 00 01 MAI X01 013 / 00 01 TOW P02 015 / 00 01 BET C01 006 / 00 BL BET C01 006 / 00 TL BET T01 011 / 00 01 BET T01 012 / 02 01 BET P01 010 / 00 01 BET P01 030 / 00 01 BET P02 022 / 00 01 STO C02 031 / 00 01 BON P01 003 / 01 01 """ compressed_data = zlib.compress (data, 9) print len (data), len (compressed_data) TJG From horpner at yahoo.com Fri Jun 8 14:51:16 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Fri, 08 Jun 2007 18:51:16 GMT Subject: Working with fixed format text db's References: Message-ID: On 2007-06-08, Jeremy C B Nicoll wrote: > Neil Cerutti wrote: >> Luckily, the output format has not changed yet, so issues with >> maintaining the above haven't arisen. > > The problem surely is that when you want to change the format > you have to do so in all files (and what about the backups > then?) and all programs simultaneously. I don't have control of the format, unfortunately. It's an import file format for a commercial database application. > Maintaining the code is the least of your the problems, I'd > say. > > You could change the data layout so that eg each field was > terminated by a marker character, then read/write delimited > values. But unless you also review all the other parts of your > programs, you need to be sure that you don't have any other > code anywhere that implicitly relies on a particular field > being a known fixed length. > >> However, I'd like something better. > > What precisely do you want to achieve? I was hoping for a module that provides a way for me to specify a fixed file format, along with some sort of interface for writing and reading files that are in said format. It is not actually *hard* to do this with ad-hoc code, but then the program is indecipherable without a hardcopy of the spec in hand. And also, as you say, if the spec ever does change, the hand-written batch of ljust, rjust and slice will be somewhat of a pain to reconfigure. But biggest weakness, to me, is that the specification is not in the code, or read and used by the code, and I think it should be. If nothing exists already I guess I'll roll my own. But I'd like to be lazier, and virtually all published modules are better than what I'll write for myself. ;) The underlying problem, of course, is the archaic flat-file format with fixed-width data fields. Even the Department of Education has moved on to XML for most of it's data files, which are much simpler for me to parse. -- Neil Cerutti From stefan.behnel-n05pAM at web.de Tue Jun 19 15:13:13 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Tue, 19 Jun 2007 21:13:13 +0200 Subject: easy_install from svn In-Reply-To: <1182269819.795671.43860@k79g2000hse.googlegroups.com> References: <1182269819.795671.43860@k79g2000hse.googlegroups.com> Message-ID: <46782AC9.6040501@web.de> Rob Cowie wrote: > I currently use easy_install to install packages from a custom, > locally hosted package_index. The index consists of a single html doc > with a list of package names and urls. All works well. > > I would like to get a little more sophisticated and install a package > from subversion. > > My package is structured as described in the setuptools docs. > > Simply pointing the url in my package index to svn://my/repo/package/trunk > works, but I would like - and I get the impression it is possible - to > be able to specify a revision number, or a tag and have that version > installed. > > Is it simply a case of appending a fragment to the url? > Would anyone be so kind as to provide a working example? This is how we do it for lxml: http://cheeseshop.python.org/pypi/lxml/1.2.1 Stefan From michael at jedimindworks.com Tue Jun 5 18:13:43 2007 From: michael at jedimindworks.com (Michael Bentley) Date: Tue, 5 Jun 2007 17:13:43 -0500 Subject: subprocess leaves child living In-Reply-To: References: <1181052375.551083.117390@p47g2000hsd.googlegroups.com> <874plmgogn.fsf@merkury.smsnet.pl> Message-ID: On Jun 5, 2007, at 4:17 PM, Thomas Dybdahl Ahle wrote: > Den Tue, 05 Jun 2007 15:46:39 -0500 skrev Michael Bentley: > >> But actually *that* is an orphan process. When a parent process dies >> and the child continues to run, the child becomes an orphan and is >> adopted by init. Orphan processes can be cleaned up on most >> Unices with >> 'init q' (or something very similar). > > Is it not possible to tell python that this process should not be > adopted > by init, but die with its parrent? > Just like terminals seem to do it.. Well, the way you posed the original question: > from subprocess import Popen > popen = Popen(["ping", "google.com"]) > from time import sleep > sleep(100) is really what adoption by init is designed to handle. Here you've created a child but have not waited for its return value. Like a good adoptive parent, init will wait(2) for the child. I think if you really looked into it you'd find that the terminal had called wait(2) before it was killed. Similarly, if you start a long- running subprocess in python and wait for it to return -- killing the parent will slaughter the child as well. hth, Michael --- Let the wookie win. From sean.farrow at seanfarrow.co.uk Fri Jun 8 09:45:31 2007 From: sean.farrow at seanfarrow.co.uk (Sean Farrow) Date: Fri, 8 Jun 2007 14:45:31 +0100 Subject: Obtaining hte currently running script under windows Message-ID: Hi: Is there any way to obtain the full path to the currently running script under win32? I am using the pythonw.exe file is that helps. Sean. From jan.m.danielsson at gmail.com Wed Jun 27 01:12:18 2007 From: jan.m.danielsson at gmail.com (Jan Danielsson) Date: Wed, 27 Jun 2007 07:12:18 +0200 Subject: p & br using ElementTree? In-Reply-To: References: <4681e39a$1@griseus.its.uu.se> Message-ID: <4681F1B2.3020708@gmail.com> Robert Kern wrote: [---] >>

        Current date:
        2000-01-01

        [---] > Use the .tail attribute on the br element: > > In [1]: from xml.etree import ElementTree as ET > > In [4]: p = ET.Element('p') > > In [5]: p.text = 'Current date:' > > In [6]: br = ET.SubElement(p, 'br') > > In [7]: br.tail = '2000-01-01' > > In [8]: ET.dump(p) >

        Current date:
        2000-01-01

        That did the trick. Thanks! -- Kind regards, Jan Danielsson From http Sat Jun 30 14:35:59 2007 From: http (Paul Rubin) Date: 30 Jun 2007 11:35:59 -0700 Subject: Python's "only one way to do it" philosophy isn't good? References: <1182750077.570603.160240@q69g2000hsb.googlegroups.com> <7xir9cbm0g.fsf@ruckus.brouhaha.com> <7xejjzmk7u.fsf@ruckus.brouhaha.com> <7xy7i7xjl5.fsf@ruckus.brouhaha.com> <1182872972.417776.78650@o11g2000prd.googlegroups.com> <1182873568.454491.302860@e9g2000prf.googlegroups.com> <7xps3iy73h.fsf@ruckus.brouhaha.com> <7x1wfudtw9.fsf@ruckus.brouhaha.com> <7x8xa1pbg8.fsf@ruckus.brouhaha.com> Message-ID: <7xhcopnvcg.fsf@ruckus.brouhaha.com> Douglas Alan writes: > > I'd say Haskell and ML are descended from Lisp, just like mammals are > > descended from fish. > > Hardly -- they all want to share the elegance of lambda calculus, > n'est-ce pas? Also, ML was originally implemented in Lisp, and IIRC > correctly, at least in early versions, shared much of Lisp's syntax. Haskell and ML are both evaluate typed lambda calculus unlike Lisp which is based on untyped lambda calculus. Certainly the most familiar features of Lisp (dynamic typing, S-expression syntax, programs as data (Lisp's macro system results from this)) are absent from Haskell and ML. Haskell's type system lets it do stuff that Lisp can't approach. I'm reserving judgement about whether Haskell is really practical for application development, but it can do stuff that no traditional Lisp can (e.g. its concurrency and parallelism stuff, with correctness enforced by the type system). It makes it pretty clear that Lisp has become Blub. ML's original implementation language is completely irrelevant; after all Python is still implemented in C. > Also, Scheme has a purely functional core (few people stick to it, of > course), and there are purely functional dialects of Lisp. Scheme has never been purely functional. It has had mutation since the beginning. Hedgehog Lisp (purely functional, doesn't have setq etc.) is really cute. I almost used it in an embedded project but that got cancelled too early. It seems to me more like a poor man's Erlang though, than anything resemblant to ML. From eadmund42 at NOSPAMgmail.com Sun Jun 24 19:19:10 2007 From: eadmund42 at NOSPAMgmail.com (Robert Uhl) Date: Sun, 24 Jun 2007 17:19:10 -0600 Subject: The Modernization of Emacs: terminology buffer and keybinding References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182272495.990807.99110@a26g2000pre.googlegroups.com> <87tzt3ihev.fsf@kobe.laptop> <1182370216.961241.6960@n60g2000hse.googlegroups.com> <85zm2ufjpb.fsf@lola.goethe.zz> <1182372592.803332.288260@u2g2000hsc.googlegroups.com> <1182373919.262388.100740@c77g2000hse.googlegroups.com> <85r6o6fhkb.fsf@lola.goethe.zz> <1182375045.626510.188170@m36g2000hse.googlegroups.com> <85myyufgwj.fsf@lola.goethe.zz> <1182375528.985142.293900@q69g2000hsb.googlegroups.com> <1182545268.055596.228700@i38g2000prf.googlegroups.com> <1182661040.286559.150880@q75g2000hsh.googlegroups.com> Message-ID: Twisted writes: > > Of course, if emacs let you keep THREE windows open and visible at the > same time, instead of being limited to one or a horizontally split two > ... and a cramped 80x10 or so each, at that ... I have two frames open right now: one 80x70, the other around 180x70 (characters, not pixels). One isn't split at all; the other is split into four windows, horizontally and vertically. > I'll admit that it didn't USED TO 'eschew normal methods of > navigation', but at a certain point in time there began to be 'normal > methods of navigation' and emacs naturally began eschewing them > promptly and has done so ever since. emacs has continued doing its own thing, mostly because that thing is better. The CUA standards (there exists an emacs package if you really want them) are broken and lame--I and most other don't wish to cripple our text editor of choice. > If I haven't, it must be the case that finding this tutorial (or even > discovering that it exists) was nontrivial, or it wasn't built into > emacs, one or the other. When you start emacs in a text console, you see this: Welcome to GNU Emacs, one component of the GNU/Linux operating system. Type C-l to begin editing. Get help C-h (Hold down CTRL and press h) Emacs manual C-h r Emacs tutorial C-h t Undo changes C-x u Buy manuals C-h C-m Exit Emacs C-x C-c Browse manuals C-h i Activate menubar F10 or ESC ` or M-` (`C-' means use the CTRL key. `M-' means use the Meta (or Alt) key. If you have no Meta key, you may instead type ESC followed by the character.) A GUI window shows a similar message. Note the 'Emacs tutorial' entry? Or you could just go to the Help menu, then select 'Emacs Tutorial.' >> If I'm browsing the manual online, I can switch from said manual to >> my document buffer without making the manual scroll to the >> documentation for switch-to-buffer. > > Apparently because you find the switch second nature, despite its not > being the obvious (which is ctrl-tab, to switch between documents in > an MDI app). Clicking within the document's window isn't obvious?!? > * OK, time to resort to *gulp* the help. > * Oh, great, now what did it do? I hit F1 and ... > * Eh. Try random stuff. Help starts with h. Alt-h? Ctrl-h? ... > * Oh, right. I seem to remember the help popping up unwanted when I > tried to backspace over a typo earlier, so I'll just do that. Ha! f1 and C-h do the exact same thing. You've obviously not used emacs this millennium. > WHAT menu bar? We're discussing emacs. As in, a text-mode editor. As > in a cramped little 80x24 grid of letters, numbers, spaces, and > punctuation with no menus, no concept of a pointing device, and a bad > attitude. No, we're discussing emacs, a text editor which runs in both a GUI and a text console. Which can display images. It's cool like that. > At least Windows 3.1 had most apps have the same keys for the vast > majority of commands, and those were the right keys. Emacs has all the > applications have the vast majority of their commands use the same > WRONG keys. Neither is right nor wrong; you're just used to one. The emacs keys are certainly more flexible and powerful, though. Some might consider them right for that reason. >> Wouldn't it be cool not to have one program implement search in one >> way, and another a second way, and yet another a third? Wouldn't it >> be cool to have access to a proper text editor when editing text on a >> web page? > > Search is usually ctrl+f, type something, hit enter in my experience. Unless you want regexp search. And if you want to find again it can be interesting. And maybe the program defaults to case-sensitive or case-insensitive search... > And I can use any text editor I want to edit HTML. You could use Notepad no doubt; you could also use a Turing machine. I prefer to use a useful tool. >> Do you realise that emacs has a GUI these days? I'm writing this in a >> 70-line window, with gtk+ widgets. Which means full-resolution, >> full-colour. > > What are you talking about? Clearly not emacs, which is a console app > for unix systems (with the inevitable MS-DOS ports and others). No, as I've said over and over and over again, emacs is not what you think it is. It has a GUI; it has colours; it can display images; it can use the native widget set. It can even be configured to use native keybindings, although that way lies madness. > Some sort of bastardized Windows port I suppose? Hah! Dude, I don't use Windows--I've better things to do with my life. -- Robert Uhl With weapons, we are citizens. Without them, we are subjects. From martin at v.loewis.de Tue Jun 5 15:32:21 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 05 Jun 2007 21:32:21 +0200 Subject: Getting mount stats for filesystems In-Reply-To: References: <46650e6c$0$25817$9b622d9e@news.freenet.de> <4665a7e9$0$24866$9b622d9e@news.freenet.de> Message-ID: <4665ba45$0$19674$9b622d9e@news.freenet.de> Mitko Haralanov schrieb: > On Tue, 05 Jun 2007 20:14:01 +0200 > "Martin v. L?wis" wrote: > >> Ah, ok. I recommend to parse /proc/mounts. > > I was looking for something that reminded me less of Perl and more of C > but haven't been able to find such a method. You could try to invoke getmntent(3). I'm not aware of a Python wrapper for it, so you either try to write one yourself in C, or use ctypes to write it in Python. Regards, Martin From senwin30 at gmail.com Wed Jun 20 12:43:12 2007 From: senwin30 at gmail.com (senthil arasu) Date: Wed, 20 Jun 2007 11:43:12 -0500 Subject: python25_d.lib Message-ID: <1ef9860e0706200943s2a2b8488vc56de9026f0ad43a@mail.gmail.com> Hi , After integrating python 2.5 in visual studio. Iam getting the linked error "cannot open file python25_d.lib" Help me to solve this issue. thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: From benji.york at gmail.com Mon Jun 25 15:39:50 2007 From: benji.york at gmail.com (Benji York) Date: Mon, 25 Jun 2007 12:39:50 -0700 Subject: eggs considered harmful In-Reply-To: References: Message-ID: <1182800390.085572.283870@g4g2000hsf.googlegroups.com> On Jun 21, 8:10 am, Harry George wrote: [snip description of unacceptable behaviors] > These are unacceptable behaviors. I am therefore dropping ZODB3 If you have bugs to report against ZODB, I sugest posting to zodb-dev (http://mail.zope.org/mailman/listinfo/zodb-dev). -- Benji York From mkb at incubus.de Sat Jun 23 12:39:33 2007 From: mkb at incubus.de (Matthias Buelow) Date: Sat, 23 Jun 2007 18:39:33 +0200 Subject: The Modernization of Emacs: terminology buffer and keybinding In-Reply-To: References: <1182272495.990807.99110@a26g2000pre.googlegroups.com> <87tzt3ihev.fsf@kobe.laptop> <1182370216.961241.6960@n60g2000hse.googlegroups.com> <85zm2ufjpb.fsf@lola.goethe.zz> <1182372592.803332.288260@u2g2000hsc.googlegroups.com> <1182549094.366282.286740@m37g2000prh.googlegroups.com> <87bqf7fwmg.fsf@telesippa.clsnet.nl> <1182553682.197778.138500@g37g2000prf.googlegroups.com> <877ipvfswe.fsf@telesippa.clsnet.nl> Message-ID: <5e50ltF356nbjU1@mid.dfncis.de> Tim Roberts wrote: > Editors are like underwear. We each have our own favorite brand, and > nothing you say will convince me to change mine. You really should have stopped here.... :) From gagsl-py2 at yahoo.com.ar Mon Jun 4 04:06:53 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 04 Jun 2007 05:06:53 -0300 Subject: Strange behavior in Windows References: <8B637660DDD59A40AA725C926CFC3D46035E39E4@nike.hir.is> Message-ID: En Sat, 02 Jun 2007 15:31:40 -0300, Jakob Svavar Bjarnason escribi?: > I have been trying to switch to Python from other languages such as Perl > and now I have a newbie question. > > I have been trying to run a setup script to install a python library. To > do that I need to run "c:> python setup.py install" but the strange > thing is is that when it runs the command: > >>>> from distutils import log > > I get the error ONLY while in cmd. If I run this from the interactive > shell that comes with IDLE it works. But if I go into the interactive > shell in the Windows shell cmd then I get: > > ImportError: cannot import log Maybe you have two different versions installed? Try this and post what you get: import sys print sys.version print sys.executable print sys.path both from inside IDLE and the console. Python versions earlier than 2.3 did not have a distutils.log module. -- Gabriel Genellina From cam.ac.uk at mh391.invalid Sun Jun 24 15:41:18 2007 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Sun, 24 Jun 2007 20:41:18 +0100 Subject: dealing with emf/wmf files In-Reply-To: References: Message-ID: Jackie Wang wrote: > I'd like to put some emf/wmf pictures into a pdf file > using 'reportlab', but the Python Imaging Library > cannot recognize emf files. The wmf files are said to > be 'identified only'. libwmf (not for Python) can convert WMF (not EMF) to SVG or EPS. http://wvware.sourceforge.net/libwmf.html -- Michael Hoffman From dak at gnu.org Sat Jun 23 03:31:37 2007 From: dak at gnu.org (David Kastrup) Date: Sat, 23 Jun 2007 09:31:37 +0200 Subject: The Modernization of Emacs: terminology buffer and keybinding References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182272495.990807.99110@a26g2000pre.googlegroups.com> <87tzt3ihev.fsf@kobe.laptop> <1182370216.961241.6960@n60g2000hse.googlegroups.com> <85zm2ufjpb.fsf@lola.goethe.zz> <1182372592.803332.288260@u2g2000hsc.googlegroups.com> <1182373919.262388.100740@c77g2000hse.googlegroups.com> <85r6o6fhkb.fsf@lola.goethe.zz> <1182375045.626510.188170@m36g2000hse.googlegroups.com> <1182546050.465987.115740@q19g2000prn.googlegroups.com> <871wg3k8c8.fsf@thalassa.lan.informatimago.com> <1182546979.295368.146110@q19g2000prn.googlegroups.com> <87wsxviqol.fsf@thalassa.lan.informatimago.com> Message-ID: <85k5tvazza.fsf@lola.goethe.zz> Pascal Bourguignon writes: > Falcolas writes: >> >> Would you mind elaborating on *what* took 3 hours to do, as opposed >> to just throwing around unquantified numbers? Would you also mind >> explaining the user's familiarity with the tools they were using on >> the mac? > > Anything that the user have to do repeatitively with the GUI, like > copy-and-paste, or reformating of a lot of paragraphs or table > entries, and which is done automatically by writting a one-liner > program in emacs or shell. Actually, in Emacs the task more often than not is solved by using C-h a or M-x apropos and then finding the command that already does the job. >> It's just as easy for me to say that it took me 30 minutes to >> simply exit emacs, and use that to justify that emacs, and by >> extension Linux, is a terrible tool. Somebody who needs 30 minutes to find the File/Exit Emacs menu is not qualified for reporting _any_ computing experience. It is like letting yourself get a report about the points of violin playing from somebody who has just had his first exposure to music, incidentally in the form of a violin lesson. -- David Kastrup, Kriemhildstr. 15, 44793 Bochum From no-spam at no-spam-no-spam.invalid Sat Jun 9 10:18:08 2007 From: no-spam at no-spam-no-spam.invalid (robert) Date: Sat, 09 Jun 2007 16:18:08 +0200 Subject: piping data stream through GPG In-Reply-To: References: Message-ID: robert wrote: > I played around trying to encrypt/decrypt data through GPG on the fly > (or worse - by using a file) (on Windows first - later to try on Linux too) > > Using os.popen3 like > > >>> i,o,e=os.popen3('gpg -e -r Robert') > >>> # i.write('y\n') > >>> i.write('wefwef') > >>> i.close() > >>> # e.read(1) > >>> o.read(1) > > hangs on o.read or e.read. > > So its quite dark. Just a totally non-existing userid (-r) will result > significantly different like > > >>> i.write('wefwef') > Traceback (most recent call last): > File "", line 1, in ? > IOError: [Errno 22] Invalid argument > > > GPG asks confirmation stuff (and pwd upon -d or -c) on the command line. > How to get all this the right way? > > now tryed around like >>> i,o,e=os.popen3('gpg --status-fd 2 --passphrase-fd 0 -e -r Robert','b') >>> i.write('y\r') >>> i.write('wefwef') >>> i.close() >>> # e.read(1) >>> o.read(1) still just hanging... never any output (status or honey) Robert From tjreedy at udel.edu Wed Jun 20 13:18:05 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 20 Jun 2007 13:18:05 -0400 Subject: Python's "only one way to do it" philosophy isn't good? References: <1181368143.874341.273140@r19g2000prf.googlegroups.com> Message-ID: "Douglas Alan" wrote in message news:lck5tzfri4.fsf at gaffa.mit.edu... | I think you are missing the point. Sussman is making a broad criticism of software | engineering in general, as it is understood today. On the contrary, I understood exactly that and said so. *My* point is that in doing so, he made one jab at one specific language in a herky-jerky footnote (a sentence on systems design philosopy, one on Python, one on physics) that I consider to be at least misleading. And so I feel the essay would be better without that wart. | > So Python seems to have the sort of flexibility that he implicitly | > claims it does not. | | For instance, one of the things that he talks about | exploring for more robust software systems is predicate dispatching, | which is an extension of multiple dispatch. Which I obviously read and responded to by noting "And 3.0 may add a new generic function module to dispatch on multiple arguments and possibly predicates." | Although you might be | able to cobble something like this together in Python, it would end up | being very cumbersome to use. Well, talk about shooting down innovations before they happen. Perhaps you could wait and see what Eby and others come up with in the next year. [from your other post] | A good multimethod system, e.g., would make Python a significantly | nicer language for my purposes, for instance. Or better yet, read http://www.python.org/dev/peps/pep-3124/ (tentatively approved by Guido, pending actual code) and perhaps some of the discussion thereof on the Python-3000 dev list and help design and code something that would be at least usable if not 'good'. | > The general problems of software inflexibility that he mentioned in | > a previous section have nothing specific to do with Python. | | Right. And he never said they did. And I never said that he said that they did. He just dropped in a formally awkward and contentually untrue dig at Python, and only Python, that I think should be removed. | You didn't read the paper very carefully. Because I don't agree with you? Because reading the paper did not much change my original response to the original poster's request for responses to the footnote? I read more than carefully enough to confirm and extend my opinion that the footnote is a wart that detracts from an otherwise interesting paper. | He things, for instance, that predicate dispatching, | backtracking, and first-class continuations will be required. Yes, I read and understood that. But learning this did not change my opinion of the bad form and bad content of the footnote. |The essay in questions was written for a graduate-level MIT |computer science class that aims to explore potential avenues of |research into new languages and approaches that encourage and |facilitate more robust software systems. Thanks for the additional context. But this still does not change my negative opinion of the footnote. In fact, it only strengthens it in that I think the footnote detracts from this aim. Terry Jan Reedy From james.harris.1 at googlemail.com Mon Jun 25 16:55:59 2007 From: james.harris.1 at googlemail.com (James Harris) Date: Mon, 25 Jun 2007 13:55:59 -0700 Subject: Portable general timestamp format, not 2038-limited In-Reply-To: References: <1182544384.709759.235300@o11g2000prd.googlegroups.com> Message-ID: <1182804959.215548.110140@k79g2000hse.googlegroups.com> On 25 Jun, 02:14, rem6... at yahoo.com (Robert Maas, see http://tinyurl.com/uh3t) wrote: > > From: James Harris > > I have a requirement to store timestamps in a database. ... > > 1) subsecond resolution - milliseconds or, preferably, more detailed > > How do you plan to deal with leap seconds? > - Stick to astronomical time, which is absolutely consistent but > which drifts from legal time? > - Stick to legal time (UTC), which stalls by one second from time > to time, causing time-difference calculations to be incorrect by > varying numbers of seconds? > Only after you make *that* crucial decision, will it be reasonable > to consider milliseconds or other sub-second resolution. Not a problem for me. I will be taking samples and storing either point samples or averages depending on the value being sampled. Pseudo- GMT will be good enough. Astronimical time will be no good as the time is to relate to the time of day the samples were taken. I think I can just use the time as returned by the language I am using (which presumably will get it from a C system call or similar). If one sample over midnight when a leap second adjustment happens turns out to be slightly incorrect it won't skew the results significantly. I could sanity check the time, though. Hmmm..... From doug at alum.mit.edu Sat Jun 30 14:15:00 2007 From: doug at alum.mit.edu (Douglas Alan) Date: Sat, 30 Jun 2007 14:15:00 -0400 Subject: Python's "only one way to do it" philosophy isn't good? References: <1182750077.570603.160240@q69g2000hsb.googlegroups.com> <7xir9cbm0g.fsf@ruckus.brouhaha.com> <7xejjzmk7u.fsf@ruckus.brouhaha.com> <7xy7i7xjl5.fsf@ruckus.brouhaha.com> <1182872972.417776.78650@o11g2000prd.googlegroups.com> <1182873568.454491.302860@e9g2000prf.googlegroups.com> <7xps3iy73h.fsf@ruckus.brouhaha.com> <7x1wfudtw9.fsf@ruckus.brouhaha.com> <7x8xa1pbg8.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin writes: > Douglas Alan writes: >> P.S. Besides Haskell is basically a refinement of ML, which is a >> dialect of Lisp. > I'd say Haskell and ML are descended from Lisp, just like mammals are > descended from fish. Hardly -- they all want to share the elegance of lambda calculus, n'est-ce pas? Also, ML was originally implemented in Lisp, and IIRC correctly, at least in early versions, shared much of Lisp's syntax. Also, Scheme has a purely functional core (few people stick to it, of course), and there are purely functional dialects of Lisp. |>oug From bruno.42.desthuilliers at wtf.websiteburo.oops.com Wed Jun 20 08:18:08 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Wed, 20 Jun 2007 14:18:08 +0200 Subject: Does altering a private member decouple the property's value? In-Reply-To: <87r6o8z5m6.fsf@benfinney.id.au> References: <87r6o8z5m6.fsf@benfinney.id.au> Message-ID: <46791af4$0$10322$426a74cc@news.free.fr> Ben Finney a ?crit : > "Ethan Kennerly" writes: > >> I really like properties for readonly attributes, > > Python doesn't have "readonly attributes", Err... Ever tried to set a class mro ?-) > and to attempt to use > properties for that purpose will only lead to confusion. read-only attributes actually are one of the common use-case for properties. From nszabolcs at gmail.com Mon Jun 4 14:21:24 2007 From: nszabolcs at gmail.com (Szabolcs Nagy) Date: Mon, 04 Jun 2007 11:21:24 -0700 Subject: Graph plotting module In-Reply-To: <1180976321.795513.172360@n4g2000hsb.googlegroups.com> References: <1180976321.795513.172360@n4g2000hsb.googlegroups.com> Message-ID: <1180981284.860490.240070@o5g2000hsb.googlegroups.com> Viewer T. wrote: > Is there a python module anywhere out there that can plot straight > line graphs, curves (quadratic, etc). If anyone knows where I can > download one, please let me know. http://matplotlib.sourceforge.net/ From andreengels at gmail.com Fri Jun 8 09:58:57 2007 From: andreengels at gmail.com (Andre Engels) Date: Fri, 8 Jun 2007 15:58:57 +0200 Subject: error when calling method of class In-Reply-To: References: Message-ID: <6faf39c90706080658s36defae7lf56e1929120fee4d@mail.gmail.com> 2007/6/8, Sean Farrow : > Hi: > I have defined a class in that class is a method defined as follows: > def splitTime(n): > seconds =float(n) > I call the method in another procedure as follows: > sefl.splitTime(200) > the traceback states that splitTime takes one argument two given. why is > this occuring? > if I try calling it like: > splitTime(200) > I get a name resultion error saying that the global name splitTime is > not defined. > Any help apreciated. In self.splitTime(200), self is considered an argument as well, thus the definition should be done with: def splitTime(self,n): -- Andre Engels, andreengels at gmail.com ICQ: 6260644 -- Skype: a_engels From dwahler at gmail.com Sun Jun 17 06:08:16 2007 From: dwahler at gmail.com (David Wahler) Date: Sun, 17 Jun 2007 11:08:16 +0100 Subject: Function that returns a tuple In-Reply-To: <1182071765.760451.298490@u2g2000hsc.googlegroups.com> References: <1182043826.790070.4420@u2g2000hsc.googlegroups.com> <1182071765.760451.298490@u2g2000hsc.googlegroups.com> Message-ID: On 6/17/07, Marcpp wrote: > On 17 jun, 03:53, Dan Hipschman wrote: > Hi, I need to return a tupla like this function: > > def BDllids(a): > a = () > conn = sqlite.connect('tasques.db') > cursor = conn.cursor() > cursor.execute('SELECT * FROM tasques') > for row in cursor: > a.append (row[0]) > return a() > > I'm doing the correct, method? Tuples are immutable (can't be modified once created). Try this: def BDllids(): conn = sqlite.connect('tasques.db') cursor = conn.cursor() cursor.execute('SELECT * FROM tasques') a = [row[0] for row in cursor] return tuple(a) Is there some particular reason you need to return a tuple as opposed to a list? P.S. Accessing fields of a SELECT * by numeric index is prone to breakage if the order of your fields changes. You can make your code more robust by either specifying the column name explicitly in the SELECT statement. Alternatively, you may be interested in the sqlite.Row object (see the documentation for details). -- David From half.italian at gmail.com Wed Jun 13 03:53:36 2007 From: half.italian at gmail.com (half.italian at gmail.com) Date: Wed, 13 Jun 2007 00:53:36 -0700 Subject: Bytes/File Size Format Function In-Reply-To: <1181720934.824480.175540@n15g2000prd.googlegroups.com> References: <1181706472.008233.80050@a26g2000pre.googlegroups.com> <1181720934.824480.175540@n15g2000prd.googlegroups.com> Message-ID: <1181721216.035950.27170@e26g2000pro.googlegroups.com> On Jun 13, 12:48 am, half.ital... at gmail.com wrote: > On Jun 12, 8:47 pm, samuraisam wrote: > > > > > Quick file size formatting for all those seekers out there... > > > import math > > > def filesizeformat(bytes, precision=2): > > """Returns a humanized string for a given amount of bytes""" > > bytes = int(bytes) > > if bytes is 0: > > return '0bytes' > > log = math.floor(math.log(bytes, 1024)) > > return "%.*f%s" % ( > > precision, > > bytes / math.pow(1024, log), > > ['bytes', 'kb', 'mb', 'gb', 'tb','pb', 'eb', 'zb', 'yb'] > > [int(log)] > > ) > > Wait a sec...what if you send it a large amount of bytes? Say... > bigger than 2147483647. You'll get an OverflowError. I thought you > had my solution... > > ~Sean I take it back. From nospam at nowhere.com Mon Jun 25 20:28:30 2007 From: nospam at nowhere.com (DavidM) Date: 26 Jun 2007 12:28:30 +1200 Subject: simplifying algebraic expressions Message-ID: <46805dae$1@news.orcon.net.nz> Hi, Are there any libraries for manipulating algebraic expression trees? In particular, take an expression tree and simplify it down. I'm working up the next release of PyGene, the genetic programming and genetic algorithms library. Part of PyGene works with trees holding algebraic expressions. For example, the expression: f = x**2 + sqrt(y) + 7 is represented as the tree: + ** x 2 + sqrt y 7 My GP code is successfully evolving expression trees to solve problems, however they're often full of redundancies, eg adding y in one part then subtracting y later on. I've added some simplification code which takes out some of the more obvious redundancies - eg replacing 'x - x' with '0', and replacing 'y / 1' with 'y' etc. But there'd be a pile of work to make this code smart enough to go deep into the tree and fix everything. So if someone can point me in the direction of an algebraic expressions library that can simplify expression trees and weed out redundancies, that would be awesome. Many thanks if you can help. Cheers David From jjl at pobox.com Sun Jun 17 13:01:07 2007 From: jjl at pobox.com (John J. Lee) Date: Sun, 17 Jun 2007 17:01:07 GMT Subject: Longest issue tracker thread? References: <87wsy9j8b4.fsf@pobox.com> Message-ID: <877iq2zfak.fsf@pobox.com> jjl at pobox.com (John J. Lee) writes: > Reading a recent message about a mozilla project bugzilla comment > thread 7 years old, I am curious re how dismally long and drawn-out a > tracker thread has so far been observed in the wild. [...] I'll get my coat... :-) John From aleax at mac.com Sat Jun 16 09:06:34 2007 From: aleax at mac.com (Alex Martelli) Date: Sat, 16 Jun 2007 06:06:34 -0700 Subject: Python's "only one way to do it" philosophy isn't good? References: <1181368143.874341.273140@r19g2000prf.googlegroups.com> <1hzrsp4.7vjuav1aegg0tN%aleax@mac.com> Message-ID: <1hzsdrr.wxcx771jwicv5N%aleax@mac.com> Steven D'Aprano wrote: ... > > perception that, at their roots, Scheme, C and Python share one > > philosophical underpinning (one that's extremely rare among programming > > languages as a whole) -- an appreciation of SIMPLICITY AND UNIFORMITY as > > language characteristics. > > Out of curiosity, what do you consider some of the worst offenders as far > as overly complex and inconsistent languages go, and why? I think the Original Sin in that regard was PL/I: it tried to have all the "cool features" of the three widespread languages of the time, Cobol, Algol _and_ Fortran (and then some), because it aimed to replace all three and become the "one programming language". As a result, it tended to have two or more ways to perform any given task, typically inspired by some of the existing languages, often with the addition of new ones made out of whole cloth. PL/I (mostly in various subset and "extended subset" forms) was widely used in the implementation of Multics, and I believe that the statement in the "Spirit of C" was at least partly inspired by that experience (just like "Unix" was originally intended as a pun on "Multics" underscoring the drastically simpler philosophy of the new OS). Alex From me at privacy.net Sat Jun 2 13:50:17 2007 From: me at privacy.net (Mark Carter) Date: Sat, 02 Jun 2007 18:50:17 +0100 Subject: Python rocks In-Reply-To: References: Message-ID: <4661adda$0$19256$da0feed9@news.zen.co.uk> Steve Howell wrote: > --- Mark Carter wrote: > >> Well, I know I'm preaching to the converted - but >> Python rocks. >> [...] > > A few questions from the choir: > > As a recent newcomer to the language, did you > encounter any traps or pitfalls while you were > learning? Also, could you single out anything in > particular about Python that started making you more > productive, or was it just the overall design? Well, I've been around the block a few times with Python, and had decided to try a couple of other languages. Having poked around, I've come to the conclusion that Python is the best language out there, and thought I'd share my observation with everyone. I hadn't posted to Lisp, because that'd be, like, considered trollish. Python's biggest win is probably its "batteries included" philosophy. Plus its extensive documentation. IDLE is simple, but it gets the job done. The syntax is obvious enough, so there's not much to dislike about Python. Not that I'm particularly knowledgeable about language design issues, but maybe closures and slightly different scoping rules would be nice. A pitfall of Python is knowing whether an operation is destructive or not. I guess if it was a purely functional language, that particular question wouldn't arise. Not that I'm saying I want Python to be a purely functional language. Oh, and when I read a line, I'd like it to get rid of the trailing line-ending characters. Python is accreting a lot of language features, and I'm not sure that's a good idea. Still, I guess if I don't like them, I don't have to use them. The thing about Lisp I found is that it's horribly fragmented, and doesn't do what I want it to do out of the box. Lisp is just too tedious. Python Just Works. I checked out Ruby a couple of years ago, but couldn't find anything to be worth the switch. I'm amazed at some of the things people have been able to do in Forth; but then, it doesn't beat Python's truckload of libraries and stuff like dictionaries, lists and other goodies that I get out of the box. From showell30 at yahoo.com Sun Jun 10 12:13:30 2007 From: showell30 at yahoo.com (Steve Howell) Date: Sun, 10 Jun 2007 09:13:30 -0700 (PDT) Subject: Python in the Mozilla world In-Reply-To: Message-ID: <97241.77728.qm@web33511.mail.mud.yahoo.com> --- "Eric S. Johansson" wrote: http://www.voidspace.org.uk/python/weblog/arch_d7_2007_04_28.shtml#e702 > > interesting. Very interesting but I suspect the > message is "don't hold your > breath but don't give up hope." > Exactly. :) > [...] What I need to do would take maybe a > day if you're distracted but > to spend some number of weeks learning how to > accomplish that day's effort is a > pretty low return on investment. I don't see a > career in plug-in writing is > something worth chasing. Anyway, that's my opinion > and I'm living with the > consequences. :-) > Well, that sounds pretty reasonable, and I'm sure a lot of folks are in a similar quandary. They need to use JS to a certain degree, but nobody wants to make a career out of plug-in writing, etc. (I certainly don't!) It wouldn't surprise me that there are lots of Python programmers who do JS maybe 5% of the time, and many of those folks can't justify the effort to go a bit deeper on the learning curve, create more of a community, etc. I guess I'm not helping you much other than to commiserate, but can I ask you to what extent you've looked into existing Python web frameworks, to see how much code there is out there that you could mine for your projects? I stumbled on some pretty high quality Python code a few weeks ago that amounted to Javascript helpers, but now I can't find it for the life of me. But it's out there... ____________________________________________________________________________________ 8:00? 8:25? 8:40? Find a flick in no time with the Yahoo! Search movie showtime shortcut. http://tools.search.yahoo.com/shortcuts/#news From harry.g.george at boeing.com Tue Jun 26 01:20:06 2007 From: harry.g.george at boeing.com (Harry George) Date: Tue, 26 Jun 2007 05:20:06 GMT Subject: eggs considered harmful References: <87fy4knb1u.fsf@pobox.com> <87wsxru83g.fsf@pobox.com> Message-ID: jjl at pobox.com (John J. Lee) writes: > Harry George writes: >> jjl at pobox.com (John J. Lee) writes: > [...] >>> 2. You can run your own private egg repository. IIRC, it's as simple >>> as a directory of eggs and a plain old web server with directory >>> listings turned on. You then run easy_install -f URL package_name >>> instead of easy_install package_name . The distutils-sig archives >>> will have more on this. >> >> Again, not speaking for anyone else: With 500 OSS packages, all of >> which play by the same tarball rules, we don't have resources to >> handle eggs differently. > > You said earlier: > >> The rules are that a) a very few authorized downloaders obtain >> tarballs and put them in a depot and b) other users get tarballs from >> the depot and build from source. > > Not sure how this differs significantly "from running a repository", > in the sense I use it above. > > > John Significant differences: "depot": Place(s) where tarballs can be stored, and can then be reached via http. "private egg repository": Tuned to the needs of Python eggs. E.g., not scattered over several directories or several versions. Thus a depot of self-contained packages can handle: 1. Multiple "releases" of the depot live at the same time. 2. Packages factored into CD-sized directories (not all in one "-f" location) 3. Multiple versions of Python, without having a new egg for each. 4. Multiple target platforms. Various *NIX and MS Win and Mac systems -- each at their own OS versions and own compiler versions. All without having platform-specific and compiler-specific eggs. 5. Different package version selections based on compatibility with other (non-Python) packages. E.g., to tune for GIS systems vs 3D animation systems vs numerical analysis systems vs web server systems. 6. Refresh process which does not need to fiddle with egg-ness, or even know about Python. Everything is a tarball. -- Harry George PLM Engineering Architecture From doug at alum.mit.edu Sun Jun 24 14:42:15 2007 From: doug at alum.mit.edu (Douglas Alan) Date: Sun, 24 Jun 2007 14:42:15 -0400 Subject: Python's "only one way to do it" philosophy isn't good? References: <1181368143.874341.273140@r19g2000prf.googlegroups.com> <7x3b0nmkk6.fsf@ruckus.brouhaha.com> Message-ID: Steven D'Aprano writes: > On Sat, 23 Jun 2007 14:56:35 -0400, Douglas Alan wrote: > >>> How long did it take you to write the macros, and use them, compared >>> to running Pylint or Pychecker or equivalent? >> An hour? Who cares? You write it once and then you have it for the >> rest of your life. You put it in a widely available library, and then >> *every* programmer also has it for the rest of their lives. The >> amortized cost: $0.00. The value: priceless. > Really? Where do I download this macro? How do I find out about it? How > many Lisp programmers are using it now? (1) I didn't have to write such a macro for Lisp, as Lisp works differently. For one thing, Lisp already has let and set special forms. (Lisp uses the term "special form" for what Python would call a "statement", but Lisp doesn't call them statements since they return values.) (2) You act as if I have no heavy criticisms of Lisp or the Lisp community. I critique everything with equal vigor, and keep an eye out for the good aspects and ideas of everything with equal vigor. > How does your glib response jib with your earlier claims that the > weakness of Lisp/Scheme is the lack of good libraries? (1) See above. (2) My response wasn't glib. > Googling for ' "Douglas Allen" download lisp OR scheme ' wasn't very > promising. (1) You spelled my name wrong. (2) I haven't written any libraries for any mainstream dialects of Lisp since there was a web. I did write a multiple dispatch lookup cacher for a research dialect of Lisp, but it was just an exercise for a version of Lisp that few people have ever used. > In fairness, the various Python lints/checkers aren't part of the standard > library either, but they are well-know "standards". In general I don't like such checkers, as I tend to find them more annoying than useful. >> Thanks, but that's just too syntactically ugly and verbose for me to >> use. > "Syntactically ugly"? "Verbose"? > Compare yours with mine: > let x = 0 > let y = 1 > let z = 2 > set x = 99 > (Looks like BASIC, circa 1979.) It looks like a lot of languages. And there's a reason for that -- it was a good idea. > variables.declare(x=0, y=1, z=2) > variables.x = 99 > (Standard Python syntax.) > I don't think having two easily confused names, let and set is an > advantage, Let and set are not easily confused. Lisp programmers have had absolutely no problem keeping the distinction separate for the last 47 years now. > but if you don't like the word "declare" you could change it to > "let", or change the name of the module to "set" (although that runs the > risk of confusing it with sets). > Because this uses perfectly stock-standard Python syntax, you could even > do this, so you type fewer characters: > v = variables > v.x = 99 > and it would Just Work. I wouldn't program that way, and no one that I know would either. In this regard you sound exactly like all the C++ folks, who when you point out that something in C++ is inadequate for one's needs, they point you at some cumbersome and ugly solution and then tell you that since C++ can already deal with the complaint, that there's no good reason to consider changing C++. Consequently, C++ still doesn't have a "finally" statement, and it requires either making instance variables public or forcing the programmer to write lots of boilerplate code writing setter and getter functions. Fortunately, the Python developers finally saw the errors of their ways in this regard and fixed the situation. But, it seems to me that you would have been one of those people saying that there's no need to have a way of overriding attribute assignment and fetching, as you can always just write all that extra boilerplate code, or instead add an extra layer of indirection (proxy objects) in your instance data to have things done the way you want, at the expense of ugly code. >> Not only that, but my fellow Python programmers would be sure to >> come and shoot me if I were to code that way. > *shrug* They'd shoot you if you used "let x = 0" too. Clearly you are not familiar with the programmers that I work with. As I mentioned previously, at least one of them is quite upset about the auto-declaration feature of most scripting languages, and your suggestion would not make her any happier. >> One of the reasons that I want to use Python is because I like reading >> and writing code that is easy to read and looks good. I don't want to >> bend it to my will at the expense of ugly looking code. > But the "ugly looking code" is stock-standard Python syntax. There many things that cannot be done in stock Python syntax elegantly (e.g. multiple predicate dispatch), which is why, when programming in Python, one often sticks to doing things the way that *can* be done elegantly. (This can often result in programs that are structured less elegantly in the large, however.) If you don't recognize this, then you must be livid over the addition to Python of decorators, list and generator comprehension, etc. After, all, Python is Turing complete, and any problem that can be solved in Python now could have been solved in Python before. The solution might just have looked a little (or a lot) different. > module.function(keyword=value) > module.attribute = value > is precisely the standard Python syntax you describe as "easy to read and > looks good" one moment. I don't believe you that you find it "ugly looking > code" -- if you did, you wouldn't be using Python. It's ugly for the purpose of local variable assignment, as it doesn't *look* like local variable assignment. If I wanted to program in a language that didn't understand the idea that different sorts of things ought to look different, I'd program in Java, rather than Python. |>oug From half.italian at gmail.com Thu Jun 7 14:36:04 2007 From: half.italian at gmail.com (half.italian at gmail.com) Date: Thu, 07 Jun 2007 18:36:04 -0000 Subject: ftplib error- Large file In-Reply-To: References: <1181147997.268014.50550@i38g2000prf.googlegroups.com> <1181207449.968884.158930@n15g2000prd.googlegroups.com> Message-ID: <1181241364.556715.303890@q19g2000prn.googlegroups.com> On Jun 7, 8:54 am, Facundo Batista wrote: > half.ital... at gmail.com wrote: > > Why would storbinary throw an exception even when the file transfer > > was successful? Why would the exception not be thrown until after the > > file was sent? Shouldn't ftplib return something like (104, > > "Connection reset by peer") instead of throwing an error? Is my > > reasoning off somewhere? > > There was an error, the connection was reset by peer. The error code is > 104. As it *was* an error, an exception is correct. > > You always can hide it yourself, with try/except... > > Regards, > > -- > . Facundo > . > Blog:http://www.taniquetil.com.ar/plog/ > PyAr:http://www.python.org/ar/ Ok. I guess that makes sense. But what about the other questions...mainly: Why would it throw an exception even though the file was properly transferred? I guess this could be blamed on the FTP server. ~Sean From bruno.42.desthuilliers at wtf.websiteburo.oops.com Fri Jun 15 07:12:20 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Fri, 15 Jun 2007 13:12:20 +0200 Subject: Serialization across languages? In-Reply-To: <46719c90$0$10851$88260bb3@free.teranews.com> References: <46719c90$0$10851$88260bb3@free.teranews.com> Message-ID: <46727407$0$20038$426a74cc@news.free.fr> Tobiah a ?crit : > I want to do SOAP like calls from a device who's libraries > don't include SOAP. I'm thinking of using simple HTTP posts, > but I'm going to want to send arrays and hashes. Then I'd second Simon's suggestion to use JSON. From nick at craig-wood.com Thu Jun 7 13:30:03 2007 From: nick at craig-wood.com (Nick Craig-Wood) Date: Thu, 07 Jun 2007 12:30:03 -0500 Subject: Bug/Weak Implementation? popen* routines can't handle simultaneous read/write? References: <1181232071.928835.301710@w5g2000hsg.googlegroups.com> Message-ID: dmoore wrote: > I've seen the following issue come up in multiple posts to this > mailing list: > > I have a python program that spawns a child process with popen or > popen2 or popen3 or popen2.popen2 etc. > the child process is interactive: it asks for input then spits out > some output, asks for more input then spits out some output. for > example, consider the trivial child program: > > print "welcome" > print ">", > s=raw_input() > while s!='exit': > print "you entered:",s > print ">", > s=raw_input() > > Now I may be completely wrong about this (I did play with popen for a > very long time before writing this message), but it appears that none > of the popen variants allow for a sequence of reads and writes to/from > this child. that is, if I read from the open pipe's output I will > never be able to write the input for the child because the parent > program will block on read until eof (I will have similar blocking > problems if I start with write - using readline does not seem to > help). You are correct. > the standard proposed remedy I have seen on this list is to use Unix- > only select/fctl, or otherwise dig into the bowls of the win32 api, or > download some half-complete sourceforge process control project. If you are referring to pexpect I've found it works well - unix only though. I've not noticed it being half complete. There is also a recipe for a non-blocking subprocess - see http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/440554 > All well and good, but unsatisfying for writing platform independent code. > > it turns out that there is at least one open source multi-platform > (read: win32/linux) api that does handle synchronous I/O with the > child: wxWidgets and wxPython using the class wxProcess. Now the > wxWidgets implementation is far from perfect, but it at least allows a > program to test for new input on the child's stdout and read stdout/ > write stdout in a non-blocking way. Interesting I didn't know about that - I shall try it! > However, I find it frustrating > that I have to import wx just to have useable interactive pipes in my > python scripts when I would expect this to be part of the native > python implementation. > > Anybody have any thoughts on this? Do I have my story straight? (the > popen variants can't handle this case and there are no other > alternatives in the standard python distro) Is there some place I can > submit this as a feature request? (Python dev?) The non-blocking subprocess would make a good start for a stdlib submission. It should really optionally use ptys under unix too otherwise you'll never be able to script passwd etc. An interface a bit like pexpect wpuld be useful too (ie scan for these regexps or timeout and return a match object). -- Nick Craig-Wood -- http://www.craig-wood.com/nick From bscrivener42 at gmail.com Thu Jun 28 08:17:57 2007 From: bscrivener42 at gmail.com (BartlebyScrivener) Date: Thu, 28 Jun 2007 12:17:57 -0000 Subject: Evolution of a pythonistas! In-Reply-To: <1183031173.173821.104990@e16g2000pri.googlegroups.com> References: <1183031173.173821.104990@e16g2000pri.googlegroups.com> Message-ID: <1183033077.051144.134400@n60g2000hse.googlegroups.com> On Jun 28, 6:46 am, swordofrue wrote: > Hello everyone, > > How does a pythonistas evolve? > Get the Python Cookbook 2d, pick a useful looking project, and adapt it for your own needs. Learn by doing. Some people enjoy just doing the tutorials with the interpreter open, testing code line by line. That works, too. But often the most gratifying is to solve a problem, or make a useful script that does something you need, which saves you time--time you can invest in learning more Python. :) rd From rw at smsnet.pl Tue Jun 12 17:37:59 2007 From: rw at smsnet.pl (Rob Wolfe) Date: Tue, 12 Jun 2007 23:37:59 +0200 Subject: SimplePrograms challenge References: <1181649968.097585.131780@g37g2000prf.googlegroups.com> Message-ID: <87vedsua4o.fsf@merkury.smsnet.pl> Steven Bethard writes: > I'd hate to steer a potential new Python developer to a clumsier "clumsier"??? Try to parse this with your program: page2 = ''' URLs
        • some page1
        • some page2
        • ''' > library when Python 2.5 includes ElementTree:: > > import xml.etree.ElementTree as etree > > page = ''' > URLs > > > > ''' > > tree = etree.fromstring(page) > for a_node in tree.getiterator('a'): > url = a_node.get('href') > if url is not None: > print url It might be even one-liner: print "\n".join((url.get('href', '') for url in tree.findall(".//a"))) But as far as HTML (not XML) is concerned this is not very realistic solution. > > I know that the wiki page is supposed to be Python 2.4 only, but I'd > rather have no example than an outdated one. This example is by no means "outdated". -- Regards, Rob From http Sat Jun 23 11:17:29 2007 From: http (Paul Rubin) Date: 23 Jun 2007 08:17:29 -0700 Subject: Python's "only one way to do it" philosophy isn't good? References: <1181368143.874341.273140@r19g2000prf.googlegroups.com> <7x3b0nmkk6.fsf@ruckus.brouhaha.com> <1182609058.566839.210870@n2g2000hse.googlegroups.com> Message-ID: <7xfy4ir986.fsf@ruckus.brouhaha.com> Michele Simionato writes: > Really powerful languages (say Haskell, just not to be too > Python-centric) do not need macros. http://www.haskell.org/th/ From __peter__ at web.de Wed Jun 6 02:59:03 2007 From: __peter__ at web.de (Peter Otten) Date: Wed, 06 Jun 2007 08:59:03 +0200 Subject: Does unicode() equal to unicode(sys.getfilesystemencoding()) ? References: <1181112038.934840.158590@q19g2000prn.googlegroups.com> Message-ID: ??????????????? wrote: > The follow statement comes from the Python 2.5 documentation > -------------- > encode( [encoding[,errors]]) > > Return an encoded version of the string. Default encoding is the > current default string encoding. errors may be given to set a > different error handling scheme. > --------------- > what's the "Default encoding" mean ? Does it equal to the > sys.getfilesystemencoding()? > If yes, but : > >>>>unicode('??', sys.getfilesystemencoding()) > u'\u4e2d\u56fd' >>>>unicode('??') > Traceback (most recent call last): > File "", line 1, in > UnicodeDecodeError: 'ascii' codec can't decode byte 0xd6 in position > 0: ordinal not in range(128) > > It seems the "Default encoding" is not equal to the > sys.getfilesystemencoding(). And then, what is it ? It is sys.getdefaultencoding(). On a properly configured system this is always 'ascii'. Peter From Afro.Systems at gmail.com Sun Jun 17 13:33:02 2007 From: Afro.Systems at gmail.com (Tzury) Date: Sun, 17 Jun 2007 17:33:02 -0000 Subject: Comparing UTF-8 into USC-2 and vice versa (newbie :-) ) In-Reply-To: <1182070999.570999.311690@e9g2000prf.googlegroups.com> References: <1182064058.292960.319970@p77g2000hsh.googlegroups.com> <4674E74E.1080406@v.loewis.de> <1182070124.121858.97140@q69g2000hsb.googlegroups.com> <1182070999.570999.311690@e9g2000prf.googlegroups.com> Message-ID: <1182101582.573171.213190@q75g2000hsh.googlegroups.com> Yet, 'utf_16_be' is not 'ucs-2'. How would I get ucs-2 encoding and decoding functionality with python? From martin at v.loewis.de Tue Jun 19 16:59:46 2007 From: martin at v.loewis.de (=?ISO-8859-2?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 19 Jun 2007 22:59:46 +0200 Subject: Python/C API bug (multithreading) In-Reply-To: References: Message-ID: <467843c2$0$23218$9b622d9e@news.freenet.de> > Is there any simple way to fix this damned bug?? Sure: just fixed your damned code!! Regards, Marttin From doug at alum.mit.edu Tue Jun 19 17:46:35 2007 From: doug at alum.mit.edu (Douglas Alan) Date: Tue, 19 Jun 2007 17:46:35 -0400 Subject: Python's "only one way to do it" philosophy isn't good? References: <1181368143.874341.273140@r19g2000prf.googlegroups.com> Message-ID: Neil Cerutti writes: > |>oug writes: >> Sussman's statements are not ironic because Scheme is a >> language that is designed to be extended by the end-user (even >> syntactically), while keeping the core language minimal. This >> is a rather different design philosophy from that of Python. > Which version Scheme, though? Scheme has only formally had macros > since R4RS, and then only as an extension. Macros are an extension > to Scheme, rather than a founder. Macros were only *standardized* in Scheme with R4RS. This is because they wanted to figure out the "right" way to do macros before putting it in stone. (Common Lisp-like non-hygienic macros were considered inelegant.) All the major implementations of Scheme that I know of implemented some form of powerful macro mechanism. N.b., Rabbit, which was Guy Steele's implementation of Scheme, and completed long, long before the R4RS standard. (Guy Steele was one of the two inventors of Scheme.) And, as far as I am aware, the plan was always to eventually come up with a macro mechanism that was as elegant as the rest of Scheme. The problem with this approach was that achieving this daunting goal turned out to take quite a while. > Python could conceivably end up in the same position 15 years > from now, with macros a well-established late-comer, as > generators have become. That would be very cool. The feeling I get, however, is that there would be too much complaining from the Python community about how such a thing would be "un-Pythonic". > The SRFIs are cool. > The last time I dipped my toe into the Scheme newsgroup, I was > overwhelmed by the many impractical discussions of Scheme's dark > corners. Python is either much more free of dark corners, or else > simply doesn't attract that kind of aficionado. I don't really think that Scheme itself has many dark corners -- it's just that being basically a pristine implementation of lambda calculus, Scheme lets you directly explore some pretty mind-bending stuff. I would agree that most of that kind of stuff is not particularly practical, but it can be fun in a hackerly, brain-expanding/brain-teaser kind of way. I think that most people who program in Scheme these days don't do it to write practical software. They either do it to have fun, or for academic purposes. On the other hand, most people who program in Python are trying to get real work done. Which is precisely why I program a lot in Python and very little in Scheme these days. It's nice to have the batteries included. |>oug From markacy at gmail.com Wed Jun 13 04:14:06 2007 From: markacy at gmail.com (markacy) Date: Wed, 13 Jun 2007 08:14:06 -0000 Subject: How to create a tuple quickly with list comprehension? In-Reply-To: References: Message-ID: <1181722446.984694.242700@q19g2000prn.googlegroups.com> On 13 Cze, 09:45, "fdu.xia... at gmail.com" wrote: > Hi all, > > I can use list comprehension to create list quickly. So I expected that I > can created tuple quickly with the same syntax. But I found that the > same syntax will get a generator, not a tuple. Here is my example: > > In [147]: a = (i for i in range(10)) > > In [148]: b = [i for i in range(10)] > > In [149]: type(a) > Out[149]: > > In [150]: type(b) > Out[150]: > > Is there a way to create a tuple like (1, 2, 3, 4, 5, 6, 7, 8, 9) > quickly? I already I can use tuple() on a list which is created by list > comprehension to get a desired tuple. > > Regards, > > Xiao Jianfeng You should do it like this: >>> a = tuple([i for i in range(10)]) >>> type(a) >>> print a[0] 0 >>> print a[9] 9 >>> print a (0, 1, 2, 3, 4, 5, 6, 7, 8, 9) Cheers, Marek From ronpro at cox.net Tue Jun 26 22:21:48 2007 From: ronpro at cox.net (Ron Provost) Date: Tue, 26 Jun 2007 22:21:48 -0400 Subject: idestudio Message-ID: <001801c7b861$eabd4700$6501a8c0@aristotle> Has anyone been able to download idestudio? Any link I find on google is broken. Thanks, Ron -------------- next part -------------- An HTML attachment was scrubbed... URL: From grflanagan at yahoo.co.uk Thu Jun 7 03:18:55 2007 From: grflanagan at yahoo.co.uk (Gerard Flanagan) Date: Thu, 07 Jun 2007 00:18:55 -0700 Subject: howto obtain directory where current (running) py-file is placed? In-Reply-To: <1181198387.952428.163120@q75g2000hsh.googlegroups.com> References: <1181198387.952428.163120@q75g2000hsh.googlegroups.com> Message-ID: <1181200735.220105.19250@q69g2000hsb.googlegroups.com> On Jun 7, 8:39 am, dmitrey wrote: > Hi all, > I guess this question was asked many times before, but I don't know > keywords for web search. > > Thank you in advance, D. import os d1 = os.path.dirname(__file__) d2 = os.path.dirname(os.__file__) print d1 print d2 From baur79 at gmail.com Tue Jun 5 05:06:07 2007 From: baur79 at gmail.com (baur79) Date: Tue, 05 Jun 2007 02:06:07 -0700 Subject: html 2 image script or library Message-ID: <1181034367.911086.189870@k79g2000hse.googlegroups.com> Hi everyone can you help me to find script or library for making website (from url) 2 image (png, jpg no matter). thanks a lot From stefan.behnel-n05pAM at web.de Tue Jun 19 17:28:02 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Tue, 19 Jun 2007 23:28:02 +0200 Subject: HTMLParser.HTMLParseError: EOF in middle of construct In-Reply-To: <46783ab1$0$1266$a729d347@news.telepac.pt> References: <1182195498.16548.5.camel@localhost.localdomain> <4677e790$0$2840$a729d347@news.telepac.pt> <46783ab1$0$1266$a729d347@news.telepac.pt> Message-ID: <46784A62.1000303@web.de> S?rgio Monteiro Basto wrote: > but is one single error that blocks this. > Finally I found it , it is : > if I put : > > p = re.compile('"align') > content = p.sub('" align', content) > > I can parse the html > I don't know if it a bug of HTMLParser Sure, and next time your key doesn't open your neighbours house, please report to the building company to have them fix the door. Stefan From kw at codebykevin.com Wed Jun 13 18:13:28 2007 From: kw at codebykevin.com (Kevin Walzer) Date: Wed, 13 Jun 2007 18:13:28 -0400 Subject: Build EXE on Mac OsX 10.4 In-Reply-To: References: <1181762699.145088.159500@j4g2000prf.googlegroups.com> Message-ID: <46706C08.8020809@codebykevin.com> Paul McNett wrote: > Tempo wrote: >> Has anyone sucesfully built a *.exe file on a mac operating system >> before from a *.py file? I have been trying to do this with >> pyinstaller, but I keep getting errors and I don't know how to install >> UPX properly. I tried putting the linux UPX folder in my python 2.4 >> directory, but that didn't work. I am just generally confused right >> now. Ha. If anybody can lend me some insight I would really appreciate >> it. Thank you for taking the time to read this post. > > You need to build Mac Apps on Mac, Windows EXE's on Windows, and Linux > ELF's on Linux. You can't build a windows.exe from Mac, just as you > can't build a mac.app from Windows. > Also, use py2app--that's the standard on the Mac. I don't believe pyinstaller works on OS X. -- Kevin Walzer Code by Kevin http://www.codebykevin.com From borud-news at borud.no Fri Jun 22 11:52:27 2007 From: borud-news at borud.no (Bjorn Borud) Date: 22 Jun 2007 17:52:27 +0200 Subject: The Modernization of Emacs References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182344981.372713.298580@w5g2000hsg.googlegroups.com> <1182370884.853838.321440@c77g2000hse.googlegroups.com> <2jpok4-ajt.ln1@zoogz.gregorie.org> Message-ID: [Martin Gregorie ] | | Yep, and the same people think a command line is to be avoided at all | costs. "I mean, its so /last century/ and you can't do anything useful | with it anyway". I have a friend who is a carpenter. he switched to Linux a few years ago because he was tired of how slow windows was and how easily it was infested with malware. he really, really doesn't give a toss what it says on the tin, he's a _user_ and that's it. to my surprise, finds Linux as easy, if not easier to use, than windows. (he still has to use windows for his invoicing system. everything else he does in Linux). I have observed similar opinions in other non-computer-freaks. people who see the computer only as a tool and are only interested in getting the job done. they have a surprising preference for Linux. (not many of them have ever been exposed to OSX though, and I'd suspect they'd prefer that since it is far more streamlined). | Obligatory OT comment: right now I have two xterm sessions open with | which I've been writing a Swing/JDBC app using nowt but a bash shell, | cvs, microEmacs and (of course) J2SE. I don't need no steenking IDE. I used J2SE, Ant, Emacs, Xterm, bash and Firefox as my main tools when I wrote most of my production Java code. and it is not exactly what you'd call "hobbyist projects" either. :-) -Bj?rn From edreamleo at charter.net Tue Jun 26 10:09:03 2007 From: edreamleo at charter.net (Edward K Ream) Date: Tue, 26 Jun 2007 09:09:03 -0500 Subject: Leo 4.4.3 final released Message-ID: <569gi.12$BL.7@newsfe12.lga> Leo 4.4.3 final is available at: http://sourceforge.net/project/showfiles.php?group_id=3458&package_id=29106 Leo is a text editor, data organizer, project manager and much more. See: http://webpages.charter.net/edreamleo/intro.html The highlights of Leo 4.4.3: ---------------------------- - Added support for chapters in Leo's core. - Added support for zipped .leo files. - Added a leoBridge module that allows full access to all of Leo's capabilities from programs running outside of Leo. - Removed all gui-dependent code from Leo's core. - Better support for the winpdb debugger. - Added support for @enabled-plugins nodes in settings files. - Added support for @open-with nodes in settings files. - Added support for @bool write_strips_blank_lines setting. - The__wx_gui plugin is now functional. - Leo can use aspell on Linux when using Python 2.5 or later. - @test nodes can now be run from any .leo file. - Many minor improvements, new settings, commands and bug fixes. Links: ------ Leo: http://webpages.charter.net/edreamleo/front.html Home: http://sourceforge.net/projects/leo/ Download: http://sourceforge.net/project/showfiles.php?group_id=3458 CVS: http://leo.tigris.org/source/browse/leo/ Quotes: http://webpages.charter.net/edreamleo/testimonials.html -------------------------------------------------------------------- Edward K. Ream email: edreamleo at charter.net Leo: http://webpages.charter.net/edreamleo/front.html -------------------------------------------------------------------- From aleax at mac.com Sun Jun 24 12:58:45 2007 From: aleax at mac.com (Alex Martelli) Date: Sun, 24 Jun 2007 09:58:45 -0700 Subject: is this a valid import sequence ? References: <4f97$467c254d$d443bb3a$9522@news.speedlinq.nl> <137qo1egg4v1k04@corp.supernews.com> <1i0694u.1n6evsntoei0wN%aleax@mac.com> <1i06hm3.1ii0h87p707f2N%aleax@mac.com> <137t2ro7p1cp531@corp.supernews.com> Message-ID: <1i07hbc.ocb2f41uxj3dqN%aleax@mac.com> Scott David Daniels wrote: > Steven D'Aprano wrote: > > On Sat, 23 Jun 2007 21:11:42 -0700, Alex Martelli wrote a lot, with lots > > of YELLING. > > > > Given the amount of SHOUTING in your post, and the fact that you feel so > > strongly about the trivial question of the redundant use of the global > > statement that you would "fail a student" who did it -- even if they did > > everything else correctly, efficiently and elegantly -- it seems to me > > that you are beyond rational discussion on this subject. > > I, for one, appreciate a second voice suggesting that your (Steve's) > vehement rejection of my technically correct and non-condemnatory post > explaining that one use of global in the OP's code was superfluous. Glad to hear this! I think the root of the issue is in learning to read "superfluous" as a NEGATIVE word -- follow Occam, and learn to not multiply entities beyond need:-). > You said (in the previous post): > > That's technically true, but declaring it with global makes the code > > self-documenting and therefore easier to read. > > > > It's never _wrong_ to use the global statement, even if it is strictly > > unnecessary for the Python compiler. > > Your post led a newbie to presume the extra use of global was "good > style," while I think you'll find there is no such consensus. I concur: having discussed style issues at many Python shops, I'm quite convinced that the general consensus is closer to the "redundant is bad" approach. Exhaustively listing all of the redundancies that are to be eschewed would of course take far too long; a more common approach is to try to identify those extremely few cases where redundancy IS explicitly deemed OK (and leave all other redundancies intrinsically disapproved). The cases I've seen with reasonable frequency for accepting certain redundancies basically boil down to accepting some "redundant parentheses". Python has many levels of priorities in expressions, and while they do tend to work "just right" there are always some corner cases where even a frequent Python coder MAY feel uncertain for a moment (and these uncertainties grow for coders that also have to use, e.g., C, or Fortran, &c, frequently). So, spelling things out as, e.g., (-a) ** b versus -(a ** b) is not unreasonable (vs just coding '-a**b' and relying on the reader to know exactly which of the two cases applies). An important subcase has to do with tuples -- while I personally prefer to use parentheses around tuples only where they're indispensable, I understand the opposite stance, where parentheses are always placed around tuples (it may be hard to memorize exactly all cases where they're required, e.g. when the tuple is the expression in a listcomp...). A more debatable case, IMHO, is slicing (and the related cases of range and xrange). Do you ever write x[0:N:1], xrange(0, N), etc? Or are the simpler x[:N], xrange(N), etc, always to be preferred? This is one of the few cases where I've seen group consensus fail to emerge in discussions about Python style even in close-knit teams... Alex From thomas.pohl at gmail.com Tue Jun 5 07:27:43 2007 From: thomas.pohl at gmail.com (thomas.pohl at gmail.com) Date: Tue, 05 Jun 2007 04:27:43 -0700 Subject: Feature request: New string conversion type to ignore list item In-Reply-To: References: <1181040836.014198.223080@h2g2000hsg.googlegroups.com> Message-ID: <1181042863.724725.128250@p77g2000hsh.googlegroups.com> On 5 Jun., 13:12, Peter Otten <__pete... at web.de> wrote: > or like this: > > >>> "%s %.s %s" % ("first", "second", "third") > > 'first third' Hey, that's great, thanks Peter! Tom From rw at smsnet.pl Wed Jun 13 15:31:42 2007 From: rw at smsnet.pl (Rob Wolfe) Date: Wed, 13 Jun 2007 21:31:42 +0200 Subject: SimplePrograms challenge References: <466F9329.2020306@gmail.com> <1181735763.199492.164760@q19g2000prn.googlegroups.com> Message-ID: <87odjjfy75.fsf@merkury.smsnet.pl> Steven Bethard writes: >> I vote for example with ElementTree (without xpath) >> with a mention of using ElementSoup for invalid HTML. > > Sounds good to me. Maybe something like:: > > import xml.etree.ElementTree as etree > dinner_recipe = ''' > > 24slicesbaguette > 2+tbspolive_oil ^^^^^^^^^ Is that a typo here? > 1cuptomatoes > 1-2tbspgarlic > 1/2cupParmesan > 1jarpesto > ''' > pantry = set(['olive oil', 'pesto']) > tree = etree.fromstring(dinner_recipe) > for item_elem in tree.getiterator('item'): > if item_elem.text not in pantry: > print item_elem.text That's nice example. :) > Though I wouldn't know where to put the ElementSoup link in this one... I had a regular HTML in mind, something like: # HTML page dinner_recipe = ''' Recipe
          amtunititem
          24slicesbaguette
          2+tbspolive_oil
          1cuptomatoes
          1-2tbspgarlic
          1/2cupParmesan
          1jarpesto
          ''' # program import xml.etree.ElementTree as etree tree = etree.fromstring(dinner_recipe) #import ElementSoup as etree # for invalid HTML #from cStringIO import StringIO # use this #tree = etree.parse(StringIO(dinner_recipe)) # wrapper for BeautifulSoup pantry = set(['olive oil', 'pesto']) for ingredient in tree.getiterator('tr'): amt, unit, item = ingredient.getchildren() if item.tag == "td" and item.text not in pantry: print "%s: %s %s" % (item.text, amt.text, unit.text)
          But if that's too complicated I will not insist on this. :) Your example is good enough. -- Regards, Rob From infocat at earthlink.net Fri Jun 8 22:11:11 2007 From: infocat at earthlink.net (Frank Swarbrick) Date: Fri, 08 Jun 2007 20:11:11 -0600 Subject: Working with fixed format text db's In-Reply-To: References: Message-ID: <5cughuF31samnU1@mid.individual.net> Neil Cerutti wrote: > The underlying problem, of course, is the archaic flat-file > format with fixed-width data fields. Even the Department of > Education has moved on to XML for most of it's data files, which > are much simpler for me to parse. XML easier to parse than fixed position file. Wow! Very likely this file is created by a COBOL program, because this is what COBOL loves. 01 my-record. 05 ssn pic 9(9). 05 id pic 9(10). 05 last-name pic x(16). 05 first-name pic x(11). 05 phone-nbr pic 9(10). 05 filler pic x(1254). 05 filler pic x(6) value '2813'. 05 major pic x(5). write my-record Haha. I'm just amused that new languages make simpler some things that were hard in older languages, but in turn make more difficult things that were simple! Frank COBOL expert/Python newbie From ping.nsr.yeh at gmail.com Sun Jun 17 11:42:47 2007 From: ping.nsr.yeh at gmail.com (Ping) Date: Sun, 17 Jun 2007 15:42:47 -0000 Subject: a_list.count(a_callable) ? In-Reply-To: References: <1181850818.567840.251090@x35g2000prf.googlegroups.com> <1181853479.914070.217270@i13g2000prf.googlegroups.com> <1181855184.511137.100870@z28g2000prd.googlegroups.com> <1181916937.648267.163070@z28g2000prd.googlegroups.com> <1181981527.960296.135820@i13g2000prf.googlegroups.com> <1182026221.039617.56320@n2g2000hse.googlegroups.com> Message-ID: <1182094967.099444.91410@n15g2000prd.googlegroups.com> Somehow I did not see my post sent about 10 hours ago. I'm posting it again. I apologize if it showed up twice. After seeing all the ideas tossed around, now I like the proposal made by BJ?rn Lindqvist the best, and I extend it further to match the sort() method: L.count(value, cmp=None, key=None) With this signature, the callable case is simply L.count(True, cmp=a_callable), although now a_callable must return True instead of anything logical equivalent. I can live with that. I made an implementation with subclassing and Carsten Haese's sum(1 ...) method, see below. It works fine for me. It would be great to see it supported by the built-in list. :) cheers, Ping $ cat slist.py #!/usr/bin/env python from operator import * class slist (list): def count(self, value, cmp=None, key=None): if not cmp and not key: return list.count(self, value) if not cmp: cmp = eq if not key: # cmp given, no key return sum(1 for i in self if cmp(i, value)) # both cmp and key are given return sum(1 for i in self if cmp(key(i), value)) class Person: def __init__(self, first_name, last_name, age, gender): self.first_name, self.last_name, self.age, self.gender = \ first_name, last_name, age, gender a = slist([3, 5, 7, 3]) print "a =", a print "a has", a.count(3), "3's and", a.count(4), "4's." print "a has", a.count(4, cmp=gt), "elements > 4 and", \ a.count(5, cmp=le), "elements <= 5." b = slist( [ Person("John", "Smith", 30, 'm'), Person("Claire", "Doe", 23, 'f'), \ Person("John", "Black", 43, 'm'), Person("Anne", "Jolie", 50, 'f') ] ) print "b has", b.count("John", key=attrgetter("first_name")), \ "elements with first_name == John." print "b has", b.count(25, cmp=le, key=attrgetter("age")), \ "elements with age <= 25." $ ./slist.py a = [3, 5, 7, 3] a has 2 3's and 0 4's. a has 2 elements > 4 and 3 elements <= 5. b has 2 elements with first_name == John. b has 2 elements with age <= 30. From marcoberi at gmail.com Thu Jun 7 07:11:38 2007 From: marcoberi at gmail.com (marcoberi at gmail.com) Date: Thu, 07 Jun 2007 11:11:38 -0000 Subject: Tkinter, tkMessagebox and overrideredirect In-Reply-To: References: <1181060331.167762.19180@q69g2000hsb.googlegroups.com> <1181132772.551848.192400@o5g2000hsb.googlegroups.com> <1181199864.217585.208370@q75g2000hsh.googlegroups.com> Message-ID: <1181214698.577148.41910@q66g2000hsg.googlegroups.com> On Jun 7, 12:01 pm, "Eric Brunel" wrote: > BTW, what are you trying to do here? Will your application run on a > "normal" desktop computer? Or will it run on special devices such as > vending machines or similar? You got it: it's a special device. > in the second case, you shouldn't rely on an existing window manager, and > try to design your GUI so that doing things "manually" will be easier. For > example, instead of displaying a dialog for a message, maybe you should > just reserve a screen zone to display the message, optionally displaying > it in a special color or making it blink so that the user can't miss it. > You may also consider using the "place" layout method to display things at > random coordinates in your application window. For example: You are right and I think it's not a big deal for simple popup messages. But when I need tkFileDialog.askdirectory I think things get harder. I would prefer not have to reimplement the whole stuff from scratch... Ciao. Marco. P.S. BTW I already owe you a pizza for your help. Do you think you can be at http://www.pycon.it this weekend? :-) From evan at yelp.com Thu Jun 14 12:16:08 2007 From: evan at yelp.com (Evan Klitzke) Date: Thu, 14 Jun 2007 09:16:08 -0700 Subject: for web application development In-Reply-To: <1181812584.392929.232670@o11g2000prd.googlegroups.com> References: <1181812584.392929.232670@o11g2000prd.googlegroups.com> Message-ID: On 6/14/07, james_027 wrote: > My problem is looking for a web framework for python, that could > provide a natural way of developing web app. I am avoiding to learn > template language as much as possible. You should definitely reconsider avoiding templates -- it's hard to imagine building a reasonably large webapp that didn't use them at all. Cheetah templates are a really, really good Python framework for writing templates, and the templates themselves that can use Python-like constructs, which make them pretty powerful. The standard way to do web programming in Python would of course be using something that ties into mod_python, but WSGI[1] has been brought into the language as of Python 2.5. Between Cheetah templates and the WSGI modules, you can put together a simple lightweight web framework in a couple hundred lines (or less) of Python. For my own personal website I threw together a really simple Python "framework" that runs as a daemon and uses WSGI and Cheetah templates, and it all ended up being only 150 lines of code, so I think this is a fairly good solution if you don't envision a huge/complex site. If you want to build a a much bigger site you should obviously look into the other frameworks that are available, particularly Django. [1] http://www.python.org/dev/peps/pep-0333/ -- Evan Klitzke From carsten at uniqsys.com Thu Jun 14 17:18:22 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Thu, 14 Jun 2007 17:18:22 -0400 Subject: a_list.count(a_callable) ? In-Reply-To: <1181855184.511137.100870@z28g2000prd.googlegroups.com> References: <1181850818.567840.251090@x35g2000prf.googlegroups.com> <1181853479.914070.217270@i13g2000prf.googlegroups.com> <1181855184.511137.100870@z28g2000prd.googlegroups.com> Message-ID: <1181855902.3382.16.camel@dot.uniqsys.com> On Thu, 2007-06-14 at 21:06 +0000, Dustan wrote: > On Jun 14, 3:37 pm, Dustan wrote: > > Which can then be converted into a generator expression (round > > brackets instead of square brackets) to avoid the intermediate list: > > len((i for i in a_list if a_callable(i))) > > Sorry for the excess of posts everybody. > > I just realized that the generator expression would not work. I'm not > sure how else could be implemented efficiently and without using up > memory besides by accumulating the count as your earlier example shows. sum(1 for i in a_list if a_callable(i)) -- Carsten Haese http://informixdb.sourceforge.net From ahlongxp at gmail.com Mon Jun 4 09:53:44 2007 From: ahlongxp at gmail.com (ahlongxp) Date: Mon, 04 Jun 2007 13:53:44 -0000 Subject: Python, Dutch, English, Chinese, Japanese, etc. In-Reply-To: References: Message-ID: <1180965224.136341.271180@z28g2000prd.googlegroups.com> On Jun 4, 11:54 am, Ross Ridge wrote: > Steve Howell wrote: > > >about Japan: > > major linguistic influences: Chinese, English, > >Dutch > > English and Dutch are minor linguistic influences. > Obviously. But language evolves. > > >Asia: > > > Python should be *completely* internationalized for > >Mandarin, Japanese, and possibly Hindi and Korean. > >Not just identifiers. I'm talking the entire > >language, keywords and all. > > This would be more convincing if it came from someone who spoke Mandarin, > Japanese, Hindi or Korean. > I'm a Chinese. Language/English is really a big problem for Chinese programmers. If python can be written in Chinese, it may become the most popular program language in China(though popular alreay). Considering the potential large amount of users in China, the effort of internationalization for Chinese will totally worth. > btw. Mandarin is a spoken dialect Chinese, what you're actually asking > for is a Simplified-Chinese version of Python. Mandarin is not a friendly way of saying Chinese and it is totally unacceptable in some area. Either Simplified Chinese or Traditional Chinese will be better. and last but not least, python ROCKS. From rh00667 at gmail.com Wed Jun 6 11:26:37 2007 From: rh00667 at gmail.com (rhXX) Date: Wed, 06 Jun 2007 15:26:37 -0000 Subject: lists - append - unique and sorted Message-ID: <1181143597.563633.241640@o5g2000hsb.googlegroups.com> hi, can i append a item to a list using criterias: - UNIQUE - if there already exist don't append and/or - SORTED - INSERT in the correct place using some criteria? tks in advance From garrickp at gmail.com Fri Jun 22 14:05:16 2007 From: garrickp at gmail.com (Falcolas) Date: Fri, 22 Jun 2007 11:05:16 -0700 Subject: The Modernization of Emacs: terminology buffer and keybinding In-Reply-To: References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182272495.990807.99110@a26g2000pre.googlegroups.com> <87tzt3ihev.fsf@kobe.laptop> <1182370216.961241.6960@n60g2000hse.googlegroups.com> <85zm2ufjpb.fsf@lola.goethe.zz> <1182372592.803332.288260@u2g2000hsc.googlegroups.com> <1182373919.262388.100740@c77g2000hse.googlegroups.com> <85r6o6fhkb.fsf@lola.goethe.zz> <1182375045.626510.188170@m36g2000hse.googlegroups.com> <1182453375.531950.141460@m36g2000hse.googlegroups.com> Message-ID: <1182535516.594974.243910@q69g2000hsb.googlegroups.com> On Jun 22, 11:28 am, Robert Uhl wrote: > That's the advantage of a well-organised set of commands. If you want > to use regexp search, you have to look at the dialogue box and click on > a checkbox--which would be a context switch. Again, you are assuming that the editor isn't set up in a way which allows this to be done from the keyboard. ctrl-f, alt-e, type, enter > That's even assuming that your editor _offers_ regexp search. If emacs > didn't have it, I could add it, and it'd be just as much part of the > editor as if it were included... One advantage I'm more than happy to cede to you - the current program I use is closed source and not extensible. Though, I'm sure that there are editors for windows/mac/xwindows which are as extensible as emacs. > It's Mac OS and Windows which are inconsistent. Emacs has been around > since they were mere glimmers in the eye of Jobs & Gates... Inconsistent? I would have to disagree. They changed paradigms - terminal text based interfaces to GUIs. You wouldn't expect a piece of software built for a terminal to be backwards compatibility to punch card interfaces, would you? Why would a GUI based program limit itself to functionality as defined by a terminal application? From joel.regen at gmail.com Tue Jun 26 10:48:36 2007 From: joel.regen at gmail.com (Jesse James) Date: Tue, 26 Jun 2007 14:48:36 -0000 Subject: logging anomaly Message-ID: <1182869316.358944.133430@n2g2000hse.googlegroups.com> I have some fairly simply code in a turbogears controller that uploads files. In this code, I inserted a 'start uploading' and a 'done uploading' log record like this: logger.info('----- start uploading file: '+Filename) # copy file to specified location. while 1: # Read blocks of 8KB at a time to avoid memory problems with large files. data = Filedata.file.read(1024 * 8) if not data: break fp.write(data) logger.info('----- done uploading file: '+Filename) fp.close() It is nice to occasionally see the upload time for a large file...but what I am seeing is that the 'start' message is not being logged until just immediately before the 'done' message: 2007-06-26 07:59:38,192 vor.uploader INFO ----- start uploading file: 7_Canyons_Clip_1.flv 2007-06-26 07:59:38,206 vor.uploader INFO ----- done uploading file: 7_Canyons_Clip_1.flv I know this is wrong because this is a large file that took almost a minute to upload. Seems like, with my experience with log4j, upon which I believe the python logging module was modeled, this should just work as expected. What am I missing here? Jesse. From stuart.tett at gmail.com Mon Jun 18 11:37:37 2007 From: stuart.tett at gmail.com (stuart.tett at gmail.com) Date: Mon, 18 Jun 2007 15:37:37 -0000 Subject: PyRun_String with Py_single_input to stdout? In-Reply-To: References: <1182141938.747032.122260@p77g2000hsh.googlegroups.com> Message-ID: <1182181057.605789.189590@o61g2000hsh.googlegroups.com> I found a solution using sys.displayhook here: http://groups.google.com/group/comp.lang.python/browse_thread/thread/593cd28e568c32e1/1e0f930e7ac5ebb2?#1e0f930e7ac5ebb2 On Jun 18, 4:24 am, "Gabriel Genellina" wrote: > En Mon, 18 Jun 2007 01:45:38 -0300, stuart.t... at gmail.com > escribi?: > > > I'm using PyRun_String with Py_single_input for a python interpreter > > embedded in my application. I'm using Py_single_input. Py_single input > > is what I want, but it seems to output to stdout. Before when I was > > using Py_eval_input I was able to grab the result so I could print it > > in a text box: > > > PyObject *resultObject = PyObject_Str( rstring ); > > if( resultObject != NULL ) { > > char *string = PyString_AsString( resultObject ); > > } > > > But Py_eval_input is only for isolated evaluation, not what I want. > > Py_single_input gives "None" for the string. > > Maybe because it actually returns None? No it doesn't. I know the function returns something because when I used Py_eval_input, it returned the correct output. The only difference is thate Py_string_input outputs using sys.write (stdout) > > > I wrote a class that redirects std::cout, but this doesn't work for > > this, I'm guessing because it uses printf to stdout, not cout. > > > Anyone know how I can get the string so I can print it in a text box. > > From your description this should be working... try posting some more code > showing how you call PyRun_String and how you process the result... > > -- > Gabriel Genellina From Dave.Baum at motorola.com Thu Jun 21 12:08:54 2007 From: Dave.Baum at motorola.com (Dave Baum) Date: Thu, 21 Jun 2007 11:08:54 -0500 Subject: PEP 3107 and stronger typing (note: probably a newbie question) References: <1182369568.941307.316260@p77g2000hsh.googlegroups.com> <5dtmtnF36t3pfU1@mid.uni-berlin.de> Message-ID: In article , kaens wrote: > On 6/20/07, Diez B. Roggisch wrote: > > > That is exactly the problem - there is no "some more" static typing. > > There is static typing - or not. You can't have it "just a bit". > > Couldn't a language be made so that if you declared a variable like, say: > > string foo = "I'm a string" > > it would be a string, and always a string, and if you declared a variable like > > foo = "i'm a dynamic variable" > > it would be considered dynamic? > > This doesn't seem like it would be too hard to add in to a language > that already had dynamic typing (But then again, I am inexperienced - > although interested in - language design). > > It seems to me like this could be really useful, but I'm not aware of > any language implementing something like this. Common Lisp has a mechanism similar to what you described. In general, variables are completely dynamic. However, it is possible to declare individual variables to be of specific types. There are also declarations that allow you to specify your preferences for speed versus safety. The upshot of all of this is that the language is a dynamic language most of the time, but the programmer can choose to give the compiler a bit more information, and with that information a good compiler can generate more efficient code (often competitive with the speed of C code). The Common Lisp approach is not without its problems (for one thing, a lot of the behavior when type declarations are not met is implementation dependent). But I think there are some ideas in there that could be applied to Python. On the other hand, I'm pretty happy with Python/SWIG/C++ for performance critical code, so I'm not sure if optional static typing would really be of much use unless the Python compiler got *very* good at generating optimized code when declarations were present. I still think it would be handy to easily specify the expected types of function arguments. I sometimes write code in this pattern: def foo(a, b): "a, b - instances of Bar" assert isinstance(a, Bar) assert isinstance(b, Bar) # do some stuff Note that the expectation that 'a' and 'b' are to be of type Bar is specified twice: once for a runtime check, once for the docstring. It might be nice if there were a mechanism to specify it once and have the docstring and runtime check both make use of that information: >>>def foo(Bar a, Bar b): >>> # do some stuff >>>foo(1, Bar()) TypeError: argument a is not of type Bar >>>help(foo) foo(Bar a, Bar b) On the downside, this sort of mechanism might do more harm than good. For one thing, it would really clash with duck typing. For another, anyone coming to Python from Java/C++ would probably use those declarations *everywhere*, even when there isn't a good reason to limit the type. Dave From rh00667 at gmail.com Tue Jun 12 08:03:20 2007 From: rh00667 at gmail.com (rhXX) Date: Tue, 12 Jun 2007 12:03:20 -0000 Subject: lists - append - unique and sorted In-Reply-To: References: Message-ID: <1181649800.089953.28650@n15g2000prd.googlegroups.com> On Jun 8, 12:17 am, "Delaney, Timothy (Tim)" wrote: > Terry Reedy wrote: > > "Dan Bishop" wrote in message > >news:1181181710.879767.234090 at m36g2000hse.googlegroups.com... > >> If you don't need the list to be sorted until you're done building > >> it, you can just use: > > >> lst = sorted(set(lst)) > > > ?? looks same as > > lst.sort() > > You missed that the OP wants only unique values from the original list. > > Tim Delaney tks to all for comments! From timr at probo.com Fri Jun 15 02:39:39 2007 From: timr at probo.com (Tim Roberts) Date: Fri, 15 Jun 2007 06:39:39 GMT Subject: python i2c ioctl References: <1181852794.603064.113340@n15g2000prd.googlegroups.com> Message-ID: <5hc473hr4gntc50sqph076r5lnded9glc8@4ax.com> luca wrote: > > I was trying to make to work directly l i2c with python with the >calls ioctl. But I have of the problems and I do not succeed to go >ahead. > >[root at axis-00408c000001 /usr/local/wrap]129# python pcf8591_ioctl.py >Reading from 4 ch 8 bit A/D converter PCF8591 >Traceback (most recent call last): > File "pcf8591_ioctl.py", line 269, in ? > main() > File "pcf8591_ioctl.py", line 229, in main > if i2c_open () < 0: > File "pcf8591_ioctl.py", line 168, in i2c_open > fcntl.ioctl(i2c_fd, _IO(ETRAXGPIO_IOCTYPE, IO_SETGET_OUTPUT), 0, >iomask) >TypeError: ioctl requires a file or file descriptor, an integer and >optionally a integer or buffer argument The error message pretty much tells you the problem. One of the parameters is not correct. Notice this: >def IO_CFG_WRITE_MODE_VALUE(msb, data_mask, clk_mask): > ( (((msb)&1) << 16) | (((data_mask) &0xFF) << 8) | ((clk_mask) & >0xFF) ) >def IO_CFG_WRITE_MODE_VALUE(msb, data_mask, clk_mask): > ( (((msb)&1) << 16) | (((data_mask) &0xFF) << 8) | ((clk_mask) & >0xFF) ) Key question: what do these functions return? Answer: nothing. You compute a value and then throw it away. Thus: print IO_CFG_WRITE_MODE_VALUE( 15, 0xfff, 0x0f0 ) This will print "None". Add a "return" before the expression. The same thing is true of all of these functions. You are thinking that a Python "def" is like a C "#define". It's not. It's like a C function. Nothing is returned unless you return it. >def _IOC(dir,type,nr,size): > (((dir) << _IOC_DIRSHIFT) | > ((type) << _IOC_TYPESHIFT) | > ((nr) << _IOC_NRSHIFT) | > ((size) << _IOC_SIZESHIFT)) > >def _IO(type,nr): > _IOC(_IOC_NONE,(type),(nr),0) > >def _IOR(type,nr,size): > _IOC(_IOC_READ,(type),(nr),sizeof(size)) > >def _IOW(type,nr,size): > _IOC(_IOC_WRITE,(type),(nr),sizeof(size)) > >def _IOWR(type,nr,size): > _IOC(_IOC_READ|_IOC_WRITE,(type),(nr),sizeof(size)) > >def _IOC_DIR(nr): > (((nr) >> _IOC_DIRSHIFT) & _IOC_DIRMASK) >def _IOC_TYPE(nr): > (((nr) >> _IOC_TYPESHIFT) & _IOC_TYPEMASK) >def _IOC_NR(nr): > (((nr) >> _IOC_NRSHIFT) & _IOC_NRMASK) >def _IOC_SIZE(nr): > (((nr) >> _IOC_SIZESHIFT) & _IOC_SIZEMASK) >def IOC_IN(): > (_IOC_WRITE << _IOC_DIRSHIFT) > >def IOC_OUT(): > (_IOC_READ << _IOC_DIRSHIFT) >def IOC_INOUT(): > ((_IOC_WRITE|_IOC_READ) << _IOC_DIRSHIFT) >def IOCSIZE_MASK(): > (_IOC_SIZEMASK << _IOC_SIZESHIFT) >def IOCSIZE_SHIFT(): > (_IOC_SIZESHIFT) However, there are more problems with this script. Example: >#Get the SDA line state >def i2c_getbit(): > value=fcntl.ioctl(i2c_fd, _IO(ETRAXGPIO_IOCTYPE, IO_READBITS)) > if ((value&(I2C_DATA_LINE))==0): > return 0 > else: > return 1 This will produce a runtime error, because the name "i2c_fd" is not defined. Notice this: >#Open the GPIOB dev >def i2c_open(): > i2c_fd = os.open("/dev/gpiog", os.O_RDWR) > iomask = I2C_CLOCK_LINE > fcntl.ioctl(i2c_fd, _IO(ETRAXGPIO_IOCTYPE, IO_SETGET_OUTPUT), iomask) > iomask = I2C_DATA_LINE > fcntl.ioctl(i2c_fd, _IO(ETRAXGPIO_IOCTYPE, IO_SETGET_INPUT), iomask) > fcntl.ioctl(i2c_fd, _IO(ETRAXGPIO_IOCTYPE, IO_SETBITS), >I2C_DATA_LINE) > i2c_dir_in() > i2c_clk(1) > return i2c_fd The result of the open is bound in a LOCAL variable called "i2c_fd". As soon as the function returns, that variable goes away. You do RETURN the value, but you don't store it anywhere: >#PCF8591 address scheme >#| 1 | 0 | 0 | 1 | A2 | A1 | A0 | R/W | >#| i2c_fixed | i2c_addr | 1/0 | >def main (): > i2c_fixed = 0x09 > i2c_addr = 0x01 > > print "Reading from 4 ch 8 bit A/D converter PCF8591" > > if i2c_open () < 0: > print "i2c open error" > return 1 You should probably make this: i2c_fd = i2c_open() if i2c_fd < 0: print "i2c open error" return 1 But, of course, that's not enough either; i2c_fd is a local variable in THIS function as well. You should change ALL of the functions so that they accept an fd as the first parameter, and then pass i2c_fd into the functions here. Alternatively, you could create a wrapper class to hold the fd and make the function methods on that class. > while "azz": > i2c_start () I'm curious. What do you think "while" statement is doing? The answer is that it is an infinite loop; the string "azz" will always be true, so the while statement will always loop. I can't guess what you really wanted here. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From jmtulloss at gmail.com Tue Jun 19 13:49:35 2007 From: jmtulloss at gmail.com (jmtulloss at gmail.com) Date: Tue, 19 Jun 2007 10:49:35 -0700 Subject: ARM cross compile - one last problem Message-ID: <1182275375.513700.46290@g4g2000hsf.googlegroups.com> Hello all, I've been trying to get Python to cross compile to linux running on an ARM. I've been fiddling with the cross compile patches here: http://sourceforge.net/tracker/index.php?func=detail&aid=1597850&group_id=5470&atid=305470 and I've had some success. Python compiles and now all of the extensions do too, but when I try to import some of them (time, socket, etc.), they have trouble finding certain symbols. Py_Exc_IOError and _Py_NoneStruct are the two I remember seeing. It would appear that they are exported by libpython, which I believe is statically linked into the python executable? That's where I start to get confused. What part of python is breaking? Where should I be looking for problems? Thanks a lot! Justin From len-l at telus.net Fri Jun 29 22:42:26 2007 From: len-l at telus.net (Lenard Lindstrom) Date: Sat, 30 Jun 2007 02:42:26 GMT Subject: Python's "only one way to do it" philosophy isn't good? In-Reply-To: References: <7xejjzmk7u.fsf@ruckus.brouhaha.com> <7xy7i7xjl5.fsf@ruckus.brouhaha.com> Message-ID: Douglas Alan wrote: > Lenard Lindstrom writes: > >> Douglas Alan wrote: > >>> [I]n Python, you can be 100% sure that your files >>> will be closed in a timely manner without explicitly closing them, as >>> long as you are safe in making certain assumptions about how your code >>> will be used. Such assumptions are called "preconditions", which are >>> an understood notion in software engineering and by me when I write >>> software. > >> So documenting an assumption is more effective than removing the >> assumption using a with statement? > > Once again I state that I have nothing against "with" statements. I > used it all the time ages ago in Lisp. > Sorry if I implied that. I assumed it would be clear I was only referring to the specific case of implicitly closing files using reference counting. > But (1) try/finally blocks were not to my liking for this sort of > thing because they are verbose and I think error-prone for code > maintenance. I and many others prefer relying on the refcounter for > file closing over the try/finally solution. Consequently, using the > refcounter for such things is a well-entrenched and succinct idiom. > "with" statements are a big improvement over try/finally, but for > things like file closing, it's six of one, half dozen of the other > compared against just relying on the refcounter. > I agree that try/finally is not a good way to handle resources. > (2) "with" statements do not work in all situations because often you > need to have an open file (or what have you) survive the scope in > which it was opened. You may need to have multiple objects be able to > read and/or write to the file. And yet, the file may not want to be > kept open for the entire life of the program. If you have to decide > when to explicitly close the file, then you end up with the same sort > of modularity issues as when you have to free memory explicitly. The > refcounter handles these sorts of situations with aplomb. > Hmm. I come from a C background so normally don't think of a file object as leading a nomadic life. I automatically associate a file with a home scope that is responsible for opening and closing it. That scope could be defined by a function or a module. But I'm not a theorist so can't make any general claims. I can see, though, how ref count could close a file sooner than if one waits until returning to some ultimate enclosing scope. > (3) Any code that is saving tracebacks should assume that it is likely > to cause trouble, unless it is using code that is explicitly > documented to be robust in the face of this, just as any code that > wants to share objects between multiple threads should assume that > this is likely to cause trouble, unless it is using code that is > explicitly documented to be robust in the face of this. > Luckily there is not much need to save tracebacks. > (4) Any code that catches exceptions should either return soon or > clear the exception. If it doesn't, the problem is not with the > callee, but with the caller. > Explicitly clear the exception? With sys.exc_clear? > (5) You don't necessarily want a function that raises an exception to > deallocate all of its resources before raising the exception, since > you may want access to these resources for debugging, or what have you. > No problem: >>> class MyFile(file): def __exit__(self, exc_type, exc_val, exc_tb): if exc_type is None: file.__exit__(self, None, None, None) return False >>> del f Traceback (most recent call last): File "", line 1, in del f NameError: name 'f' is not defined >>> try: with MyFile("something", "w") as f: raise StandardError("") except StandardError: print "Caught" Caught >>> f.closed False But that is not very imaginative: >>> class MyFile(file): def __exit__(self, exc_type, exc_val, exc_tb): if exc_type is not None: self.my_last_posn = self.tell() return file.__exit__(self, exc_type, exc_val, exc_tb) >>> del f Traceback (most recent call last): File "", line 1, in del f NameError: name 'f' is not defined >>> try: with MyFile("something", "w") as f: f.write("A line of text\n") raise StandardError("") except StandardError: print "Caught" Caught >>> f.closed True >>> f.my_last_posn 16L --- Lenard Lindstrom From doug at alum.mit.edu Fri Jun 22 13:21:14 2007 From: doug at alum.mit.edu (Douglas Alan) Date: Fri, 22 Jun 2007 13:21:14 -0400 Subject: Python's "only one way to do it" philosophy isn't good? References: <1181368143.874341.273140@r19g2000prf.googlegroups.com> <7x3b0nmkk6.fsf@ruckus.brouhaha.com> Message-ID: "Terry Reedy" writes: > "Douglas Alan" wrote in message > | > But why is the ability to abstract syntax good? > | It allows the community to develop language features in a modular way > | without having to sully the code base for the language itself. > Anyone can write modules, experimental or otherwise, without touching the > code base for any particular implementation. > For those whose know one of the implementation languages, source code > control systems allow one to do experiments on branches without 'sullying' > the trunk or impeding the development thereof. When I said "without having to sully the code base", I meant that one can implement a language feature for the target language as a loadable module written entirely within the language itself, and without having to understand anything particularly deep or specific about the language implementation details. I.e., I could write a new object system for Lisp faster than I could even begin to fathom the internal of CPython. Not only that, I have absolutely no desire to spend my valuable free time writing C code. I'd much rather be hacking in Python, thank you very much. > One of the goals of the PyPy project was to allow people to experiment with > syntax extensions in Python itself. (But I don't know how easy that is > yet.) PyPy sounds like a very interesting project indeed! > But I think that overall the problem of designing new syntax is more > in the design than the implementation. Anything new has to be > usable, readable, not clash too much with existing style, not > introduce ambiguities, and not move the extended language outside > the LL(1) [I believe that is right] subset of CFLs. People (myself included) haven't had much trouble implementing nice and useful macro packages for Lisp. Admittedly, it's a harder problem for a language that doesn't have a Lisp-like syntax. I believe that Dylan has macros without having a Lisp-like syntax, but Dylan is really a dialect of Lisp, only with a more traditional Algol-like syntax veneered onto it. My guess is that a macro developer for Dylan would have to be familiar with an underlying hidden intermediate Lisp syntax. (Though I'm just really just spouting that guess out of my butt.) A few years back, I designed a somewhat Python-like language with a macro facility for a class on dynamic languages and their implementations. I didn't implement it, however, and I doubt that I'll have time to get around to it in this lifetime. |>oug From gagsl-py2 at yahoo.com.ar Thu Jun 28 23:47:16 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 29 Jun 2007 00:47:16 -0300 Subject: equality & comparison by default (was Re: Too many 'self' in python.That's a big flaw in this language.) References: <1182942154.185461.89620@e9g2000prf.googlegroups.com> <1i0cy8z.z94q5d1dxgexxN%aleax@mac.com> Message-ID: En Thu, 28 Jun 2007 11:38:56 -0300, A.T.Hofkamp escribi?: > The point I intended to make was that having a default __hash__ method on > objects give weird results that not everybody may be aware of. > In addition, to get useful behavior of objects in sets one should > override > __hash__ anyway, so what is the point of having a default > object.__hash__ ? __hash__ and equality tests are used by the dictionary implementation, and the default implementation is OK for immutable objects. I like the fact that I can use almost anything as dictionary keys without much coding. This must always be true: (a==b) => (hash(a)==hash(b)), and the documentation for __hash__ and __cmp__ warns about the requisites (but __eq__ and the other rich-comparison methods are lacking the warning). -- Gabriel Genellina From bruno.desthuilliers at gmail.com Sun Jun 10 07:36:35 2007 From: bruno.desthuilliers at gmail.com (bruno.desthuilliers at gmail.com) Date: Sun, 10 Jun 2007 04:36:35 -0700 Subject: Python's "only one way to do it" philosophy isn't good? In-Reply-To: References: <1181368143.874341.273140@r19g2000prf.googlegroups.com> Message-ID: <1181475395.749525.185520@m36g2000hse.googlegroups.com> On Jun 9, 12:16 pm, James Stroud wrote: > Terry Reedy wrote: > > In Python, you have a choice of recursion (normal or tail) > > Please explain this. I remember reading on this newsgroup that an > advantage of ruby (wrt python) is that ruby has tail recursion, implying > that python does not. Does python have fully optimized tail recursion as > described in the tail recursion Wikipedia entry? Under what > circumstances can one count on the python interpreter recognizing the > possibility for optimized tail recursion? > I'm afraid Terry is wrong here, at least if he meant that CPython had tail recursion *optimization*. (and just for those who don't know yet, it's not a shortcoming, it's a design choice.) From justin.mailinglists at gmail.com Wed Jun 20 06:40:06 2007 From: justin.mailinglists at gmail.com (Justin Ezequiel) Date: Wed, 20 Jun 2007 10:40:06 -0000 Subject: something similar to shutil.copytree that can overwrite? In-Reply-To: <1182331815.865344.190700@u2g2000hsc.googlegroups.com> References: <1182331815.865344.190700@u2g2000hsc.googlegroups.com> Message-ID: <1182336006.442871.287590@a26g2000pre.googlegroups.com> On Jun 20, 5:30 pm, Ben Sizer wrote: > I need to copy directories from one place to another, but it needs to > overwrite individual files and directories rather than just exiting if > a destination file already exists. What version of Python do you have? Nothing in the source would make it exit if a target file exists. (Unless perhaps you have sym-links or the like.) Python 2.4.4 (#71, Oct 18 2006, 08:34:43) [MSC v.1310 32 bit (Intel)] copytree calls copy2 which calls copyfile from shutil.py: #-------------------------------------------------------------------- def _samefile(src, dst): # Macintosh, Unix. if hasattr(os.path,'samefile'): try: return os.path.samefile(src, dst) except OSError: return False # All other platforms: check for same pathname. return (os.path.normcase(os.path.abspath(src)) == os.path.normcase(os.path.abspath(dst))) def copyfile(src, dst): """Copy data from src to dst""" if _samefile(src, dst): raise Error, "`%s` and `%s` are the same file" % (src, dst) fsrc = None fdst = None try: fsrc = open(src, 'rb') fdst = open(dst, 'wb') copyfileobj(fsrc, fdst) finally: if fdst: fdst.close() if fsrc: fsrc.close() #-------------------------------------------------------------------- From srikrishnamohan at gmail.com Tue Jun 5 05:16:59 2007 From: srikrishnamohan at gmail.com (km) Date: Tue, 5 Jun 2007 14:46:59 +0530 Subject: Please help on Binary file manipulation In-Reply-To: References: Message-ID: Hi, I assume ur on a linux/unix box... pls check the manual for 'split' command in linux/unix this does ur job regards, KM --------------------------------------------------------------------------------------------------------------------------- On 6/5/07, Pieter Potgieter wrote: > > Hi all > I have a binary file of about 600kbytes - I want to break it up in file > chunks of 1085 bytes - every file must have a new file name. > The data is binary video frames (370 frames) - I want to play the data > back into an embedded system frame/file by file. > I am a complete Python newby - but have C/C++ skills. > Please supply/help me with an snippet or example > Thanks > Pieter > > > ******************************************************************************************************* > > Disclaimer: The information contained in this communication is > confidential and may be legally privileged. > > It is intended solely for the use of the individual or entity to whom it > is addressed and others authorised to receive it. > > Any review, retransmission, dissemination, copying, disclosure or other > use of, or taking of any action in reliance upon, this information by person > or entities other then the intended recipient is prohibited. > > If you have received this message in error, please notify the sender > immediately by e-mail, facsimile or telephone and return and/or destroy the > original message and all copies from any computer. > > Denel (Pty) Ltd exercises no editorial control over e-mail messages > originating in the organisation and does not accept any responsibility for > either the contents of the message or any copyright laws that may have been > violated by the person sending this message. > > Denel (Pty) Ltd is neither liable for the proper and complete transmission > of the information contained in this communication nor any delay in its > receipt. > > This message should not be copied or used for any purpose other than > intended, nor should it be disclosed to any other person. > > > ******************************************************************************************************* > > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From kareta at web.de Thu Jun 21 07:31:26 2007 From: kareta at web.de (Juergen Kareta) Date: Thu, 21 Jun 2007 13:31:26 +0200 Subject: fetching text from the screen In-Reply-To: References: <5dnbq8F341tilU1@mid.individual.net> Message-ID: <5dv6g3F35qel7U1@mid.individual.net> Gabriel Genellina schrieb: > En Mon, 18 Jun 2007 09:13:16 -0300, Juergen Kareta > escribi?: > >> I'm thinking about a python script which fetch some text from the screen >> independent of what application provides the text on the screen. In this >> regard it should be similar to the babylon software: www.babylon.com >> >> >> Here my thoughts: >> >> 1) getting the mouse position >> 2) calculate a adequate rectangle around the mouse position >> 3) fetch the screen content in this rectangle >> 4) use a OCR library to get the text out of 3) >> 5) do something usefull with it. > > > On Windows, I'd try first using WindowFromPoint to get a window handle, > and the sending it a WM_GETTEXT message. This should work for all > windowed controls that contain text of some kind. I'd use your generic > approach when this doesn't work. > Hi Gabriel, thanks for your interesting suggestions. I'll try that to figure out, how it works in different situations. J?rgen From arorap at gmail.com Wed Jun 13 09:47:31 2007 From: arorap at gmail.com (arorap) Date: Wed, 13 Jun 2007 06:47:31 -0700 Subject: cgi.FieldStorage() not working on Windows In-Reply-To: <1181721697.803594.208260@q19g2000prn.googlegroups.com> References: <1181661435.258140.17800@x35g2000prf.googlegroups.com> <1181692790.432649.273820@i13g2000prf.googlegroups.com> <1181703494.047837.26120@i38g2000prf.googlegroups.com> <1181721697.803594.208260@q19g2000prn.googlegroups.com> Message-ID: <1181742451.405813.303490@n15g2000prd.googlegroups.com> OOps .. yes I mean mod_python. I've been using PHP way too long :P .. hence the typo On Jun 13, 4:01 am, Graham Dumpleton wrote: > On Jun 13, 12:58 pm,arorap wrote: > > > Thanks for your reply. > > > The reason I want to run it as CGI (even though mod_php is available > > on my local computer > > Why do you keep mentioning mod_php, surely you mean mod_python. > > > is that the target machine to which I will > > finally be uploading my scripts runs CGI. > > > cgihandler should work just like CGI. > > I wouldn't rely on it being exactly the same. The way it works uses a > number of kludges. Also, the mod_python.cgihandler code in mod_python > doesn't really get much attention from mod_python developers anymore > and not sure if it was even specifically retested when mod_python 3.3 > was released. > > > Any clue why the > > cgi.FieldStorage()might not be working ? > > Have no idea why it doesn't work as works as written on MacOS X even > when mod_python.cgihandler is used. > > You'll have to get someone else who has Windows to try it. You might > be better off going to the mod_python mailing list to get help, or > just use plain old CGI instead since using mod_python isn't really > going to gain you much anyway. > > Graham > > > > > On Jun 12, 7:59 pm, Graham Dumpleton > > wrote: > > > > On Jun 13, 1:17 am,arorap wrote: > > > > > I've mod_php installed with Apache 2.2. In one of my folders, I'm > > > > using the cgihandler as the PythonHandler as my target host runs > > > > python only as CGI. Here cgi.FieldStorage() doesn't seem to work. I > > > > can see the form data in sys.stdin but cgi.FieldStorage() returns an > > > > empty dictionary. Here's the code for the test script I am posting to > > > > - > > > > > -- > > > > #!/usr/bin/python > > > > > import os > > > > import cgi > > > > import sys > > > > > print "Content Type: text/plain\n\n" > > > > print "Hello CGI World !\n" > > > > > for key in os.environ: > > > > print key + "= " + os.environ[key] > > > > > print cgi.FieldStorage() > > > > > print sys.stdin.read() > > > > -- > > > > > And here's the output I see .. > > > > > -- > > > > Hello CGI World ! > > > > > HTTP_REFERER=http://learnpython/form.htm > > > > SERVER_SOFTWARE= Apache/2.2.4 (Win32)mod_python/3.3.1 Python/2.5.1 > > > > SCRIPT_NAME= /mptest.py > > > > SERVER_SIGNATURE= > > > > REQUEST_METHOD= POST > > > > SERVER_PROTOCOL= HTTP/1.1 > > > > QUERY_STRING= abc=ayz > > > > PATH= C:\Program Files\Internet Explorer;;C:\WINDOWS\system32;C: > > > > \WINDOWS;C:\WINDOWS\System32\Wbem;q:\bin;m:\cm\clearcase\bin;M:\PERL\NT > > > > \EXEC\BIN;m:\cm\clearcase\bin\nt;M:\Perl\NT\EXEC\BIN;m:\perl\nt\exec > > > > \bin;m:\cm\clearcase\utils;q:\bin;m:\opus;m:\tvcs;C:\highc331\bin;C: > > > > \Program Files\Rational\ClearCase\bin;C:\Program Files\Rational\common > > > > CONTENT_LENGTH= 86 > > > > HTTP_USER_AGENT= Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; > > > > SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727) > > > > HTTP_CONNECTION= Keep-Alive > > > > SERVER_NAME= learnpython > > > > REMOTE_ADDR= 127.0.0.1 > > > > PATHEXT= .COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH > > > > SERVER_PORT= 80 > > > > SERVER_ADDR= 127.0.0.1 > > > > DOCUMENT_ROOT= D:/Projects/LearnPython/www > > > > COMSPEC= C:\WINDOWS\system32\cmd.exe > > > > SCRIPT_FILENAME= D:/Projects/LearnPython/www/mptest.py > > > > SERVER_ADMIN= puneet.ar... at tekelec.com > > > > HTTP_HOST= learnpython > > > > SystemRoot= C:\WINDOWS > > > > HTTP_CACHE_CONTROL= no-cache > > > > REQUEST_URI= /mptest.py?abc=ayz > > > > HTTP_ACCEPT= */* > > > > WINDIR= C:\WINDOWS > > > > GATEWAY_INTERFACE= Python-CGI/1.1 > > > > REMOTE_PORT= 1081 > > > > HTTP_ACCEPT_LANGUAGE= en-us > > > > CONTENT_TYPE= application/x-www-form-urlencoded > > > > HTTP_ACCEPT_ENCODING= gzip, deflate > > > > > FieldStorage(None, None, []) > > > > > firstName=puneet&address=hawaii > > > > -- > > > > > I am posting to this script using a form with two text fields named > > > > firstName and address. > > > > > any clue where am I going wrong ? > > > > You don't need mod_python/cgihandler to run CGI scripts. Rather than > > > bring mod_python into the picture and confuse things, set up Apache to > > > run your script as a traditional CGI script instead. > > > > BTW, the fact that mod_python is loaded means that CGI scripts aren't > > > the only way of using Python available to you as you seem to think. > > > So, suggest you do some research as to what the differences are > > > between CGI and mod_python.- Hide quoted text - > > - Show quoted text - From robin at reportlab.com Tue Jun 26 06:11:39 2007 From: robin at reportlab.com (Robin Becker) Date: Tue, 26 Jun 2007 11:11:39 +0100 Subject: simplifying algebraic expressions In-Reply-To: <46805dae$1@news.orcon.net.nz> References: <46805dae$1@news.orcon.net.nz> Message-ID: <4680E65B.6000201@chamonix.reportlab.co.uk> > Hi, > > Are there any libraries for manipulating algebraic expression trees? > In particular, take an expression tree and simplify it down. > > I'm working up the next release of PyGene, the genetic programming and > genetic algorithms library. > > Part of PyGene works with trees holding algebraic expressions. For > example, the expression: > f = x**2 + sqrt(y) + 7 > is represented as the tree: > > + > ** > x > 2 > + > sqrt > y > 7 > > My GP code is successfully evolving expression trees to solve problems, > however they're often full of redundancies, eg adding y in one part then > subtracting y later on. I have seen this sort of evolution strategy in the past and it's very wrong to attempt to simplify outside the genetic framework. The implication is that you know better than the overall fitness requirement. The additional expressions and redundancies allow for extra mutation and combination possibilities which is a good thing for the whole population. If you must, add the requirement to the target ie give extra fitness points to organisms which perform efficiently. -- Robin Becker From ping.nsr.yeh at gmail.com Fri Jun 15 13:52:55 2007 From: ping.nsr.yeh at gmail.com (Ping) Date: Fri, 15 Jun 2007 17:52:55 -0000 Subject: a_list.count(a_callable) ? In-Reply-To: <1181920645.597497.133930@m36g2000hse.googlegroups.com> References: <1181850818.567840.251090@x35g2000prf.googlegroups.com> <1181853479.914070.217270@i13g2000prf.googlegroups.com> <1181855184.511137.100870@z28g2000prd.googlegroups.com> <1181916937.648267.163070@z28g2000prd.googlegroups.com> <1181920645.597497.133930@m36g2000hse.googlegroups.com> Message-ID: <1181929975.491931.3200@o11g2000prd.googlegroups.com> On 6 15 , 11 17 , Dustan wrote: > On Jun 15, 9:15 am, Ping wrote: > > > > sum(1 for i in a_list if a_callable(i)) > > > > -- > > > Carsten Haesehttp://informixdb.sourceforge.net > > > This works nicely but not very intuitive or readable to me. > > > First of all, the generator expression makes sense only to > > trained eyes. Secondly, using sum(1 ...) to mean count() > > isn't very intuitive either. > > Then wrap it in a function: > def count(a_list, a_function): > return sum(1 for i in a_list if a_function(i)) > > And call the function. You can also give it a different name (although > I can't think of a concise name that would express it any better). > Hmm... This sounds like the best idea so far. It is efficient both in memory and time while exposes an easy-to-understand name. I would name the function count_items though. n = count_items(a_list, lambda x: x > 3) # very readable :) cheers, Ping From bruno.42.desthuilliers at wtf.websiteburo.oops.com Wed Jun 20 08:13:11 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Wed, 20 Jun 2007 14:13:11 +0200 Subject: Help With Better Design In-Reply-To: <1182303267.427179.223720@i13g2000prf.googlegroups.com> References: <1182303267.427179.223720@i13g2000prf.googlegroups.com> Message-ID: <467919ca$0$28811$426a74cc@news.free.fr> apollonius2 at gmail.com a ?crit : > Greetings, > > I have been working on a little project today to help me better > understand classes in Python (I really like Python). I am a self > taught programmer and consider myself to fall in the "beginner" > category for sure. It was initially sparked by reading about "state > machines". This was my attempt at it however I feel it is not quite > where it should be: > First, a few general comments > ON = "ON" > OFF = "OFF" > > class LightBulb: Better to use newstyle classes: class LightBulb(object): > def __init__(self, initial_state): > self.state = initial_state > > def TurnOn(self): Pep-08 (naming conventions): def turn_on(self): > if self.state == OFF: > self.state = ON > else: > print "The Bulb Is Already ON!" > > def TurnOff(self): > if self.state == ON: > self.state = OFF > else: > print "The Bulb Is Aleady OFF!" What about: class LightBulb(object): def __init__(self, state): self.state = state def switch(self): self.state = not self.state (snip) > I would like to be able to get a good hold of the concept state machines ? > with this example before I try to model a more complex problem. Would > someone be willing to give me some feedback on this class and whether > I am on the right track or how I might better go about it? There is a lot to say about OO and state machines. Someone once defined the use of OO in simulations as "building an big unpredictable state machine from small predictable state machines". As a matter of fact, objects are (most of the time) informal state machines (they have state, and they have behaviour depending on state). Now there are much more formal state machines (google for "FSM" or "finite state machine") - which can be implemented in a lot of ways - including the "State" design pattern. Before jumping to implementation, you should probably try to model the "more complex problem" with something like UML state diagram (one of the few usable things in UML). My 2 cents From gagsl-py2 at yahoo.com.ar Mon Jun 18 19:27:08 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 18 Jun 2007 20:27:08 -0300 Subject: fetching text from the screen References: <5dnbq8F341tilU1@mid.individual.net> Message-ID: En Mon, 18 Jun 2007 09:13:16 -0300, Juergen Kareta escribi?: > I'm thinking about a python script which fetch some text from the screen > independent of what application provides the text on the screen. In this > regard it should be similar to the babylon software: www.babylon.com > > > Here my thoughts: > > 1) getting the mouse position > 2) calculate a adequate rectangle around the mouse position > 3) fetch the screen content in this rectangle > 4) use a OCR library to get the text out of 3) > 5) do something usefull with it. On Windows, I'd try first using WindowFromPoint to get a window handle, and the sending it a WM_GETTEXT message. This should work for all windowed controls that contain text of some kind. I'd use your generic approach when this doesn't work. -- Gabriel Genellina From sclewin at gmail.com Tue Jun 26 09:40:40 2007 From: sclewin at gmail.com (Scott) Date: Tue, 26 Jun 2007 06:40:40 -0700 Subject: Change Geany Syntax Highlighting Message-ID: <1182865240.610073.301480@n60g2000hse.googlegroups.com> Hi, I think I may have finally found a IDE/text editor that I like, but, it still haves one problem. Geany haves syntax highlighting, but it is not very good for Python. It only seems to have a couple different colours. One for text and another for modules/classes/ functions. Is it possible to change the syntax highlighting for Python, so it highlights more and uses more different colours? I really liked the syntax highlighting for Python in kwrite/kate, but did not like the bugs. Your friend, Scott From shikha at consusitechnologies.com Tue Jun 19 08:08:22 2007 From: shikha at consusitechnologies.com (Shikha Tomar) Date: Tue, 19 Jun 2007 17:38:22 +0530 Subject: Urgent Onsite opportunity for Python Developers Message-ID: <00a101c7b26a$89e06310$ce05a8c0@SYSTELGGN5> Hi, This is in Reference to the position for the direct client of Consus iTechnologies ( www.consusitechnologies.com) for Python Developer. We have reviewed your resume on one of the portal and a client of ours has a position available that we thought you might be interested in. Job Title: Python Developer Relevant Experience: 2+ yrs Location : Gurgaon / US Company : Navisite If you are interested in the position, please feel free to e-mail us at the address given below or call us at 9910353107 along with a word formatted resume of yours giving details of the projects you have done and the number of years of experience you have in the above mentioned skill sets and information about the following: 1. Updated word formatted resume. 2. Portfolio of works done 3. Current salary & expected salary 4. Availability status If you are not in the market at this time feel free to forward this information to a friend or associate that has identical skills and might be interested in this position. GIVE US THE BEST NUMBERS TO REACH YOU (TELEPHONE/ MOBILE NUMBERS) SO THAT WE CAN PROCEED IN RECRUITING PROCESS Thanks & Regards, Shikha Tomar Resourcing Specialist Consus iTechnologies Ltd. shikha at consusitechnologies.com Mob.9910353107 From pytkvtk at gmail.com Tue Jun 26 09:36:32 2007 From: pytkvtk at gmail.com (Olivier Feys) Date: Tue, 26 Jun 2007 15:36:32 +0200 Subject: _hashlib portability issue Message-ID: <46811660.4060905@gmail.com> Hi all, I build python 2.5 on linux-x86-64 (centos). Why is lib-dynload/_hashlib.so dynamically linked with libssl.so.0.9.7 and not with libssl.so that points on it (same thing for libcrypto.so)? This causes problems when copying all the python distribution and running it on a different os, where the theses lib versions are not allways the same. Is it possible to configure that ? thanks, Olivier From spamtrap at dot-app.org Thu Jun 14 00:29:09 2007 From: spamtrap at dot-app.org (Sherm Pendley) Date: Thu, 14 Jun 2007 00:29:09 -0400 Subject: Build EXE on Mac OsX 10.4 References: <1181762699.145088.159500@j4g2000prf.googlegroups.com> <46705507.4000201@ulmcnett.com> Message-ID: "Gabriel Genellina" writes: > En Wed, 13 Jun 2007 17:35:19 -0300, Paul McNett

          escribi?: > >> Tempo wrote: >>> Has anyone sucesfully built a *.exe file on a mac operating system >>> before from a *.py file? I have been trying to do this with >>> pyinstaller, but I keep getting errors and I don't know how to >>> install [...] >> >> You need to build Mac Apps on Mac, Windows EXE's on Windows, and Linux >> ELF's on Linux. You can't build a windows.exe from Mac, just as you >> can't build a mac.app from Windows. > > That's not entirely true. gcc on linux can generate a Windows EXE, and > using: python setup.py bdist_wininst, you can generate a complete > binary installer for Windows. I'm not sure if this can be done on a > Mac too. In principle, certainly - there's even a MacPort package for a complete cygwin installation. I've built a number of packages with it - SDL and several related libraries, for instance. There are also ELF cross-compiler MacPort packages, presumably for building Linux binaries. On the other hand, I *haven't* tried any of those compilers with setup.py, and I have no idea if it can support those targets in practice. :-( sherm-- -- Web Hosting by West Virginians, for West Virginians: http://wv-www.net Cocoa programming in Perl: http://camelbones.sourceforge.net From see.signature at no.spam Wed Jun 13 03:21:18 2007 From: see.signature at no.spam (Eric Brunel) Date: Wed, 13 Jun 2007 09:21:18 +0200 Subject: Tamil/Indian Languages Support in Tkinter References: <1181669558.321094.111440@d30g2000prg.googlegroups.com> Message-ID: On Tue, 12 Jun 2007 19:32:38 +0200, reverse_gear wrote: > hi, > Does Tkinter has support for tamil/Indian Languages?? > I tried this code > it is able to print both tamil and german text on console.. but on > Tkinter Label it is printing only the german code > Plz help > from Tkinter import * > import codecs > > german_ae = unicode('\xc3\xa4','utf-8') > tamil_text = unicode('\xe0\xae\xb9\xe0\xae\xbf \xe0\xae\xae\xe0\xaf > \x81\xe0\xae\x95\xe0\xaf\x81\xe0\xae\xa9\xe0\xaf\x8d\xe0\xae\x9f > \xe0\xaf\x8d','utf-8') > root = Tk() > print tamil_text > print german_ae > label = Label(root, text = german_ae) > label2= Label(root, text = tamil_text) > label.pack() > label2.pack() > mainloop() If you have a recent version of tcl/tk, it should work as long as you have the proper fonts installed.BTW, I tried it and the tamil text didn't show at all on my Linux box: no text on the console (just squares) and nothing in the Tkinter label. But I certainly don't have any font able to display these characters. This is apparently not your problem since if it works on the console, you should have a usable font. So my guess would be that some font installed on your system claims to be able to display these characters, but actually isn't. Since you didn't specify a font to use in your labels and the default font probably can't display tamil, tk looks for a font that can. When it finds one, it stops and uses it. So if a font claims to have these characters, but actually can't display them, you end up with a blank text. Did you try to specify the font to use in the labels? A good candidate would obviously be the font used by the console. And you didn't specify on which platform you were, or your Python and tcl/tk version. This may help... HTH -- python -c "print ''.join([chr(154 - ord(c)) for c in 'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])" From Leo.Kislov at gmail.com Fri Jun 1 03:11:17 2007 From: Leo.Kislov at gmail.com (Leo Kislov) Date: Fri, 01 Jun 2007 00:11:17 -0700 Subject: Python memory handling In-Reply-To: <1180623978.372352.194860@q69g2000hsb.googlegroups.com> References: <1180611604.247696.149060@h2g2000hsg.googlegroups.com> <1180623978.372352.194860@q69g2000hsb.googlegroups.com> Message-ID: <1180681877.539035.133270@z28g2000prd.googlegroups.com> On May 31, 8:06 am, frederic.pica at gmail.com wrote: > Hello, > > I will try later with python 2.5 under linux, but as far as I can see, > it's the same problem under my windows python 2.5 > After reading this document :http://evanjones.ca/memoryallocator/python-memory.pdf > > I think it's because list or dictionnaries are used by the parser, and > python use an internal memory pool (not pymalloc) for them... > If I understand the document correctly you should be able to free list and dict caches if you create more than 80 new lists and dicts: [list(), dict() for i in range(88)] If it doesn't help that means 1) list&dict caches don't really work like I think or 2) pymalloc cannot return memory because of fragmentation and that is not simple to "fix". -- Leo From mgedmin at gmail.com Mon Jun 11 12:22:43 2007 From: mgedmin at gmail.com (Marius Gedminas) Date: Mon, 11 Jun 2007 09:22:43 -0700 Subject: *Naming Conventions* In-Reply-To: References: <1180909218.939713.112010@q69g2000hsb.googlegroups.com> <1180990280.960271.235550@h2g2000hsg.googlegroups.com> <466699e9$0$2308$426a74cc@news.free.fr> Message-ID: <1181578963.585174.106330@n4g2000hsb.googlegroups.com> On Jun 6, 3:18 pm, Neil Cerutti wrote: > > Since 'i' and 'j' are canonically loop indices, I find it > > totally confusing to use them to name the iteration variable - > > which is not an index. > > Certainly i and j are just as generic, but they have the > advantage over 'item' of being more terse. Python programmers usually prefer readability over terseness. Finding a variable named 'i' that is not an integer index would be surprising to me. From simonroses at granisla.com Thu Jun 28 14:38:18 2007 From: simonroses at granisla.com (simonroses at granisla.com) Date: Thu, 28 Jun 2007 20:38:18 +0200 (CEST) Subject: Vista 64 + Python2.5 + wxpython 28 issue Message-ID: <20066.83.60.166.24.1183055898.squirrel@webmail.granisla.com> Hello Guys, I have installed python 2.5 (AMD64) on Vista (64), also installed wx 2.8 but I'm getting this error: """" Traceback (most recent call last): File "mymodule.py", line 39, in import wx File "C:\Python25\Lib\site-packages\wx-2.8-msw-unicode\wx\__init__.py", line 4 5, in from wx._core import * File "C:\Python25\Lib\site-packages\wx-2.8-msw-unicode\wx\_core.py", line 4, i n import _core_ ImportError: DLL load failed with error code 193 """ I have set python.exe to run under admin but that do not fix the problem. Any ideas ? Thanks! Sincerely, SRF From raacampbell at gmail.com Sun Jun 24 10:12:53 2007 From: raacampbell at gmail.com (raacampbell at gmail.com) Date: Sun, 24 Jun 2007 14:12:53 -0000 Subject: how to query/test the state of a qt widget? In-Reply-To: <5e7aq6F37in8eU1@mid.uni-berlin.de> References: <1182644455.491518.97260@u2g2000hsc.googlegroups.com> <5e7aq6F37in8eU1@mid.uni-berlin.de> Message-ID: <1182694373.567897.130970@w5g2000hsg.googlegroups.com> > RTFM. The Qt-docs are extensive. And the QRadioButton-docs are pretty > straight forward: > > http://doc.trolltech.com/3.3/qradiobutton.html#checked-prop > > So your code above should be > > if self.polPlotRadioButton.isChecked(): print "blah" Thanks, that does indeed work. Also, sorry, I have been trying to RTFM but I'm new to both Python and Qt so not always sure what I'm looking for. From owntheweb at gmail.com Thu Jun 21 10:34:42 2007 From: owntheweb at gmail.com (Ultrus) Date: Thu, 21 Jun 2007 14:34:42 -0000 Subject: Edit Audio Using Python? In-Reply-To: <1182375392.825047.141120@w5g2000hsg.googlegroups.com> References: <1182353535.158899.128650@n2g2000hse.googlegroups.com> <1182356488.189503.122180@g4g2000hsf.googlegroups.com> <1182375392.825047.141120@w5g2000hsg.googlegroups.com> Message-ID: <1182436482.889795.159400@n2g2000hse.googlegroups.com> Aaron, Thanks for sharing this! > I think you'll find that you have to put a lot of pieces together > to manipulate audio -- it's all there, but it's not straightforward. The challenge of building something unique makes it more worth while. > I did it in my "skimpygimpy" audio components, which may help > (especially > if you ignore the stranger parts where I went off the deep end). Sweet program. I wish I had access to it on websites where I can never seem to read the captcha letters. The waveTools are VERY helpful! My biggest wall was getting samples from audio files. Your scripts go beyond that. I'll play with the scripts once I know a bit more on Python, and send you an update if I expand upon it. Thank you From Ognjen at mailshack.com Mon Jun 18 16:46:23 2007 From: Ognjen at mailshack.com (Ognjen Bezanov) Date: Mon, 18 Jun 2007 21:46:23 +0100 Subject: Making static dicts? Message-ID: <4676EF1F.4030300@mailshack.com> Hello! Just to ask, is it possible to make a static dictionary in python. So that the keys in the dictionary cannot be removed, changed or new ones added, but the value pairs can. Is this possible with python? thanks, Ognjen. From steven.bethard at gmail.com Tue Jun 12 16:34:41 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 12 Jun 2007 14:34:41 -0600 Subject: SimplePrograms challenge In-Reply-To: <1181649968.097585.131780@g37g2000prf.googlegroups.com> References: <1181649968.097585.131780@g37g2000prf.googlegroups.com> Message-ID: Rob Wolfe wrote: > Steve Howell wrote: >> Hi, I'm offering a challenge to extend the following >> page by one good example: >> >> http://wiki.python.org/moin/SimplePrograms > > What about simple HTML parsing? As a matter of fact this is not > language concept, but shows the power of Python standard library. > Besides, that's very popular problem among newbies. This program > for example shows all the linked URLs in the HTML document: > > > from HTMLParser import HTMLParser [Sorry if this comes twice, it didn't seem to be showing up] I'd hate to steer a potential new Python developer to a clumsier library when Python 2.5 includes ElementTree:: import xml.etree.ElementTree as etree page = ''' URLs

          ''' tree = etree.fromstring(page) for a_node in tree.getiterator('a'): url = a_node.get('href') if url is not None: print url I know that the wiki page is supposed to be Python 2.4 only, but I'd rather have no example than an outdated one. STeVe From aleax at mac.com Sat Jun 23 20:51:17 2007 From: aleax at mac.com (Alex Martelli) Date: Sat, 23 Jun 2007 17:51:17 -0700 Subject: is this a valid import sequence ? References: <4f97$467c254d$d443bb3a$9522@news.speedlinq.nl> <137qo1egg4v1k04@corp.supernews.com> Message-ID: <1i0694u.1n6evsntoei0wN%aleax@mac.com> Steven D'Aprano wrote: > On Sat, 23 Jun 2007 11:03:03 -0700, Scott David Daniels wrote: > > > The global statement in Write_LCD_Data is completely unnecessary. The > > only time you need "global" is if you want to reassociate the global > > name to another object (such as LCD = LCD + 1 or whatever). > > That's technically true, but declaring it with global makes the code > self-documenting and therefore easier to read. > > It's never _wrong_ to use the global statement, even if it is strictly > unnecessary for the Python compiler. So, repeat that global statement ninetyseven times -- that's not "wrong", either, in exactly the same sense in which it's not "wrong" to have it once -- the Python compiler will not complain. And by repeating it over and over you make it less likely that a reader could miss it, so it's even more "self-documenting" and "easier to read", right? "Perfection is reached, not when there is no longer anything to add, but when there is no longer anything to take away", as Antoine de Saint-Exupery wrote. Since that global statement is utterly useless (it's impossible to read and understand any substantial amount of Python code without realizing that accessing a variable not locally assigned means you're accessing a global, so the "self-documenting" character claimed for that redundancy is quite fallacious), it IS perfectly suitable to take away, and so it's at least a serious imperfection. It violates Occam's Razor, by multiplying entities (specifically statements) without necessity. It's just about as bad as sticking a semicolon at the end of every statement (to make it "self-documenting" that the statement ends there), parentheses around the conditions in if and while statements and the argument in return statements (to make it "self-documenting" where those expressions start and end), and a few other less common ways to waste pixels, screen space, readers' attention spans, and everybody's time. In other words, it's almost as bad as it can get in Python without outright breakage of syntax or semantics ("almost" only because long comments that lie outright are worse:-). Alex From gluckj at gmail.com Sat Jun 30 04:52:15 2007 From: gluckj at gmail.com (gluckj at gmail.com) Date: Sat, 30 Jun 2007 08:52:15 -0000 Subject: shelve crashing under Win ME Message-ID: <1183193535.127098.299840@a26g2000pre.googlegroups.com> Hi, I'm not a Win ME fan myself (I'm a Mac user), but I'm here in Thailand developing software for special-needs kids, and the test PC in my home office is a Win ME machine (sigh). So when I ported my Python program today to the PC, it quickly crashed. Everything seems to work except for shelve. Using the latest version of Python (2.5.1), when I do the following in IDLE on the Win ME machine here's the result: Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit (Intel)] on win32 IDLE 1.2.1 >>> import shelve >>> f=shelve.open("foo") Traceback (most recent call last): File "", line 1, in f=shelve.open("foo") File "C:\PYTHON25\lib\shelve.py", line 225, in open return DbfilenameShelf(filename, flag, protocol, writeback) File "C:\PYTHON25\lib\shelve.py", line 209, in __init__ Shelf.__init__(self, anydbm.open(filename, flag), protocol, writeback) File "C:\PYTHON25\lib\anydbm.py", line 83, in open return mod.open(file, flag, mode) File "C:\PYTHON25\lib\dbhash.py", line 16, in open return bsddb.hashopen(file, flag, mode) File "C:\PYTHON25\lib\bsddb\__init__.py", line 306, in hashopen d.open(file, db.DB_HASH, flags, mode) DBError: (5, 'Input/output error') >>> For those who know shelve, this should actually run fine (if the file "foo" does not exist it should create it). Printing the value of "f" should show an empty dictionary {}. It does run fine on my iBook (under Python 2.4.4) and on my iBook's Virtual PC running Win XP & Python 2.5.0. I do not think this is a Python 2.5.1 problem, because my first attempt to run my program on the Win ME machine was with a version of the program I ported using Py2exe on the VPC under Python 2.5.0, and it crashed the same way when run on the Win ME machine (I subsequently installed Python on the Win ME PC to try to get to the root of the problem.) Help! How do I get Win ME (or at least the misbehaving Win ME machine in my office) to run shelve? (or more specifically run bsddb's hashopen?) Or should I trash shelve entirely and rewrite all my code to use a simpler, homemade database scheme? Thanks for any advice! Warmly, Joel joelgluck at yahoo.com From ahlongxp at gmail.com Mon Jun 11 10:49:49 2007 From: ahlongxp at gmail.com (ahlongxp) Date: Mon, 11 Jun 2007 14:49:49 -0000 Subject: skip next item in list Message-ID: <1181573389.186279.108590@g37g2000prf.googlegroups.com> list=('a','d','c','d') for a in list: if a=='a' : #skip the letter affer 'a' what am I supposed to do? From rbonvall at gmail.com Thu Jun 7 13:28:29 2007 From: rbonvall at gmail.com (Roberto Bonvallet) Date: Thu, 07 Jun 2007 10:28:29 -0700 Subject: running a random function In-Reply-To: <1654405.LVbK4P6cM3@teancum> References: <1654405.LVbK4P6cM3@teancum> Message-ID: <1181237309.654271.147340@q66g2000hsg.googlegroups.com> On 7 jun, 11:56, David Bear wrote: > I would like to write some code that would randomly select a function from a > list of functions and call it. I was looking in the globals names space and > randomly selecting items that were of type function.. but I didn't see a > way of actually running the function. Try this: def f(x): print "Calling f with arg %s" % x def g(x): print "Calling g with arg %s" % x def h(x): print "Calling h with arg %s" % x import random functions = [f, g, h] for i in range(10): random.choice(functions)(25) HTH, cheers. -- Roberto Bonvallet From zzqcom4 at gmail.com Fri Jun 22 14:18:02 2007 From: zzqcom4 at gmail.com (com4) Date: Fri, 22 Jun 2007 12:18:02 -0600 Subject: Python IDE In-Reply-To: <1182249585.535675.143460@m36g2000hse.googlegroups.com> References: <1182249585.535675.143460@m36g2000hse.googlegroups.com> Message-ID: <9c34a0750706221118l4dc630dbk52282c31092d2a8d@mail.gmail.com> On 6/19/07, Tom Gur wrote: > > Hi, > which IDE would you recommend for a python ? I also use VIM, but I use a couple plugins to make it more ide-esque (If you can call it that). The first is the project plugin: http://vim.sourceforge.net/scripts/script.php?script_id=69 This will make a split window on the lefthand side with a list of files and folders. You can specify a file extension whitelist. *.py works out very well. I bind F3 to :Project to open and close that window quickly The other plugin I use is BufExplorer: http://www.vim.org/scripts/script.php?script_id=42 This will show you a list of open files and let you switch between them (S will split the choice with the current file(s)). I bind F2 to :BufExplorer -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From josiah.carlson at sbcglobal.net Sat Jun 2 16:37:54 2007 From: josiah.carlson at sbcglobal.net (Josiah Carlson) Date: Sat, 02 Jun 2007 20:37:54 GMT Subject: Non-blocking subprocess call In-Reply-To: <442be$4661b3e7$4275d90a$6641@FUSE.NET> References: <442be$4661b3e7$4275d90a$6641@FUSE.NET> Message-ID: Kevin Walzer wrote: > I'm currently using os.popen in an application of mine, which calls for > non-blocking data, in this fashion: > > self.file = os.popen('echo %s | sudo -S /sw/bin/fink -y install %s' % > (self.passtext, self.packagename), 'r', os.O_NONBLOCK) > > What is the equivalent/comparable call in the new subprocess module? I > can't find any reference in the Python docs to non-blocking streams. If you are talking about non-blocking reading and writing from the subprocess, there isn't natively. But there is a cookbook entry: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/440554 - Josiah From kyosohma at gmail.com Sun Jun 10 13:39:30 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Sun, 10 Jun 2007 17:39:30 -0000 Subject: Repository - file scanner In-Reply-To: References: <1181331239.609059.320740@g4g2000hsf.googlegroups.com> <1181403049.098884.115770@q66g2000hsg.googlegroups.com> Message-ID: <1181497170.824243.45440@n4g2000hsb.googlegroups.com> On Jun 9, 12:38 pm, "Gabriel Genellina" wrote: > En Sat, 09 Jun 2007 12:30:49 -0300, escribi?: > > > On Jun 8, 2:33 pm, HMS Surprise wrote: > >> Could someone point my muddled head at a/the python repository. I know > >> that one exists but cannot find it again. In particular I am looking > >> for a standalone search tool that given a path searches files for a > >> text string. > > > Are you looking for > > > A.) a Python script to search for file names that match a given text > > string? > > B.) a script to search for a given text string within a text file? > > C.) a Python repository, as in the SVN/CVS area? > > D.) The Python Package Index perhaps?http://www.python.org/pypi > > -- > Gabriel Genellina Sorry about the dual post...google groups was acting very weird for me yesterday. Mike From bbands at gmail.com Mon Jun 11 15:18:17 2007 From: bbands at gmail.com (BBands) Date: Mon, 11 Jun 2007 19:18:17 -0000 Subject: with as a reserved word In-Reply-To: References: <1181574196.682123.291010@a26g2000pre.googlegroups.com> Message-ID: <1181589497.399747.185440@z28g2000prd.googlegroups.com> On Jun 11, 11:34 am, Fredrik Lundh wrote: > if you have Python 2.5, you can try it out yourself: > > >>> dict(with=1) > :1: Warning: 'with' will become a reserved keyword in Python 2.6 > {'with': 1} > > >>> from __future__ import with_statement > >>> dict(with=1) > File "", line 1 > dict(with=1) > ^ > SyntaxError: invalid syntax I see that this change appears to be final. http://www.python.org/dev/peps/pep-0343/ I don't have an opinion, pro or con, on this PEP, but I'll bet that it breaks a lot of code. jab From J.P.Terlouw at astro.rug.nl Mon Jun 4 10:56:39 2007 From: J.P.Terlouw at astro.rug.nl (Hans Terlouw) Date: Mon, 04 Jun 2007 16:56:39 +0200 Subject: Pyrex: problem with blanks in string Message-ID: Hi, When trying to wrap C code using Pyrex, I encountered a strange problem with a piece of pure Python code. I tried to isolate the problem. The following code causes Pyrex to generate C code which gcc cannot compile: class Axis: axtype = "unknown type of axis" def __init__(self): pass When I substitute the blanks in the string for something else, then the problem disappears: class Axis: axtype = "unknown_type_of_axis" def __init__(self): pass Does anybody have an idea? Hans Terlouw From george.sakkis at gmail.com Mon Jun 11 11:22:58 2007 From: george.sakkis at gmail.com (George Sakkis) Date: Mon, 11 Jun 2007 15:22:58 -0000 Subject: Postpone creation of attributes until needed In-Reply-To: <1181572626.761699.158130@n4g2000hsb.googlegroups.com> References: <1181553891.447344.109390@g4g2000hsf.googlegroups.com> <1181559496.911368.219210@p77g2000hsh.googlegroups.com> <1181564855.890242.116840@m36g2000hse.googlegroups.com> <1181569088.048872.254700@m36g2000hse.googlegroups.com> <1181572626.761699.158130@n4g2000hsb.googlegroups.com> Message-ID: <1181575378.910750.281590@d30g2000prg.googlegroups.com> On Jun 11, 10:37 am, Frank Millman wrote: > On Jun 11, 3:38 pm, George Sakkis wrote: > >The boilerplate code can be minimal too with an appropriate > > decorator, something like: > > > class A(object): > > > def __init__(self,x,y): > > self.x = x > > self.y = y > > > @cachedproperty > > def z(self): > > return self.x * self.y > > > where cachedproperty is > > > def cachedproperty(func): > > name = '__' + func.__name__ > > def wrapper(self): > > try: return getattr(self, name) > > except AttributeError: # raised only the first time > > value = func(self) > > setattr(self, name, value) > > return value > > return property(wrapper) > > This is very neat, George. I will have to read it a few more times > before I understand it properly - I still have not fully grasped > decorators, as I have not yet had a need for them. You never *need* decorators, in the sense it's just syntax sugar for things you might do without them, but they're handy once you get your head around them. > Actually I did spend a bit of time trying to understand it before > posting, and I have a question. > > It seems that this is now a 'read-only' attribute, whose value is > computed by the function the first time, and after that cannot be > changed. It would probably suffice for my needs, but how easy would it > be to convert it to read/write? It's straightforward, just define a setter wrapper and pass it in the property along with the getter: def cachedproperty(func): name = '__' + func.__name__ def getter(self): try: return getattr(self, name) except AttributeError: # raised only the first time value = func(self) setattr(self, name, value) return value def setter(self, value): setattr(self, name, value) return property(getter,setter) HTH, George From doug at alum.mit.edu Fri Jun 29 09:45:18 2007 From: doug at alum.mit.edu (Douglas Alan) Date: Fri, 29 Jun 2007 09:45:18 -0400 Subject: Python's "only one way to do it" philosophy isn't good? References: <7xejjzmk7u.fsf@ruckus.brouhaha.com> <7xy7i7xjl5.fsf@ruckus.brouhaha.com> Message-ID: Dennis Lee Bieber writes: > LISP and FORTH are cousins... Not really. Their only real similarity (other than the similarities shared by most programming languages) is that they both use a form of Polish notation. |>oug From thomas at jollans.com Fri Jun 29 16:42:54 2007 From: thomas at jollans.com (Thomas Jollans) Date: Fri, 29 Jun 2007 22:42:54 +0200 Subject: appending file In-Reply-To: <0Jchi.16365$2v1.11172@newssvr14.news.prodigy.net> References: <0Jchi.16365$2v1.11172@newssvr14.news.prodigy.net> Message-ID: <200706292242.59165.thomas@jollans.com> On Friday 29 June 2007, Kuo wrote: > Hi, > I'm trying to read a file (fileA) and append to another file(fileB). > However, I always get "^M" at the end. Does anyone know why ? Here is my > code ? I can't help you on your problem, but > ucf.close; > pin.close; these statements don't do anything. You'll want ucf.close() pin.close() > sys.exit(0); > > Here is what I get. > > # FPGA CLOCK^M > NET "SYSCLK_A" loc = N16 | TNM_NET = SYSCLK_A;^M > NET "SYSCLK_AN" loc = M16 | TNM_NET = SYSCLK_A;^M > > > Note that if I don't do "ucf.write(pin.read())", everything is ok. > > Thanks for any help. -- Regards, Thomas Jollans GPG key: 0xF421434B may be found on various keyservers, eg pgp.mit.edu Hacker key : v4sw6+8Yhw4/5ln3pr5Ock2ma2u7Lw2Nl7Di2e2t3/4TMb6HOPTen5/6g5OPa1XsMr9p-7/-6 -------------- 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 walterbyrd at iname.com Mon Jun 4 15:37:10 2007 From: walterbyrd at iname.com (walterbyrd) Date: Mon, 04 Jun 2007 12:37:10 -0700 Subject: Who uses Python? Message-ID: <1180985830.288414.208850@q69g2000hsb.googlegroups.com> I mean other than sysadmins, programmers, and web-site developers? I have heard of some DBAs who use a lot of python. I suppose some scientists. I think python is used in bioinformatics. I think some math and physics people use python. I suppose some people use python to learn "programming" in general. Python would do well as a teaching language. I would think that python would be a good language for data analysis. Anything else? Finance? Web-analytics? SEO? Digital art? From bruno.42.desthuilliers at wtf.websiteburo.oops.com Fri Jun 15 07:53:20 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Fri, 15 Jun 2007 13:53:20 +0200 Subject: Want to learn Python In-Reply-To: <1181907696.878873.214760@i13g2000prf.googlegroups.com> References: <1181907696.878873.214760@i13g2000prf.googlegroups.com> Message-ID: <46727da4$0$1221$426a74cc@news.free.fr> Amol a ?crit : > Hi, I want to learn Python in less than a month which resources should > I use. Your brain ?-) (actually, a computer with Python installed on it may help too...) > I prefer to read books . Books are fine, but won't be of much help unless you actually *code* in Python. > Please give me a list of *recognized* > resources. http://wiki.python.org/moin/IntroductoryBooks => I'd recommand Mark Lutz's books and/or Mark Pilgrim's Dive Into Python http://wiki.python.org/moin/AdvancedBooks => the Python CookBook From bdesth.quelquechose at free.quelquepart.fr Mon Jun 25 00:31:09 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 25 Jun 2007 06:31:09 +0200 Subject: Collections of non-arbitrary objects ? In-Reply-To: <1182620734.940718.196520@e16g2000pri.googlegroups.com> References: <1182449993.223262.229500@z28g2000prd.googlegroups.com> <87k5twx4hf.fsf@benfinney.id.au> <1182559502.069773.321620@i38g2000prf.googlegroups.com> <87wsxvrzsj.fsf@benfinney.id.au> <1182620734.940718.196520@e16g2000pri.googlegroups.com> Message-ID: <467ed491$0$27132$426a34cc@news.free.fr> walterbyrd a ?crit : > On Jun 22, 11:43 pm, Ben Finney > wrote: > > >>Can you help us understand, by showing a use case that would in your >>estimation be improved by the feature you're describing? >> > > > Suppose you are sequentially processing a list with a routine that > expects every item to be of a certain type. it should expects every item to support a given protocol (expose a given interface, have a given set of attributes, whatever...). OOP is not about "types" or "classes", it's about objects. And in a dynamic language like Python, where you can add/remove/replace almost each attribute (including methods and even it's class...) of an object at runtime, override the way the attribute look-up is done, etc, this is specially true. The fact that an object is an instance of a given class doesn't necessarily imply that it supports the same protocol. And the fact that an object is an instance of a given class is only true at a given time... So testing on type to allow inclusion of an object in a list for "type safety" reasons is mostly a waste of time. It's also counter-productive since it would reject objects that actually supports the right protocol but are not of the "correct type". > Something in the list that > doesn't conform to the type s/conform to the type/support the protocol/ > could give you unexpected results, maybe > crash your application. Yes. But... you do test your application, don't you ?-) > In python, as far as I know, there is nothing built into the language > to keep any type of item from being included in a list No. cf above. > - or any such > structure. To me, that seems like a potentially vulnerability. Did you actually had some effective problem with this ? > Especially since variables in python do not have to be explicitly > assigned ??? I suppose you meant something else here, probably about declarative typing ? > - another variable that points to the same thing, could > change the data that a variable points to. Give me a reference to an object in a list, and I can change almost any attribute of the object - even it's class. FWIW, a similar - but usually much much worse wrt/ possible results - problem exists in C with pointers and memory. I came to Python from statically typed languages, and first had a similar reaction. It took me some time to believe it, but type errors are quite less frequent that you would imagine, and most of the time quite trivial to spot and fix. I've had bigger problems with memory handling and dangling pointers in C, Pascal or C++. From sipickles at hotmail.com Thu Jun 7 03:59:11 2007 From: sipickles at hotmail.com (Simon Pickles) Date: Thu, 07 Jun 2007 08:59:11 +0100 Subject: Help a C++ escapee! Message-ID: Hi, Can someone help me leave the murky c++ world and enter shiny pythonland? I have a problem with importing and global variables, here's my code: ---------------------------------------- ##server.py #socket connections from socketManager import* network = CNetworkManager() network.Listen() -------------------------------------- ##socketManager.py from time import sleep from socket import* import threading class CNetworkManager(): def __init__(self): self.hostName = "" self.portNumber = 15500 self.buffer = 500 self.serverAddress = ( self.hostName, self.portNumber ) self.maxClients = 2 ## previous stuff to send to new client self.serverData = [] self.serverSocket = socket ( AF_INET, SOCK_STREAM ) self.serverSocket.bind ( self.serverAddress ) print( "Socket started " ) self.serverSocket.listen ( self.maxClients ) print( "Server is waiting for a connection" ) def Listen(self): self.threadArray =[] self.ch = 0 while self.ch < self.maxClients: #Create a thread listening to each socket self.newThreadObject = CServerThread() self.newThreadObject.start() self. threadArray.append(self.newThreadObject) self.ch=self.ch+1 class CServerThread(threading.Thread): def run(self): while (1): self.clientSocket, self.clientAddress = network.accept() print("New Client:", self.clientAddress) if network.serverData: for i in range(len(network.serverData)): clientSocket.send(str(network.serverData[i])) sleep(0.01) else: clientSocket.send("You are logged in") print("Entering loop for client ", clientAddress ) while 1: clientData = clientSocket.recv(Buffer) if not clientData: print( clientAddress + " has closed the connection" ) break print( "%s says %s" % (clientAddress, clientData)) clientData = clientData + "~~" network.serverData.append(clientData) for i in range(len(network.serverData)): clientSocket.send(str(network.serverData[i])) sleep(0.01) print("Ready to receive more data") clientData.close() break network.serverSocket.close() -------------------------------------------------- When run, I come unstuck here: self.clientSocket, self.clientAddress = network.accept() I get a nameError on 'network', yet it is one in the global namespace, defined in server.py before CServerThread.Listen() is called. In c++, I understood how to declare variables, here I have a problem. Its like I need an extern statement from c++. Can anyone clarify this for me? Many thanks Simon _________________________________________________________________ Play your part in making history - Email Britain! http://www.emailbritain.co.uk/ From jstroud at mbi.ucla.edu Sat Jun 9 20:46:20 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sun, 10 Jun 2007 00:46:20 GMT Subject: Python's "only one way to do it" philosophy isn't good? In-Reply-To: <1181388490.279925.147030@g4g2000hsf.googlegroups.com> References: <1181368143.874341.273140@r19g2000prf.googlegroups.com> <1181388490.279925.147030@g4g2000hsf.googlegroups.com> Message-ID: Kay Schluehr wrote: > On Jun 9, 12:16 pm, James Stroud wrote: >> Terry Reedy wrote: >>> In Python, you have a choice of recursion (normal or tail) >> Please explain this. I remember reading on this newsgroup that an >> advantage of ruby (wrt python) is that ruby has tail recursion, implying >> that python does not. > > Proof by rumour? "Proof" if you define "proof" by asking for clarification about a vague recollection of an even more vague posting. I think now I'll prove Fermat's Last Theorem by hailing a cab. From see.signature at no.spam Thu Jun 7 06:01:06 2007 From: see.signature at no.spam (Eric Brunel) Date: Thu, 07 Jun 2007 12:01:06 +0200 Subject: Tkinter, tkMessagebox and overrideredirect References: <1181060331.167762.19180@q69g2000hsb.googlegroups.com> <1181132772.551848.192400@o5g2000hsb.googlegroups.com> <1181199864.217585.208370@q75g2000hsh.googlegroups.com> Message-ID: On Thu, 07 Jun 2007 09:04:24 +0200, wrote: [snip] > I can't believe there isn't an easier way to make a kiosk application > without titlebar. That's not the problem: there *is* an easy way, and you found it: overrideredirect(1). But now you're trying to mix windows ignored by the window manager - as you've told it to - and windows that *are* managed by the window manager. This is where the problem is. > Perhaps to create a normal window bigger than screen with title bar > outside it? This won't work on some platforms and/or with some window managers... And there's no portable way to do that, as sometimes, the dimensions you give for the window includes the window decorations, and sometimes they don't. > And after how can I ignore titlebar menu command or "x" and "-" > button? For the 'X' button, it's quite simple: myToplevel.protocol('WM_DELETE_WINDOW', lambda: None) For the '-' button, I don't know any way. > Or is it possible to create a main Toplevel without "x" and "-"? Apart from overrideredirect(1), I don't think there's any. BTW, what are you trying to do here? Will your application run on a "normal" desktop computer? Or will it run on special devices such as vending machines or similar? If in the first case, my advice would be to give up this design (which many people hate, BTW) and use normal windows. You'll have far less trouble and will probably make your users happier. If in the second case, you shouldn't rely on an existing window manager, and try to design your GUI so that doing things "manually" will be easier. For example, instead of displaying a dialog for a message, maybe you should just reserve a screen zone to display the message, optionally displaying it in a special color or making it blink so that the user can't miss it. You may also consider using the "place" layout method to display things at random coordinates in your application window. For example: -------------------------------------------------------- from Tkinter import * class App: def __init__(self): self.root = Tk() self.root.overrideredirect(1) frm = Frame(self.root, width=320, height=200, borderwidth=5, relief=RAISED) frm.pack_propagate(0) frm.pack() Button(frm, text="Quit", command=self.root.quit).pack(pady=20) Button(frm, text="Hello", command=self.hello).pack(pady=20) def hello(self): self.dialogWdw = Frame(self.root, borderwidth=2, relief=RAISED) Label(self.dialogWdw, text='Hello!').pack(side=TOP, padx=20, pady=4) Button(self.dialogWdw, text='OK', command=self.destroyDialog).pack(side=TOP, padx=20, pady=4) self.dialogWdw.place(x=170, y=100, anchor='center') def destroyDialog(self): self.dialogWdw.place_forget() self.dialogWdw.destroy() app = App() app.root.mainloop() -------------------------------------------------------- HTH -- python -c "print ''.join([chr(154 - ord(c)) for c in 'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])" From twisted0n3 at gmail.com Fri Jun 22 16:47:48 2007 From: twisted0n3 at gmail.com (Twisted) Date: Fri, 22 Jun 2007 20:47:48 -0000 Subject: The Modernization of Emacs: terminology buffer and keybinding In-Reply-To: References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182272495.990807.99110@a26g2000pre.googlegroups.com> <87tzt3ihev.fsf@kobe.laptop> <1182370216.961241.6960@n60g2000hse.googlegroups.com> <85zm2ufjpb.fsf@lola.goethe.zz> <1182372592.803332.288260@u2g2000hsc.googlegroups.com> <1182373919.262388.100740@c77g2000hse.googlegroups.com> <85r6o6fhkb.fsf@lola.goethe.zz> <1182375045.626510.188170@m36g2000hse.googlegroups.com> <85myyufgwj.fsf@lola.goethe.zz> <1182375528.985142.293900@q69g2000hsb.googlegroups.com> Message-ID: <1182545268.055596.228700@i38g2000prf.googlegroups.com> On Jun 21, 12:11 pm, Robert Uhl wrote: > Twisted writes: > > >> But Emacs does not have a "clunky" interface. > > > That's for the everyday novice-to-intermediate user to decide. > > Why should the ignorant decide? Do you leave the decision of what great > art is to 3 year olds and their doting parents? Did I say it was for the "beginner" to decide? No, I said "novice-to- intermediate". How clunky versus usable an interface to a tool is is for those who invest some, but not extraordinary amounts of, time into its use to decide. If it requires years of mastery, it is clunky -- period. This may be unavoidable if it's something involved in nuclear power plants, delicate neurosurgery, or whatever. If it's a text editor, on the other hand, it's clearly going to have superior competition in the area of usability. Besides, ANY interface that involves fumbling around in the dark trying to find a light switch is clunky. You should be able to see what the hell you're doing and navigate easily. Applications that not only eschew normal methods of navigation of the interface, but force you to fumble your way between the help and the task you're trying to do, are definitely clunky. An analogy to a genuine emacs experience: you enter a workshop with some raw materials and tools. Unfortunately there's no big ceiling lights so you can just flip the switch by the door and then always be able to see where everything is. Instead there's little lights here and there by various specific tools and storage areas, and in one area a map of the place with switches to control the lights. So first you have to fumble around until you happen upon the map/light controls. Then you need to (in the dark!) hit the switch for the map/light control area itself. (Now you've found the help and gotten it to be the active pane, er "window".) Now you need to find the tool you want on the map -- OK, that was easy. Now you turn on its light. Oh, hell -- the light on the map/light controls has now gone out though! That also included the instructions on using the specific tool. You can go to and use the one tool, if you memorized those instructions, but then it's back to the darkness... (You find the help on doing a particular thing, then can't get back to the document to do it because of clunky navigation. So you go back to the help on switching windows, and now you can flip back to the document. Only you realize you can have the document and help open at the same time, but the only time the document has focus is when the help is open to "help on switching windows", which makes this rather useless! You end up having to memorize the help, because *you can't have arbitrary parts of the help and your document open side by side and be working on the document*. All because you can't simply tab or click to the document. At minimum, you have to *memorize* some arcane key controls for switching panes ... er, "windows", that are totally unintuitive and unlike what is normally used. Oops. The interface design is a nightmare. The most basic requirement, that it be easy to have the help open side by side with your document and switch back and forth and navigate inside the help easily, is broken. If you have to consult the help just to navigate the help or to switch focus between document and help, then you're trapped, and that is what happens with emacs. I don't know why people keep harping about what version. It was probably something in the low 20s, after an earlier try with one in the upper teens. The interface never improved over that time -- the biggest problem consistently being that whenever focus was successfully transferred to the document window, the help window was invariably open to the instructions for switching windows, so you could never be doing something with the document and have the help for that something available at a glance. Defeating the whole purpose of having a help system. A separate printed manual would have been better, if I could have spared the paper and toner, as I could hold that off to one side of the monitor and flip through it and open it to anywhere I wanted to, then go back to my document without even having to think about it. Even though it would be at the price of no full- text search capability -- not that I could ever get that to work in emacs anyway. There was no apparent way to do a simple substring search and click "next match" or "previous match" to navigate among the hits...more arcane keypresses would be required, and as soon as it showed you the first match inside the help, the keypress documentation of course vanished. As far as I can tell, it just is not and never was possible to get started with emacs without a separate, outside-of-emacs cheat sheet, or to be very productive at all without actually memorizing the damn thing. Modern user interfaces require a minimum of memorization, most of which is basic, standard stuff that is the same from one app to the next, so you already know it all -- your clicks and double clicks, your alt-tabs and alt-enter-for-properties etc.; application-specific keyboard shortcuts can be learned as convenient. Infrequently used commands you can stand to hunt for in menus. When you find you use one frequently, you can try to learn the keyboard shortcut -- and you can find it without even consulting the help, simply by finding the command's menu item. Every time you want to use the command but can't remember the shortcut you just find it in the menu and activate it from there, and see the shortcut while you're at it, helping to eventually memorize it. And the commonest sorts of File and Edit menu items have near-universal shortcuts, the big variation tending to be whether Redo is shift-ctrl-Z, ctrl-Y, nonexistent, or menu-only. But you can start using it right away with low productivity, and increase your productivity with proficiency and learning (optional) shortcuts, chiefly those to the commands you happen to use a lot. Not so emacs, or most other unix-heritage tools. Those you can't use in any nontrivial way without ascending a sheer cliff of memorization *first*, before doing a single useful thing. One person elsewhere in this thread even went so far as to suggest that to avoid having a similar hurdle with every application you just use emacs for everything. If you like being claustrophobically trapped in 80x24x8BPP instead of 1280x1024x32BPP, that may be your cup of tea. Also if you like having zero productivity in every single task instead of just one until you've scaled the El Capitan of user interfaces. On the other hand, you can avoid having a similar hurdle with ANY application by simply using standard GUI apps developed with Mac and Windows users in mind. I hear they even have them for Unix now -- technically including everything written for MacOSX as well as modern WMs on Linux and probably *BSD. (Use emacs for everything? That's like suggesting I move all my tools *into* that dark place with the screwy lighting system, rather than *out*. Me, I'd rather just avoid that place, or if necessary bring in a big bank of floodlights and install them, and the sensitive artiste who originally architected it be damned. Which is what Xah started this whole mess by suggesting, in effect.) From rpdooling at gmail.com Thu Jun 7 11:16:17 2007 From: rpdooling at gmail.com (BartlebyScrivener) Date: Thu, 07 Jun 2007 15:16:17 -0000 Subject: Baffled on Windows. In-Reply-To: References: Message-ID: <1181229377.134376.283650@n4g2000hsb.googlegroups.com> On Jun 7, 8:17 am, Neil Cerutti wrote: > I have the following Python program: > > Running this program with 2.5.1 causes another Python script in > the same directory to be loaded . . . 'new.py' A good habit for naming your scripts: If you have a script and you want to name it text.py, or list.py or new.py or old.py or some common name that might be found in the thousand and one other modules and programs in your various installations, just use my_text.py or my_list.py or neil_new.py or something to reduce the chances that you'll be shadowing without knowing it. rick From hiroc13 at gmail.com Fri Jun 29 04:26:23 2007 From: hiroc13 at gmail.com (hiroc13) Date: Fri, 29 Jun 2007 01:26:23 -0700 Subject: Python & MySQL problem with input to table..! Message-ID: <1183105583.922597.72930@n2g2000hse.googlegroups.com> >>> import MySQLdb >>> db = MySQLdb.connect (host = "localhost", user = "root", passwd = "pass", db = "base1") >>> c = db.cursor () >>> c.execute(""" INSERT INTO table1 (prvo, drugo) VALUES ('test', '1') """) >>> c.execute("SELECT * FROM table1") >>> res = c.fetchall () >>> print res When I start this code I get ((15L, 'test', 1L),) on the screen but if I first execute this: >>> import MySQLdb >>> db = MySQLdb.connect (host = "localhost", user = "root", passwd = "pass", db = "base1") >>> c = db.cursor () >>> c.execute(""" INSERT INTO table1 (prvo, drugo) VALUES ('test', '1') """) .... this write to table1 and now this: >>> Import MySQLdb >>> db = MySQLdb.connect (host = "localhost", user = "root", passwd = "pass", db = "base1") >>> c = db.cursor () >>> c.execute("SELECT * FROM table1") >>> res = c.fetchall () >>> print res I get only this: "()" - the table1 is empty ... I write 10 times same thing to table... only PRIMARY KEY is change WHY???? From sergio at sergiomb.no-ip.org Tue Jun 19 21:09:32 2007 From: sergio at sergiomb.no-ip.org (=?UTF-8?B?U8Opcmdpbw==?= Monteiro Basto) Date: Wed, 20 Jun 2007 02:09:32 +0100 Subject: HTMLParser.HTMLParseError: EOF in middle of construct References: <1182195498.16548.5.camel@localhost.localdomain> <4677e790$0$2840$a729d347@news.telepac.pt> <46783ab1$0$1266$a729d347@news.telepac.pt> <46784A62.1000303@web.de> Message-ID: <46787e4d$0$28429$a729d347@news.telepac.pt> Stefan Behnel wrote: > S?rgio Monteiro Basto wrote: >> but is one single error that blocks this. >> Finally I found it , it is : >> > if I put : >> > >> p = re.compile('"align') >> content = p.sub('" align', content) >> >> I can parse the html >> I don't know if it a bug of HTMLParser > > Sure, and next time your key doesn't open your neighbours house, please > report to the building company to have them fix the door. > The question, here, is if References: <46650e6c$0$25817$9b622d9e@news.freenet.de> Message-ID: <4665a7e9$0$24866$9b622d9e@news.freenet.de> > I am on machine A, which has a NFS mounted filesystem hosted on machine > B. All I need to find out is whether the NFS filesystem is mounted > using tcp or udp. Ah, ok. I recommend to parse /proc/mounts. Regards, Martin From nagle at animats.com Thu Jun 28 02:41:54 2007 From: nagle at animats.com (John Nagle) Date: Wed, 27 Jun 2007 23:41:54 -0700 Subject: Python's "only one way to do it" philosophy isn't good? In-Reply-To: References: <7xir9cbm0g.fsf@ruckus.brouhaha.com> <7xejjzmk7u.fsf@ruckus.brouhaha.com> <7xy7i7xjl5.fsf@ruckus.brouhaha.com> Message-ID: Douglas Alan wrote: > "Chris Mellon" writes: >>On 6/27/07, Douglas Alan wrote: >>This totally misrepresents the case. The with statement and the >>context manager is a superset of the RAII functionality. > > > No, it isn't. C++ allows you to define smart pointers (one of many > RAII techniques), which can use refcounting or other tracking > techniques. Refcounting smart pointers are part of Boost and have > made it into TR1, which means they're on track to be included in the > next standard library. One need not have waited for Boost, as they can > be implemented in about a page of code. > > The standard library also has auto_ptr, which is a different sort of > smart pointer, which allows for somewhat fancier RAII than > scope-based. Smart pointers in C++ never quite work. In order to do anything with the pointer, you have to bring it out as a raw pointer, which makes the smart pointer unsafe. Even auto_ptr, after three standardization attempts, is still unsafe. Much handwaving around this problem comes from the Boost crowd, but in the end, you just can't do safe reference counted pointers via C++ templates. It requires language support. This is off topic, though, for Python. If anybody cares, look at my postings in comp.lang.c++.std for a few years back. Python is close to getting it right, but not quite. Python destructors aren't airtight; you can pass the "self" pointer out of a destructor, which "re-animates" the object. This generally results in undesirable behavior. Microsoft's "managed C++" has the same problem. They explicitly addressed "re-animation" and consider the possibility that a destructor can be called twice. To see the true horror of this approach, read http://www.codeproject.com/managedcpp/cppclidtors.asp Microsoft Managed C++ ended up having destructors, finalizers, explicit destruction, scope-based destruction of locals, re-animation, and nondeterministic garbage collection, all in one language. (One might suspect that this was intended to drive people to C#.) In Python, if you have reference loops involving objects with destructors, the objects don't get reclaimed at all. You don't want to call destructors from the garbage collector. That creates major problems, like introducing unexpected concurrency and wierd destructor ordering issues. Much of the problem is that Python, like Perl and Java, started out with strong pointers only, and, like Perl and Java, weak pointers were added as afterthoughts. Once you have weak pointers, you can do it right. Because weak pointers went in late, there's a legacy code problem, mostly in GUI libraries. One right answer would be a pure reference counted system where loops are outright errors, and you must use weak pointers for backpointers. I write Python code in that style, and run with GC in debug mode, to detect leaks. I modified BeautifulSoup to use weak pointers where appropriate, and passed those patches back to the author. When all or part of a tree is detached, it goes away immediately, rather than hanging around until the next GC cycle. The general idea is that pointers toward the leaves of trees should be strong pointers, and pointers toward the root should be weak pointers. For a truly sound system, you'd want to detect reference loops at the moment they're created, and handle them as errors. This is quite possible, although inefficient for certain operations. Reversing a linked list that has depth counts is expensive. But then, Python lists aren't implemented as linked lists; they're variable sized arrays with one reference count for the whole array. So, in practice, the cases where maintaining depth counts gets expensive are rare. Then you'd want a way to limit the scope of "self" within a destructor, so that you can't use it in a context which could result in it outliving the destruction of the object. This is a bit tricky, and might require some extra checking in destructors. The basic idea is that once the reference count has gone to 0, anything that increments it is a serious error. (As mentioned above, Microsoft Managed C++ allowed "re-animation", and it's clear from that experience that you don't want to go there.) With those approaches, destructors would be sound, order of destruction would be well defined, and the "here be dragons" notes about destructors could come out of the documentation. With that, we wouldn't need "with". Or a garbage collector. If you like minimalism, this is the way to go. John Nagle From sigzero at gmail.com Thu Jun 21 15:00:25 2007 From: sigzero at gmail.com (Robert Hicks) Date: Thu, 21 Jun 2007 19:00:25 -0000 Subject: try/except with multiple files Message-ID: <1182452425.793305.193370@u2g2000hsc.googlegroups.com> Is it good practice to do something like: try: f1 = file('file1') f2 = file('file2') except: # catch the exception Or do you do a try/except for each open? Robert From hg at nospam.org Tue Jun 12 15:52:41 2007 From: hg at nospam.org (hg) Date: Tue, 12 Jun 2007 14:52:41 -0500 Subject: stdout/err and C extentions References: <5rCbi.98038$vE1.59482@newsfe24.lga> Message-ID: Robert Bauck Hamar wrote: > hg wrote: > >> Hi, >> >> I have the following >> >> ********************* C extention - redir.c >> >> >> #include "Python.h" >> >> PyObject * test_redir_test(PyObject *self) { >> fprintf(stdout, "Hello from an extention!\n"); >> Py_INCREF(Py_None); >> return Py_None; >> } >> > [...] >> *********************** python test script: test.py: >> import sys >> >> >> class My_Stdout: >> def write(self, p_string): >> l_file = open('res.txt','a') >> l_file.write(p_string) >> l_file.close >> >> >> sys.stdout = My_Stdout() >> >> print 'toto' >> import test_redir >> >> >> >> test_redir.test() >> >> >> >> **************** Question: >> >> print 'toto' does go to "res.txt" while "Hello from an extention!\n" goes >> to the console. >> >> Any clue ? > > There is no portable way to change the location of stdout during execution > of a program. If you want to print with whatever is sys.stdout from an > extension module, you should call sys.stdout's write method dynamically > from C. > > -- > Robert Bauck Hamar Robert, thanks, I understand that sys.stdout and stdout of an extention are two different entities ... correct ? hg From kw at codebykevin.com Sat Jun 30 11:18:10 2007 From: kw at codebykevin.com (Kevin Walzer) Date: Sat, 30 Jun 2007 11:18:10 -0400 Subject: Building a Python app with Mozilla In-Reply-To: References: Message-ID: <46867432.7060400@codebykevin.com> Thorsten Kampe wrote: > Hi, > > I've already sent this to the Komodo mailing list (which seemed to me > the more appropriate place) but unfortunately I got no response. > > I'd like to build a Python GUI app. Neither Tkinter nor Wxpython nor > PyQT are actually what I want (because the lack of GUI builders and > they don't really look good on Windows and Linux). > > Komodo itself is an excellent example of a - at least Python driven - > application that looks superb and has superior functionality so it > seems natural to use the Komodo approach for me. > Komodo is not a Python application. It is a Mozilla application that supports Python development. Komodo is more akin to Thunderbird and Firefox than anything else; it uses the XUL framework for rendering widgets, if I'm not mistaken. If you want to build an application like Komodo, get a book on developing with the Mozilla framework (XUL, XPCOM, and all that) and look at that. Python has little to do with that. -- Kevin Walzer Code by Kevin http://www.codebykevin.com From kay.schluehr at gmx.net Tue Jun 12 10:12:03 2007 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Tue, 12 Jun 2007 07:12:03 -0700 Subject: Multiline lamba implementation in python. In-Reply-To: References: <1b0ce1b60706112002i761dc295x9ba9c4f589c41db1@mail.gmail.com> Message-ID: <1181657523.655499.161880@g37g2000prf.googlegroups.com> On 12 Jun., 14:57, Facundo Batista wrote: > Remember that the *only* difference between the two functions is that > one is anonymous, and for other you have to came up with a name (name > that if is well thought, actually adds readibility to your code). The difference is that one can be inlined since it is an expression and the other has to be a statement and a reusable ( named ) abstraction even when you don't need one. I have a very hard time to defend this as a good design decision even when it is just a minor pain point in almost all my practical purposes. From evan at yelp.com Wed Jun 20 01:22:14 2007 From: evan at yelp.com (Evan Klitzke) Date: Tue, 19 Jun 2007 22:22:14 -0700 Subject: determine 32 or 64 bit architecture with python 2.2 In-Reply-To: <1182251830.835902.78210@n2g2000hse.googlegroups.com> References: <1182251830.835902.78210@n2g2000hse.googlegroups.com> Message-ID: On 6/19/07, Kai Rosenthal wrote: > Hello, > how can I determine the architecture (32 or 64bit) with python 2.2 on > Windows or Unix (AIX, Solaris) OS, without the modul platform? > Thanks for your hints, Kai For Unix systems you can probably use os.uname() and check what architecture the kernel is built for. For example, evan at thinkpad ~ $ python -c 'import os; print os.uname()[4]' i686 As you can see, I'm on a 32 bit system. -- Evan Klitzke From bbxx789_05ss at yahoo.com Sun Jun 24 00:00:46 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: Sat, 23 Jun 2007 21:00:46 -0700 Subject: pydoc with METH_VARGS In-Reply-To: <1182629624.579928.186260@n60g2000hse.googlegroups.com> References: <1182629624.579928.186260@n60g2000hse.googlegroups.com> Message-ID: <1182657646.734577.248820@w5g2000hsg.googlegroups.com> On Jun 23, 2:13 pm, Stuart wrote: > With my Python extension module all the function definitions are with > METH_VARGS. The result being that pydoc, just puts "(...)" for the > argument list. Can I hand edit this to put the specific variable names > I want? With optional arguments in brackets or something? > > Thanks. Are you asking whether you can change a text file that pydoc produces? From oscartheduck at gmail.com Fri Jun 22 18:44:08 2007 From: oscartheduck at gmail.com (oscartheduck) Date: Fri, 22 Jun 2007 22:44:08 -0000 Subject: regular expression concatenation with strings In-Reply-To: <1182550046.089794.153040@x35g2000prf.googlegroups.com> References: <1182543519.337279.25800@z28g2000prd.googlegroups.com> <1182546637.032673.106920@a26g2000pre.googlegroups.com> <1182550046.089794.153040@x35g2000prf.googlegroups.com> Message-ID: <1182552248.454455.275770@a26g2000pre.googlegroups.com> Oh dear. I just want to make it clear I wasn't trying to take credit for the change of extension to ext. I genuinely worked it out independently and then rushed back and posted about it, but you definitely worked it out and wrote it up first! Sorry! And thanks for the help!! James On Jun 22, 4:07 pm, oscartheduck wrote: > Got it: > > #!/usr/bin/env python > from PIL import Image > import glob, os, re > > size = 128, 128 > > def thumbnailer(dir, filenameRx): > for picture in [ p for p in os.listdir(dir) if > os.path.isfile(os.path.join( > dir,p)) and filenameRx.match(p) ]: > file, ext = os.path.splitext(picture) > im = Image.open (picture) > im.thumbnail(size, Image.ANTIALIAS) > im.save(file + ".thumbnail" + ext) > > jpg = re.compile(".*\.(jpg|jpeg)", re.IGNORECASE) > thumbnailer(".", jpg) > > The answer was sitting in front of my eyes. What is your code doing? > It looks like: > > for $foo in [current working directory] > if $foo is a file > and foo's name matches the regex From zondo42 at googlemail.com Wed Jun 6 03:02:06 2007 From: zondo42 at googlemail.com (Glenn Hutchings) Date: Wed, 06 Jun 2007 07:02:06 -0000 Subject: Need a Little Help on Tkinter and Python In-Reply-To: References: Message-ID: <1181113326.626277.208150@h2g2000hsg.googlegroups.com> On 6 Jun, 00:58, "W. Watson" wrote: > is there a Tkinter intro manual somewhere Take a look at http://www.pythonware.com/library/tkinter/introduction Glenn From exhuma at gmail.com Tue Jun 12 05:46:28 2007 From: exhuma at gmail.com (exhuma.twn) Date: Tue, 12 Jun 2007 02:46:28 -0700 Subject: Pasting an image from clipboard in Tkinter? In-Reply-To: References: <1181564628.443138.165380@k79g2000hse.googlegroups.com> Message-ID: <1181641588.573486.14380@i13g2000prf.googlegroups.com> On Jun 12, 11:24 am, "Eric Brunel" wrote: > On Mon, 11 Jun 2007 14:23:48 +0200,exhuma.twn wrote: > > As many might know, windows allows to copy an image into the clipboard > > by pressing the "Print Screen" button on the keyboard. Is it possible > > to paste such an image from the clipboard into a "Text" widget in > > Tkinter? Here is my first attempt with just trying to print out the > > image data: > > > ----------------- > > def pasteImg(tgt): > > global clipboardEnabled > > if not clipboardEnabled: return > > > win32clipboard.OpenClipboard(0) > > print win32clipboard.GetClipboardData() > > win32clipboard.CloseClipboard() > > ----------------- > > > This works fine with selecting text, but comes up with the following > > error when trying to paste an image: > > > ----------------- > > Exception in Tkinter callback > > Traceback (most recent call last): > > File "C:\Python25\lib\lib-tk\Tkinter.py", line 1403, in __call__ > > return self.func(*args) > > File "X:\development\testing\tkwiki\tkwiki.py", line 52, in > > Button( root, command=lambda: pasteImg(txt) ).pack() > > File "X:\development\testing\tkwiki\tkwiki.py", line 38, in pasteImg > > print win32clipboard.GetClipboardData() > > TypeError: Specified clipboard format is not available > > ----------------- > > > Obviously the clipboard does not know about that format. Does that > > mean I have to wait until it's implemented or are there other ways to > > access the image data? > > According tohttp://msdn2.microsoft.com/en-us/library/ms649039.aspx, there > is format that you should pass to GetClipboardData telling the data type > you expect to get. The format you should specify to get a bitmap image is > named CF_BITMAP in the Windows API. AFAIK, this constant is not exposed in > the Python world, so you have to pass directly the numeric value, which is > 2. > > But even if you do get the clipboard contents, you'll get it in BMP > format, that tk/Tkinter does not understand by default. So you'll need a > means to convert it to the only format known to tk/Tkinter by default, > which is GIF. PIL is certainly able to do that (I don't use it myself); > you may also rely on an external conversion utility. > > HTH > -- > python -c "print ''.join([chr(154 - ord(c)) for c in > 'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])" Well, by inspecting the clipboard contents, I already suspected it might be "2". So I did a getData with the format set to "2". So, when I try to paste simple text, it does complain that the requested format is not on the clipboard. So far, correct. So I press the print screen button, which loads an image into th clipboard. When pasting I get this: Exception in Tkinter callback Traceback (most recent call last): File "C:\Python25\lib\lib-tk\Tkinter.py", line 1403, in __call__ return self.func(*args) File "X:\development\testing\tkwiki\tkwiki.py", line 55, in Button( root, command=lambda: pasteImg(txt) ).pack() File "X:\development\testing\tkwiki\tkwiki.py", line 39, in pasteImg print win32clipboard.GetClipboardData(2) error: (6, 'GetClipboardData:GlobalLock', 'The handle is invalid.') I'm not sure what this means. ... Ah... bugger. It won't work (yet): http://mail.python.org/pipermail/python-win32/2001-May/000056.html From doug at alum.mit.edu Tue Jun 19 20:16:28 2007 From: doug at alum.mit.edu (Douglas Alan) Date: Tue, 19 Jun 2007 20:16:28 -0400 Subject: Python's "only one way to do it" philosophy isn't good? References: <1181368143.874341.273140@r19g2000prf.googlegroups.com> Message-ID: Steven D'Aprano writes: > On Tue, 19 Jun 2007 17:46:35 -0400, Douglas Alan wrote: >> I think that most people who program in Scheme these days don't do it >> to write practical software. They either do it to have fun, or for >> academic purposes. On the other hand, most people who program in >> Python are trying to get real work done. Which is precisely why I >> program a lot in Python and very little in Scheme these days. It's >> nice to have the batteries included. > So, once you've succeeded in your campaign to make Python more like > Scheme, what language will you use for getting real work done? The problem with using Scheme for real work is that it doesn't come with enough batteries included and there isn't a big enough of a community behind it that uses it for real work. Also, the Scheme standard has progressed at a terribly slow pace. I have heard that the reason for this is due to the way that its standardizing committees were set up. One of the whole reasons to use Lisp is for its extensible syntax, but it took more than a decade for macros to make it into the Scheme standard. And without a standard macro system, there was no standard library -- not even for doing OO programming. > And how long will it take before Schemers start agitating for it to > become more like Scheme? > There is a huge gulf between the claim that Python needs to be more > Scheme-like, and the fact that by your own admission you use Python, > not Scheme, for real work. What benefit will be gained? The ability > to "directly explore some pretty mind-bending stuff ... in a > hackerly, brain-expanding/brain-teaser kind of way"? Well, go to MIT and take SICP and then the graduate-level sequel to the class, Adventures in Advanced Symbolic Programming, and then you'll see what some of the advantages would be. A good multimethod system, e.g., would make Python a significantly nicer language for my purposes, for instance. For the record, I have a huge problem with NIH-syndrome, and think that every programming language in the world could learn a thing or two from what other languages have gotten right. |>oug From koara at atlas.cz Mon Jun 11 05:55:43 2007 From: koara at atlas.cz (koara) Date: Mon, 11 Jun 2007 02:55:43 -0700 Subject: memory efficient set/dictionary In-Reply-To: References: <1181485676.481109.234980@c77g2000hse.googlegroups.com> <1181492122.508277.209500@n4g2000hsb.googlegroups.com> Message-ID: <1181555743.786214.102780@q66g2000hsg.googlegroups.com> > > I would recommend you to use a database since it meets your > > requirements (off-memory, fast, persistent). The bsdddb module > > (berkeley db) even gives you a dictionary like interface. > >http://www.python.org/doc/lib/module-bsddb.html > > Standard SQL databases can work for this, but generally your > recommendation of using bsddb works very well for int -> int mappings. > In particular, I would suggest using a btree, if only because I have had > troubles in the past with colliding keys in the bsddb.hash (and recno is > just a flat file, and will attempt to create a file i*(record size) to > write to record number i . > > As an alternative, there are many search-engine known methods for > mapping int -> [int, int, ...], which can be implemented as int -> int, > where the second int is a pointer to an address on disk. Looking into a > few of the open source search implementations may be worthwhile. Thanks guys! I will look into bsddb, hopefully this doesn't keep all keys in memory, i couldn't find answer to that during my (very brief) look into the documentation. And how about the extra memory used for set/dict'ing of integers? Is there a simple answer? From borud-news at borud.no Sat Jun 23 10:18:28 2007 From: borud-news at borud.no (Bjorn Borud) Date: 23 Jun 2007 16:18:28 +0200 Subject: The Modernization of Emacs References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182344981.372713.298580@w5g2000hsg.googlegroups.com> <1182370884.853838.321440@c77g2000hse.googlegroups.com> <2jpok4-ajt.ln1@zoogz.gregorie.org> <1182551884.239660.209700@x35g2000prf.googlegroups.com> Message-ID: [Twisted ] | | > I have observed similar opinions in other non-computer-freaks. people | > who see the computer only as a tool and are only interested in getting | > the job done. they have a surprising preference for Linux. | | But not emacs, I'll bet. I think emacs appeals to people who like | dealing with the mechanics of emacs or fiddling with and extending the | darn thing. But most people just want to get the job done, and the | editor or other tools they use have to get out of the way and simply | let them work. no, Emacs is not among the applications they use. nor are any IDEs or compilers. I don't think Emacs is that relevant to these users since what they do is mostly word-processing, spreadsheets, mail and web browsing. Emacs is not really targeted at Word processing as such. (although that doesn't stop some people from thinking that it would be a good idea to turn Emacs into a wordprocessing application with support for graphics, mixed fonts etc.) I use Emacs for creating documents, but this is very different since I use LaTeX and I'm a programmer, so it is very conventient for me to use a system that allows me to treat documents like code (with respect to revision control systems etc). outside academia or the technical community, not that many use LaTeX, but I have seen it in the past. -Bj?rn From hniksic at xemacs.org Fri Jun 29 11:22:28 2007 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Fri, 29 Jun 2007 17:22:28 +0200 Subject: Python's "only one way to do it" philosophy isn't good? References: <7x3b0nmkk6.fsf@ruckus.brouhaha.com> <7xejjzmk7u.fsf@ruckus.brouhaha.com> <7xy7i7xjl5.fsf@ruckus.brouhaha.com> <1182872972.417776.78650@o11g2000prd.googlegroups.com> <7xtzsuy7fe.fsf@ruckus.brouhaha.com> <1182955743.076746.114790@i38g2000prf.googlegroups.com> <877ipn9gff.fsf@mulj.homelinux.net> Message-ID: <87fy4akcp7.fsf@mulj.homelinux.net> Douglas Alan writes: >>> The downside is that they are not quite as flexible as iterators >>> (which can be hard to code) and generators, which are slow. > >> Why do you think generators are any slower than hand-coded iterators? > > Generators aren't slower than hand-coded iterators in *Python*, but > that's because Python is a slow language. But then it should be slow for both generators and iterators. > *Perhaps* there would be some opportunities for more optimization if > they had used a less general mechanism.) Or if the generators were built into the language and directly supported by the compiler. In some cases implementing a feature is *not* a simple case of writing a macro, even in Lisp. Generators may well be one such case. From koara at atlas.cz Sun Jun 10 10:27:56 2007 From: koara at atlas.cz (koara) Date: Sun, 10 Jun 2007 07:27:56 -0700 Subject: memory efficient set/dictionary Message-ID: <1181485676.481109.234980@c77g2000hse.googlegroups.com> What is the best to go about using a large set (or dictionary) that doesn't fit into main memory? What is Python's (2.5 let's say) overhead for storing int in the set, and how much for storing int -> int mapping in the dict? Please recommend a module that allows persistent set/dict storage + fast query that best fits my problem, and as lightweight as possible. For queries, the hit ratio is about 10%. Fast updates would be nice, but i can rewrite the algo so that the data is static, so update speed is not critical. Or am i better off not using Python here? Cheers. From tn.pablo at gmail.com Wed Jun 27 22:23:58 2007 From: tn.pablo at gmail.com (ptn) Date: Thu, 28 Jun 2007 02:23:58 -0000 Subject: Reversing a string In-Reply-To: References: Message-ID: <1182997438.541012.54100@o61g2000hsh.googlegroups.com> > >>>>mylist = [] > > That's bad. If you need to use a list in the rev function, you > should bind a new list to a local variable inside rev. > He's right. If you want to use a list to temporarily store the reversed version of your string, it should exist only in the local namespace of your function. There's still stuff you can do with your function to make it work, such as: >>> def rev(x): mylist = [] for char in x: mylist.append(char) mylist.reverse() for letter in mylist: print letter However, compare the incredible difference in clarity and elegance between that and: > >>> print "\n".join("spam"[::-1]) So, big lessons: (1) Global variables suck if you try to manipulate them and (2) in Python, if your code isn't as clear as you would like, there's probably a better way to do it. From bignose+hates-spam at benfinney.id.au Wed Jun 20 19:14:24 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 21 Jun 2007 09:14:24 +1000 Subject: How to code dynamically created methods? References: Message-ID: <878xaexlpr.fsf@benfinney.id.au> kj writes: > Nevermind, I found the problem... Please share the solution with the list, if you would. -- \ "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 bytter at gmail.com Fri Jun 22 17:06:47 2007 From: bytter at gmail.com (Hugo Ferreira) Date: Fri, 22 Jun 2007 22:06:47 +0100 Subject: SIMD powered Python Message-ID: <4e8efcf50706221406y57b2232et1356e69c428de6d8@mail.gmail.com> Hi! Is there any I&D ongoing about using SIMD [1] instructions, like SSE [2], to speed up Python, especially regarding functional features, like list comprehension, map and reduce, etc.. ? Best regards, Hugo Ferreira -- [1] http://en.wikipedia.org/wiki/SIMD [2] http://en.wikipedia.org/wiki/Streaming_SIMD_Extensions -------------- next part -------------- An HTML attachment was scrubbed... URL: From bj_666 at gmx.net Fri Jun 15 18:17:55 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Sat, 16 Jun 2007 00:17:55 +0200 Subject: Should: "for k,v in **dictionary_instance" work? References: <1181935045.323196.287810@n2g2000hse.googlegroups.com> Message-ID: In <1181935045.323196.287810 at n2g2000hse.googlegroups.com>, keithgabryelski wrote: > Does it make sense to provide this syntax for iterating key/value > pairs from a dictionary? > > for k,v in **dict(): > print k,v > > why is this not the same as: > > for k,v in dict().items(): > print k,v Why should it be? Why adding something that unreadable and magic instead of the perfect readable ``for k, v in some_dict.iteritems():``? And I don't see why it should be ``**``!? Ciao, Marc 'BlackJack' Rintsch From gagsl-py2 at yahoo.com.ar Thu Jun 14 21:37:12 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 14 Jun 2007 22:37:12 -0300 Subject: poking around a running program References: <7xbqfidp4l.fsf_-_@ruckus.brouhaha.com> Message-ID: En Thu, 14 Jun 2007 21:42:50 -0300, Paul Rubin <"http://phr.cx"@NOSPAM.invalid> escribi?: > I have a long-running program that has lots of net connections open on > separate threads. I'm twiddling my thumbs waiting for it to finish > (each run takes maybe an hour) and although I'm logging various info > that I can monitor as the run progresses, it would be cool to be able > to actually poke around the program's data while it's running. > > I'm thinking of adding a "console" thread that would basically be a > read-eval-print loop that I could use to inspect data interactively. > Maybe it would just eval stuff or maybe it would use pdb. Of course > it would be a bit dangerous since I could mutate things with it but I > guess it would be enough to just be careful not to do that. > > Is this kind of thing common? Has it been done before and are there > some recipes? I did a quick search and didn't find anything obvious. > One thing I'm wondering is how to examine the internal state of > iterators, especially the C implementations from itertools. I don't know how common it is, but for instance, Zope has a remote console like this. The code module may be useful. > More advanced might be some kind of hot-patching scheme (to be able to > change the code without stopping it) but for now I think I'm ok just > restarting the program every so often, modifying the code between runs > based on what happens in a given run. That may be hard to do. For global functions, reload() may help, but if you have many created instances, modifying and reloading the module that contains the class definition won't automatically alter the existing instances. -- Gabriel Genellina From robert.rawlins at thinkbluemedia.co.uk Fri Jun 29 10:27:47 2007 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins - Think Blue) Date: Fri, 29 Jun 2007 15:27:47 +0100 Subject: Application Crashing Message-ID: <056301c7ba59$b39b3ee0$1ad1bca0$@rawlins@thinkbluemedia.co.uk> Hello Guys, I find my application is freezing/crashing every now and then and it becoming a bit of a frustration, so this morning I sat down to try and locate the problem. After doing some debugging I think I've found the line of code that causes my problem. Print 'Read Results' New = e.read() Print 'Results Read' The last thing the application does is print the words 'Read Results' which leads me to think that the troublesome line is e.read(). This line is reading the contents of a file object created by a popen command. This runs without fail most of the time, but on a reasonably regular occurrence it seems to crash my app. I've tried wrapping it in a try/except, which I don't know much about and that doesn't appear to make any difference, the app still crashes. print 'Reading Push' try: new = e.read() except: new = 'fault' Print 'Results Read' I'm not sure if this makes any difference, but this is all being run from within a thread. I need some help on handling this a little better to avoid my application from dying on me, if anyone can offer some advice on what can be done it would be greatly appreciated, I'm hoping just a small code solution will be available. Thanks guys, I look forward to hearing from you, Rob -------------- next part -------------- An HTML attachment was scrubbed... URL: From tleeuwenburg at gmail.com Thu Jun 21 02:00:53 2007 From: tleeuwenburg at gmail.com (tleeuwenburg at gmail.com) Date: Thu, 21 Jun 2007 06:00:53 -0000 Subject: python website In-Reply-To: <46793f39$0$8705$edfadb0f@dread14.news.tele.dk> References: <1182349364.574645.279350@q19g2000prn.googlegroups.com> <46793f39$0$8705$edfadb0f@dread14.news.tele.dk> Message-ID: <1182405653.991686.108670@e9g2000prf.googlegroups.com> On Jun 21, 12:53 am, Martin Skou wrote: > The Daily Python-URLhttp://www.pythonware.com/daily/ pythonpapers.org :) -T From bj_666 at gmx.net Mon Jun 18 14:56:53 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Mon, 18 Jun 2007 20:56:53 +0200 Subject: suggestion: recursive collections.defaultdict References: <1182184918.766497.315040@k79g2000hse.googlegroups.com> Message-ID: In <1182184918.766497.315040 at k79g2000hse.googlegroups.com>, tutufan at gmail.com wrote: > It seems like > > x = defaultdict(defaultdict(list)) > > should do the obvious, but it doesn't. It *does* the obvious. Parenthesis after a name means: call this object *now*. Any other behavior wouldn't be obvious. Ciao, Marc 'BlackJack' Rintsch From haraldarminmassa at gmail.com Wed Jun 27 11:38:56 2007 From: haraldarminmassa at gmail.com (GHUM) Date: Wed, 27 Jun 2007 15:38:56 -0000 Subject: import data.py using massive amounts of memory In-Reply-To: References: Message-ID: <1182958736.118091.31610@q69g2000hsb.googlegroups.com> > Note that once it has made the .pyc file the subsequent runs take even > less memory than the cpickle import. Could that be the compiler compiling? Without knowing to much details about that process, but from 2.4 to 2.5 the compiler was totally exchanged, to AST. That would explain the drop from 8Meg -> 2.2 Meg. Harald From borud-news at borud.no Tue Jun 26 10:37:24 2007 From: borud-news at borud.no (Bjorn Borud) Date: 26 Jun 2007 16:37:24 +0200 Subject: The Modernization of Emacs: terminology buffer and keybinding References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182272495.990807.99110@a26g2000pre.googlegroups.com> <87tzt3ihev.fsf@kobe.laptop> <1182370216.961241.6960@n60g2000hse.googlegroups.com> <85zm2ufjpb.fsf@lola.goethe.zz> <1182372592.803332.288260@u2g2000hsc.googlegroups.com> <5dtk4tF34jrimU1@mid.dfncis.de> <1182375388.814275.227380@n2g2000hse.googlegroups.com> <87645h73ei.fsf@W0053328.mgh.harvard.edu> <1182548563.561252.82480@i13g2000prf.googlegroups.com> Message-ID: [Robert Uhl ] | | Once again I am forced to wonder if you have _ever_ actually used | emacs. find-file has tab completion: hit tab without anything typed, and | it displays _everything_ in the directory; type a few characters to | narrow it down; hit tab to complete the filename and be done with | it. ...and of course, in addition you have access to history so you can easily find previous parameters and edit them. this makes it very efficient when you need to fiddle about in deep directory trees in a way no GUI can yet offer. ...and then there's bookmarking, which is very good for keeping a set of files (and locations) handy for quick access. -Bj?rn From vedrandekovic at v-programs.com Thu Jun 21 15:07:42 2007 From: vedrandekovic at v-programs.com (vedrandekovic at v-programs.com) Date: Thu, 21 Jun 2007 12:07:42 -0700 Subject: Changing the names of python keywords and functions Message-ID: <1182452862.872909.206780@u2g2000hsc.googlegroups.com> Hello, I am trying to make a program for 3D modelling with "programming".And I want make my own program commands, for example when user type code in my program: "<> OS"- (THIS IS MY IMAGINARY EXAMPLE OF KEYWORD), my program must write this code in some user file, but my program must read this command like: "import os".How can I do something like that?? Please, HELP ME somebody!!! From sergio at sergiomb.no-ip.org Mon Jun 18 16:53:49 2007 From: sergio at sergiomb.no-ip.org (Sergio Monteiro Basto) Date: Mon, 18 Jun 2007 21:53:49 +0100 Subject: csv search and print In-Reply-To: <1182197510.875585.89160@i13g2000prf.googlegroups.com> References: <1182197510.875585.89160@i13g2000prf.googlegroups.com> Message-ID: <1182200029.17378.1.camel@localhost.localdomain> On Mon, 2007-06-18 at 13:11 -0700, John Machin wrote: > On Jun 19, 4:12 am, axja... at comcast.net wrote: > > I have a csv file containing lot of rows & columns. I wanted to search thru the > > heading for each column for a string and then print all the headings and the > > corresponding rows if a match is found. > > > > Any advise? you can put cvs in a MySql DB mysql -e 'CREATE TABLE table2(col1 VARCHAR(255), col2 VARCHAR(255), col3 VARCHAR(255), col4 VARCHAR(255), col5 VARCHAR(255), col6 VARCHAR(255), col7 VARCHAR(255), col8 VARCHAR(255), col9 VARCHAR(255), col10 VARCHAR(255), col11 VARCHAR(255), col12 VARCHAR(255), col13 VARCHAR(255), col14 VARCHAR(255))' table2 in mysql: load data infile '/home/sergio/pesquisa/table2.txt' into table table2 FIELDS TERMINATED BY ',' ENCLOSED BY '"' LINES TERMINATED BY '\n'; and work with python and mysql http://dustman.net/andy/python/python-and-mysql > > 1. Clarify your requirements: "corresponding rows" ... corresponding > to what? How many rows/columns is a "lot"? "I have a csv file" ... > only one? "search thru the heading for each column for a string" is > open to misinterpretation of various kinds :-) > 2. Write your script. > 3. Ask a specific question if you have a problem. > -- S?rgio M. B. -------------- next part -------------- A non-text attachment was scrubbed... Name: smime.p7s Type: application/x-pkcs7-signature Size: 2192 bytes Desc: not available URL: From rridge at caffeine.csclub.uwaterloo.ca Mon Jun 4 10:46:17 2007 From: rridge at caffeine.csclub.uwaterloo.ca (Ross Ridge) Date: Mon, 04 Jun 2007 10:46:17 -0400 Subject: Python, Dutch, English, Chinese, Japanese, etc. References: Message-ID: Steve Howell wrote: >I'm wondering if all the English keywords in Python >would present too high a barrier for most Chinese >people--def, if, while, for, sys, os, etc. So you >might need to go even further than simply allowing >identifiers to be written in Simplified-Chinese. Translating keywords and standard identifiers into Chinese could make learning Python even more difficult. It would probably make things easier for new programmers, but I don't know if serious programmers would actually prefer programming using Chinese keywords. It would make their Python implementations incompatible with the standard implementation, they wouldn't be able to use third-party modules and their own code wouldn't be portable. If novice Chinese programmers would have to unlearn much of they've learned in order to become serious Python programmers are you really doing them a favour by teaching them Chinese Python? It would really only work if Chinese Python became it own successful dialect of Python, independent of the standard Python implementation. Chinese Python programmers would be isolated from other Python programmers, each with their own set of third-party modules and little code sharing between the two groups. I don't think this would be good for Python as whole. Ross Ridge -- l/ // Ross Ridge -- The Great HTMU [oo][oo] rridge at csclub.uwaterloo.ca -()-/()/ http://www.csclub.uwaterloo.ca/~rridge/ db // From robert.kern at gmail.com Wed Jun 6 15:16:57 2007 From: robert.kern at gmail.com (Robert Kern) Date: Wed, 06 Jun 2007 14:16:57 -0500 Subject: Determinant of Large Matrix In-Reply-To: References: Message-ID: James Stroud wrote: > Hello All, > > I'm using numpy to calculate determinants of matrices that look like > this (13x13): > > [[ 0. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1.] > [ 1. 0. 1. 4. 1. 9. 4. 4. 1. 1. 4. 9. 4. 9.] > [ 1. 1. 0. 1. 4. 4. 9. 9. 4. 4. 1. 4. 1. 4.] > [ 1. 4. 1. 0. 9. 1. 4. 4. 9. 1. 4. 1. 4. 1.] > [ 1. 1. 4. 9. 0. 4. 4. 4. 1. 4. 1. 9. 4. 9.] > [ 1. 9. 4. 1. 4. 0. 4. 4. 9. 4. 1. 1. 4. 1.] > [ 1. 4. 9. 4. 4. 4. 0. 1. 1. 1. 9. 1. 9. 4.] > [ 1. 4. 9. 4. 4. 4. 1. 0. 4. 1. 9. 4. 4. 1.] > [ 1. 1. 4. 9. 1. 9. 1. 4. 0. 4. 4. 4. 4. 9.] > [ 1. 1. 4. 1. 4. 4. 1. 1. 4. 0. 9. 4. 9. 4.] > [ 1. 4. 1. 4. 1. 1. 9. 9. 4. 9. 0. 4. 1. 4.] > [ 1. 9. 4. 1. 9. 1. 1. 4. 4. 4. 4. 0. 4. 1.] > [ 1. 4. 1. 4. 4. 4. 9. 4. 4. 9. 1. 4. 0. 1.] > [ 1. 9. 4. 1. 9. 1. 4. 1. 9. 4. 4. 1. 1. 0.]] > > For this matrix, I'm getting this with numpy: > > 2774532095.9999971 > > But I have a feeling I'm exceeding the capacity of floats here. It's not that you're exceeding the capacity of float64 numbers, it's just that there are floating point calculations taking place. The way the determinant is calculated is by doing an LU decomposition and then multiplying down the diagonal. Although all of your entries started as integers, floating point error does accumulate. The answer that you got is within finfo(float64).eps of relative error of the actual answer. > Does > anyone have an idea for how to treat this? Is it absurd to think I could > get a determinant of this matrix? Is there a python package that could > help me? If all of your matrices are going to be integers, doing the determinant-by-minors calculations yourself is probably easy enough to code and will retain complete precision. http://mathworld.wolfram.com/DeterminantExpansionbyMinors.html -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From DustanGroups at gmail.com Sat Jun 2 07:36:17 2007 From: DustanGroups at gmail.com (Dustan) Date: Sat, 02 Jun 2007 11:36:17 -0000 Subject: Python Pop Quiz In-Reply-To: <1180751587.951837.191480@h2g2000hsg.googlegroups.com> References: <1180751587.951837.191480@h2g2000hsg.googlegroups.com> Message-ID: <1180784177.967199.156970@q69g2000hsb.googlegroups.com> On Jun 1, 9:33 pm, snor... at hotmail.com wrote: > 1. Do you like Python? yes > 2. Do you think Python is good? yes > 3. Do you think Python is real good? yes > 4. What is your favorite version of Python? The most recent one. > 5. Because of Python, do you think it will be easier to take over the > world? I don't know; I've never considered taking over the world. > If so, when? If not, when? > > 7. How many Z80 assembly language programmers does it take to equal > one Python guru? I don't know about Z80, but the word 'assembly' makes me think: .00004 > Essay: "C++ is better than C", agree or disagree? (four word maximum) I can not say. > Bonus: A rabbi walks into a bar while nursing a baby goat. He is > closely followed by a priest, and a Perl hacker. Explain. I'm glad this is just bonus. What do I win? From sjmachin at lexicon.net Wed Jun 20 08:50:31 2007 From: sjmachin at lexicon.net (John Machin) Date: Wed, 20 Jun 2007 05:50:31 -0700 Subject: Packing a simple dictionary into a string - extending struct? In-Reply-To: References: Message-ID: <1182343831.972552.119720@o11g2000prd.googlegroups.com> On Jun 20, 9:19 pm, "Jonathan Fine" wrote: > Hello > > I want to serialise a dictionary, whose keys and values are ordinary strings > (i.e. a sequence of bytes). > > I can of course use pickle, but it has two big faults for me. > 1. It should not be used with untrusted data. > 2. I want non-Python programs to be able to read and write these > dictionaries. > > I don't want to use XML because: > 1. It is verbose. > 2. It forces other applications to load an XML parser. > > I've written, in about 80 lines, Python code that will pack and unpack (to > use the language of the struct module) such a dictionary. And then I > thought I might be reinventing the wheel. But so far I've not found > anything much like this out there. (The closest is work related to 'binary > XML' -http://en.wikipedia.org/wiki/Binary_XML.) > > So, what I'm looking for is something like and extension of struct that > allows dictionaries to be stored. Does anyone know of any related work? > C:\junk>copy con adict.csv k1,v1 k2,v2 k3,v3 ^Z 1 file(s) copied. C:\junk>\python25\python Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import csv >>> adict = dict(csv.reader(open('adict.csv', 'rb'))) >>> adict {'k3': 'v3', 'k2': 'v2', 'k1': 'v1'} >>> csv.writer(open('bdict.csv', 'wb')).writerows(adict.iteritems()) >>> ^Z C:\junk>type bdict.csv k3,v3 k2,v2 k1,v1 C:\junk> Easy enough? HTH, John From twisted0n3 at gmail.com Wed Jun 20 16:21:24 2007 From: twisted0n3 at gmail.com (Twisted) Date: Wed, 20 Jun 2007 20:21:24 -0000 Subject: The Modernization of Emacs In-Reply-To: <1182344981.372713.298580@w5g2000hsg.googlegroups.com> References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182344981.372713.298580@w5g2000hsg.googlegroups.com> Message-ID: <1182370884.853838.321440@c77g2000hse.googlegroups.com> On Jun 20, 9:09 am, Kaldrenon wrote: > Imagine that a man invents a vehicle that's far safer and more > maneuverable than any existing vehicle. Imagine that the increased > safety comes from the fact that it has five wheels. How incredibly > stupid would it be for that inventor to then say, "I'm going to > convince people to buy my new vehicle, which is safer thanks to this > fifth wheel. But in order to market it, I'll take the fifth wheel off, > so it's more familiar and comfortable for them." Imagine that a man invents a vehicle that's far safer and more maneuverable than any existing vehicle. Imagine that the increased safety comes from the fact that it has five wheels. Gratuitously, he also has his own peculiar ideas regarding how one should control this vehicle, and instead of giving it a normal car steering wheel, brake, and gas pedal, he gives it two stick-like left and right throttle controls, which can be pulled back to brake and even reverse the car, pushed forwards to accelerate it, and positioned differently to cause the vehicle to rotate -- even to rotate in place, obviating the need for three-point turns and simplifying parallel parking somewhat. Unfortunately, nobody used to a normal car is remotely comfortable with these controls. They have a very steep learning curve and numerous accidents result. It turns out there's even a conversion kit available for replacing them with a normal steering wheel, brake, and gas pedal, but getting the conversion kit without crashing on the way to where you get it proves problematic because of the same unusual controls you're trying to replace. All of the driving schools, of course, teach the usual wheel-and-pedals method of controlling a motor vehicle... This seems to be a closer analogy with emacs versus normal Windows text editors. Arguably even the weird controls are superior in some way -- but only if you got used to them, which will never happen because you'll abandon it for inability to be productive with it long before that can happen, and also because the same clunky controls hobble your access to the online help that would otherwise smooth the path for you. The same problem plagues attempts to reconfigure the controls to something more normal. And the computer-driving schools -- computer classes in ordinary school -- teach standard Windows UI conventions (or their Macintosh equivalents, which correspond closely to one another). If there is any formal training in emacs use, it's effectively unobtainable due to obscurity and hard-to-findness, geographical distance, expense, or even more than one of those factors. The above applies equally to vi and its derivatives, if not more so -- vi is like taking that same already-wacky car with the two separate throttles and adding, in a fit of quaint nostalgia, the need to actually crank-start its engine. ;) From kalita at poczta.onet.pl Sat Jun 9 16:00:02 2007 From: kalita at poczta.onet.pl (Marcin Kalicinski) Date: Sat, 9 Jun 2007 21:00:02 +0100 Subject: Multiple python interpreters within the same process Message-ID: How do I use multiple Python interpreters within the same process? I know there's a function Py_NewInterpreter. However, how do I use functions like Py_RunString etc. with it? They don't take any arguments that would tell on which interpreter to run the string...? Marcin From sjmachin at lexicon.net Tue Jun 12 06:43:22 2007 From: sjmachin at lexicon.net (John Machin) Date: Tue, 12 Jun 2007 03:43:22 -0700 Subject: Floating Number format problem In-Reply-To: <466e6fbc$0$6400$9b4e6d93@newsspool2.arcor-online.net> References: <1181632259.217684.144180@d30g2000prg.googlegroups.com> <1181632572.643572.154690@n15g2000prd.googlegroups.com> <1181637985.191649.280250@x35g2000prf.googlegroups.com> <466e6fbc$0$6400$9b4e6d93@newsspool2.arcor-online.net> Message-ID: <1181645002.109344.327330@q19g2000prn.googlegroups.com> On Jun 12, 8:04 pm, Marc Christiansen wrote: > Gabriel Genellina wrote: > > En Tue, 12 Jun 2007 05:46:25 -0300, escribi?: > > >> On 6 12 , 3 16 , ici wrote: > >>> On Jun 12, 10:10 am, wrote: > > >>> > How could I format the float number like this: (keep 2 digit > >>> > precision) > >>> > 1.002 => 1 > >>> > 1.12 => 1.12 > >>> >>> print "%.02f" % (2324.012) > >>> 2324.01 > > >> But in these case: > > >>>>> print '%.02f'%1.002 > >> 1.00 > >>>>> print '%.02f'%1.00 > >> 1.00 > > >> I just expect it to output "1" , but these way will output 1.00 > > > def my_formatter_ommitting_trailing_zeroes(value): > > result = '%.2f' % value > > if result[-3:]=='.00': result = result[:-3] > > return result > > > for f in [1.0, 1.002, 1.12, 1.567, 2324.012]: > > print "%g -> %s" % (f, my_formatter_ommitting_trailing_zeroes(f)) > > Or: > > def my_other_formatter_ommitting_trailing_zeroes(value): > result = '%.2f' % value > return result.rstrip('0.') > > my_other_formatter_ommitting_trailing_zeroes(1.102) == "1.1" Marc, thanks for coming, but: >>> my_other_formatter_ommitting_trailing_zeroes(100.00) '1' >>> What does the OP want to happen with 1.2? I suspect he wants '1.2', not '1.20' Looks like a variation of Marc's idea will do the business: >>> values = [100.0, 1.0, 1.2, 1.002, 1.12, 1.567, 2324.012] >>> [('%.02f' % x).rstrip('0').rstrip('.') for x in values] ['100', '1', '1.2', '1', '1.12', '1.57', '2324.01'] Howzat? From marcoberi at gmail.com Thu Jun 7 03:04:24 2007 From: marcoberi at gmail.com (marcoberi at gmail.com) Date: Thu, 07 Jun 2007 00:04:24 -0700 Subject: Tkinter, tkMessagebox and overrideredirect In-Reply-To: References: <1181060331.167762.19180@q69g2000hsb.googlegroups.com> <1181132772.551848.192400@o5g2000hsb.googlegroups.com> Message-ID: <1181199864.217585.208370@q75g2000hsh.googlegroups.com> On Jun 6, 3:38 pm, "Eric Brunel" wrote: > My only advice would then be to avoid using the standard functions to > create dialog boxes, and to create them yourself. For example: > ---------------------------------------------------------- > from Tkinter import * [snip] > app.root.mainloop() > ---------------------------------------------------------- > But even with this, you may run into problems. For example, on my Linux > box with my window manager, the main window goes behind all other windows > once the button in the dialog is clicked. So I'd say that if you want to > bypass the window manager, bypass it for everything and do > overrideredirect(1) on all the windows you create. But this means that > you'll have to do everything "manually", especially window stacking. Besides that, the popup window is yet under the main frame... :-( Seems to me that dialogWdw.tkraise(self.root) doesn't do its job. It's like overrideredirect in main window override also tkraise on it. I can't believe there isn't an easier way to make a kiosk application without titlebar. Perhaps to create a normal window bigger than screen with title bar outside it? And after how can I ignore titlebar menu command or "x" and "-" button? Or is it possible to create a main Toplevel without "x" and "-"? Thanks. Ciao. Marco. From hyugaricdeau at gmail.com Tue Jun 5 12:02:37 2007 From: hyugaricdeau at gmail.com (Hyuga) Date: Tue, 05 Jun 2007 16:02:37 -0000 Subject: otsu threshold in python In-Reply-To: <1181053148.203548.199630@w5g2000hsg.googlegroups.com> References: <1181053148.203548.199630@w5g2000hsg.googlegroups.com> Message-ID: <1181059357.248682.38980@p77g2000hsh.googlegroups.com> On Jun 5, 10:19 am, azrael wrote: > Hy guys. > I'd like to ask you for a favour. > I tried several times to implement the otsu threshold filter in > python. but I failed every time. I found the soucre code i n Java from > the ImageJ project but I never worked in Java and there have been used > some built in Java functions which I don't know how they behave. I > also found the otsu threshold in the ia636 python module and would > like only this filter and don't want to import this library. > Is there anyone who wold like to help me. I need a function that takes > a list of 256 elements as an argument and returns the threshold values > for the threshold according to Otsu. > > In addvance, I don't expect someone to do my homework. I really tried > it, I have been googling and didn't find a standalone function. I > wasn't able write a standalone function because I don't understand the > Otsu method. I just know that it works well and that I need it. > > If there is no one that wants to help me with this problem, can > someone at least explain me in a detailed way how to implement it. > > Thanks What is the whole assignment meant to accomplish? Is the assignment to implement the Otsu method? If so, you shouldn't be trying to find library functions. Or is it just something you need for some larger task? I would ask exactly what problems you're running into, but: > it, I have been googling and didn't find a standalone function. I > wasn't able write a standalone function because I don't understand the > Otsu method. I just know that it works well and that I need it. How do you know you need it? Did you learn about this in class? And if so, are you expected to understand it? I've never even heard of it, but I googled it, and found the fourth hit pretty good: http://homepages.inf.ed.ac.uk/rbf/CVonline/LOCAL_COPIES/MORSE/threshold.pdf This gives a reasonable explanation. I couldn't tell you *exactly* why it works, but it's understandable enough from that that I can see that it should work, and to see how to implement it. Not to mention that the above PDF basically *gives* you the implementation for free (just make sure not to miss the recurrence relations at the end of the section on the Otsu method, or else you'll be screwing yourself). So give that a look and see if it helps. Hyuga From paul at boddie.org.uk Thu Jun 28 06:50:36 2007 From: paul at boddie.org.uk (Paul Boddie) Date: Thu, 28 Jun 2007 03:50:36 -0700 Subject: PEP 3107 and stronger typing (note: probably a newbie question) In-Reply-To: <1i0e1i4.uu1b912brmm8N%aleax@mac.com> References: <1182369568.941307.316260@p77g2000hsh.googlegroups.com> <5dveb4F360un0U1@mid.individual.net> <467a9209$0$22165$426a74cc@news.free.fr> <1182858785.886469.93060@n60g2000hse.googlegroups.com> <46824d8d$0$2324$426a74cc@news.free.fr> <46826e38$0$2818$426a74cc@news.free.fr> <1i0e1i4.uu1b912brmm8N%aleax@mac.com> Message-ID: <1183027836.580084.112810@w5g2000hsg.googlegroups.com> On 28 Jun, 07:53, a... at mac.com (Alex Martelli) wrote: > John Nagle wrote: > > PEP 3107 is static typing without enforcement, which is not a good thing. > > Wrong: PEP3107 is a syntax for adding arbitrary metadata annotations (so > that said annotations don't get squished where they don't belong, such > as decorators or docstrings, as they used to be in 2.*). Really, we all know where PEP 3107 came from and where people are likely to go with it. When you kick the ball up the field to the striker, what's the most likely thing the striker is going to do? Pass back to the goalkeeper? (Apart from in an England vs. Republic of Ireland game, that is.) > The PEP itself offers a good example that should be vastly sufficient to destroy the > "is static typing" notion: > > def compile(source: "something compilable", > filename: "where the compilable thing comes from", > mode: "is this a single statement or a suite?"): > > how do you get from that example to "PEP 3107 is static typing"? You just need to put yourself in the position of those advocating static typing. "Oh, 'something compilable': that's an interface, 'Compilable', which has this and this methods. [Multi-month discussion ensues on which methods.] And the filename: well, that's a string!" And so it continues. > What an absurd, illogical leap. Here, it's being used to provide > "per-argument docstrings" which a pydoc-like system could access as > compile.func_annotation['source'] and the like, and format as it likes > best. Type annotations (not necessarily for checking -- third party > libraries are free to provide completely different semantics, such as > adaptation) is another possible use, and Pythonistas' creativity may > well supply many, many others. I'll accept that it allows higher precision annotations than what we've had before, although I think it'd be a strong case of denial if we didn't admit that the people who've probably had to struggle the most with metadata in docstrings have been those who have been writing wrappers and bindings. I remember decorators being proposed as useful there, but anyway. As for javadoc-style documentation as a compelling motivation, I've seen too much of this kind of thing to be persuaded: /** * The compile method. * @param source Compilable A Compilable * @param filename String A string * @param mode Mode A mode */ public void compile(Compilable source, String filename, Mode mode); With PEP 3107, you either get the same inane commentary inline, but the code is still readable, or you have lots of prose, breaking up the signature and making it potentially harder to read. The best documentation might have some reference element as that proposed, but the prose is what makes it stand out. And in any case, I await this kind of thing with the above scheme: def compile(source : MyDoc("something compilable", some_arg, some_other_arg), filename : MyOtherDoc("where the compilable thing comes from", yet_more_stuff), mode : MyDocEnum("is this a single statement or a suite?", EnumValue("it's a statement"), EnumValue("no, it's a suite!"))): I guess this could just be me being cynical as usual, though. Paul From roy at panix.com Fri Jun 1 23:28:24 2007 From: roy at panix.com (Roy Smith) Date: Fri, 01 Jun 2007 23:28:24 -0400 Subject: Python Pop Quiz References: <1180751587.951837.191480@h2g2000hsg.googlegroups.com> Message-ID: In article <1180751587.951837.191480 at h2g2000hsg.googlegroups.com>, snorble at hotmail.com wrote: > 1. Do you like Python? Yes > 2. Do you think Python is good? Yes > 3. Do you think Python is real good? Yes > 4. What is your favorite version of Python? Whichever version it was that added string methods. > 5. Because of Python, do you think it will be easier to take over the > world? If so, when? If not, when? Just as soon as I get my orbiting brain lasers back on line. > 7. How many Z80 assembly language programmers does it take to equal > one Python guru? Trick question, the Z80 was a figment of your imagination. > Essay: "C++ is better than C", agree or disagree? (four word maximum) STL compile error diagnostics. > Bonus: A rabbi walks into a bar while nursing a baby goat. He is > closely followed by a priest, and a Perl hacker. Explain. The bartender says, "What is this, some kind of a joke?" From vedrandekovic at v-programs.com Mon Jun 25 15:46:25 2007 From: vedrandekovic at v-programs.com (vedrandekovic at v-programs.com) Date: Mon, 25 Jun 2007 12:46:25 -0700 Subject: Installing python under the linux Message-ID: <1182800785.231113.199750@n2g2000hse.googlegroups.com> Hello, I have problem with installing Python on the Linux platform.Can you tell me step by step how can I install python on linux ( please detailed ) , because I don't know anything about linux and I really don't understand python documentation about installing python on linux. Thanks!!! From twisted0n3 at gmail.com Mon Jun 25 18:46:09 2007 From: twisted0n3 at gmail.com (Twisted) Date: Mon, 25 Jun 2007 22:46:09 -0000 Subject: The Modernization of Emacs: terminology buffer and keybinding In-Reply-To: <5eaqjmF36ga72U1@mid.individual.net> References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182545268.055596.228700@i38g2000prf.googlegroups.com> <1182661040.286559.150880@q75g2000hsh.googlegroups.com> <5eaqjmF36ga72U1@mid.individual.net> Message-ID: <1182811569.871702.207010@n2g2000hse.googlegroups.com> On Jun 25, 5:32 pm, blm... at myrealbox.com wrote: > To me it's similar to "memorizing" a phone number by dialing > it enough times that it makes its way into memory without > conscious effort. I suspect that not everyone's brain works > this way, and some people have to look it up every time. > For those people, I can understand why something without a > GUI could be a painful experience. "YMMV", maybe. You'll be happy to know then that my opinion is that the phone system is archaic too. Exposing the numerical network addresses like that is so 1970s; where's the phone version of DNS, given that the technology to develop it is clearly there now, and (from my experiences with the phone menus at some 800 numbers) even the technology for you to just pick up the handset, say someone's name, and have it look them up and ring them, possibly after being prompted to accept long distance charges, reverse them, or cancel if it's LD. :) We'll actually probably see a generation of friendlier phones RSN -- either regular phones, or because VoIP providers leapfrog them and advance rapidly leaving the old telcos eating dust when these don't advance their technology and interfaces. Setting up and using voice mail or speed-dial keys still tends to be *painful*. There's still an excuse for that with cell phones since you can't put a more sophisticated interface onto something the size of a credit card, but a phone that takes up a substantial chunk of desk space really should have more than a tiny LCD screen and twelve tone keys. The only reason nobody complains much is because they're so bog standard everyone is used to them and knows how to operate them. If we had modern internet and other services and someone tried to introduce the touch-tone telephone system now, the market would reject it in a heartbeat and pursue VoIP, and Techdirt would run a "Failures" category article blaming the terrible UI and excessive fee structure. The same sort of inertia that let the phone system survive mostly unchanged over the last 20 years without improving its UI much keeps some old unix tools beloved by those who mastered them, and of course propels Windows, which has done some dumb things with its UI (and much worse under the hood). From laurent.pointal at wanadoo.fr Fri Jun 8 12:46:20 2007 From: laurent.pointal at wanadoo.fr (Laurent Pointal) Date: Fri, 08 Jun 2007 18:46:20 +0200 Subject: launching default browser References: Message-ID: <466987dc$0$27396$ba4acef3@news.orange.fr> alf wrote: > Hi, > > I wonder how to launch from python default Windows browser? In fact I > have the same question for Linux. > > thx in advancve, Via webbrowser module http://docs.python.org/lib/module-webbrowser.html (note: its in top five in google search for Python + launch + browser...) From bbxx789_05ss at yahoo.com Sun Jun 3 01:13:08 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: Sat, 02 Jun 2007 22:13:08 -0700 Subject: How to control the creation of an instance? In-Reply-To: References: Message-ID: <1180847588.831667.41190@w5g2000hsg.googlegroups.com> On Jun 2, 10:31 pm, lialie wrote: > Hi, > > suppose i have a free_object list[Sample1, Smaple2....]. when create a > new object sample(*args, **kwds), if free_object_list isn't empty, just > pop one from free_object_list instead of creating a new instance. > > any way to do this? > > I do some work as follows: > > class Sample(object): > used_object = [] > free_object = [] > > def __init__(self, *args, **kwds): > pass > > def __new__(self, *args, **kwds): > if Sample.free_object: > obj = Sample.free_object.pop(0) > else: > obj = object.__new__(Sample, *args, **kwds) > Sample.used_object.append(obj) > return obj > > ######## still get a new instance :( > > def Release(self): > Sample.used_object.remove(self) > Sample.free_object.append(self) > return True Try something like this: class A(object): pass def getObj(alist): if alist: return alist.pop() else: return A() x = [A(), A()] print x newlist = [] for i in range(0,3): newlist.append(getObj(x) ) print newlist --output:-- [<__main__.A object at 0x55bf0>, <__main__.A object at 0x55b50>] [<__main__.A object at 0x55b50>, <__main__.A object at 0x55bf0>, <__main__.A object at 0x55d30>] Examine the addresses, i.e. the set of numbers in each <....> From xah at xahlee.org Sun Jun 17 11:13:20 2007 From: xah at xahlee.org (Xah Lee) Date: Sun, 17 Jun 2007 08:13:20 -0700 Subject: The Modernization of Emacs Message-ID: <1182093200.598418.218620@e9g2000prf.googlegroups.com> [this post is a excerpt from The Modernization of Emacs, Xah Lee, 2006-04 at http://xahlee.org/emacs/modernization.html ] The Modernization of Emacs ---------------------------------------- THE PROBLEM Emacs is a great editor. It is perhaps the most powerful and most versatile text editor. And, besides text editing, it also serves as a email application, newsgroup application, ftp application, irc application, web browser, shell interface, file management application, programable calculator, calendar and personal info management application, lisp language system, among other things. These seemingly wild functionalities are employed in production daily by a significant number of programers around the world. Some calls emacs as a Operating System as a joke. (Technically it does not qualify because a OS implies management of hardware.). If emacs is such a great and powerful text editor why almost nobody knows about it? Vast majority of people who need to write will be more than happy to use editors other than emacs. Ask a Microsoft Windows user. She'll be more than happy to use Microsoft Word?. If he doesn't have MS Word, he'll use NotePad? or WordPad?. If he is a programer, most will be more than happy to use any of other graphical editors on the Windows platform or any of the Integrated development environment?. Same is true on other operating systems, and new editors spring up here and there even though they don't have as much power or flexibility as emacs. For example, there are NEdit, JEdit, Eclipse, Xcode? , or the various associated with languages or third party language software, such as Visual Basic or Borland C++. Many reasons can be made out of this. For example, emacs is not bundled on popular operating systems such as Windows or Mac, which are used by some 99% of computer users worldwide. Windows and Mac both have simple text editors bundled that will satisfy majority of computer users, which are non-professional computer users. (NotePad and WordPad on Windows, TextEdit? on Mac) For the few professional computer users, a majority will need a easy to use, yet powerful editor that also does styled text, formatting, and sundry light publishing needs such as table layout, simple line graphics drawing, embedded images, math formulas. They will choose and adopt Microsoft Word for their needs. The tiny percentage that might be interested in emacs, are programers. Even among professional programers, a majority shy away from emacs. A major difficulty among programers who do not use or like emacs, is that emacs's user interface is rather esoteric, involving arcane terminologies and keystrokes. This is in sharp contrast to the thousands of software applications used today, where their User Interface are similar and familiar to today's computer users. ---------------------------------------- THE COMMON USER INTERFACE The following is a excerpt from the Wikipedia article on Common User Access?: CUA was a detailed specification and set strict rules about how applications should look and function. Its aim was in part to bring about harmony between MS-DOS applications, which until then had implemented totally different user interfaces. Examples: * In WordPerfect, the command to open a file was [F7], [3]. * In Lotus 1-2-3, a file was opened with [/] (to open the menus), [W] (for Workspace), [R] (for Retrieve). * In Microsoft Word, a file was opened with [Esc] (to open the menus), [T] (for Transfer), [L] (for Load). * In WordStar, it was [Ctrl]+[K]+[O]. * In Emacs, a file was opened with [Ctrl]+[x] followed by [Ctrl]+ [f] (for find-file). Some programs used [Esc] to cancel an action, some used it to complete one; WordPerfect used it to repeat a character. Some programs used [End] to go to the end of a line, some used it to complete filling in a form. [F1] was often help but in WordPerfect that was [F3]. [Ins] sometimes toggled between overtype and inserting characters, but some programs used it for ?paste?. Thus, every program had to be learned individually and its complete user interface memorized. It was a sign of expertise to have learned the UIs of dozens of applications, since a novice user facing a new program would find their existing knowledge of a similar application absolutely no use whatsoever. ---------------------------------------- SIMPLE CHANGES In the following, i describe some critical changes that are also very easy to fix in emacs. If emacs officially adopt these changes, i think it will make a lot people, at least programers, like emacs and choose emacs as their text editor. * Change the keyboard shortcut of Copy & Paste to ctrl-c and ctrl- v as to be the same with all modern applications. * Change the undo behavior so that there is a Undo and Redo, as the same with all modern applications. * Get rid of the *scratch* buffer. * Change the terminology of ?kill? to ?cut?, and ?yank? to ?paste?. * Change the terminology of Meta key to Alt. * Make longlines-mode the default editor behavior for any file. Things emacs should do now, even though it eventually will do. * When opening a HTML document, automatically provide highlighting of HTML, CSS, and Javascript codes. Similarly for other multi-language files such as PHP, JSP, et al. This behavior must be automatic without requiring user to customize emacs. Possible Documentation Change Proposals * Reduce the use of the word ?buffer? in the emacs documentation. Call it ?opened file? or ?unsaved document?. * Switch the terminology of Window and Frame so it is more standard. That is, Emacs's ?Window? should be called Panes or Frames. While Emacs's ?Frame? should be termed Window. * Change the terminology of keybinding to ?keyboard shortcut? in emacs documentation. Use the term keybinding or binding only in a technical context, such as in elisp documentation. Xah xah at xahlee.org ? http://xahlee.org/ From ladynikon at gmail.com Mon Jun 25 15:56:54 2007 From: ladynikon at gmail.com (Danyelle Gragsone) Date: Mon, 25 Jun 2007 15:56:54 -0400 Subject: Installing python under the linux In-Reply-To: <1182800785.231113.199750@n2g2000hse.googlegroups.com> References: <1182800785.231113.199750@n2g2000hse.googlegroups.com> Message-ID: <59f9c5160706251256w5d18e3abo6c68eb6cab7e9bca@mail.gmail.com> Greetings, Python is usally already installed on most distros. In a terminal window type "python" to see if something happens. Also please provide what distro you are running. Danyelle On 6/25/07, vedrandekovic at v-programs.com wrote: > Hello, > > I have problem with installing Python on the Linux platform.Can you > tell me step by step how can I install > python on linux ( please detailed ) , because I don't know anything > about linux and I really don't understand > python documentation about installing python on linux. > > > > Thanks!!! > > -- > http://mail.python.org/mailman/listinfo/python-list > From duncan.booth at invalid.invalid Fri Jun 1 08:03:24 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 1 Jun 2007 12:03:24 GMT Subject: c[:]() References: <1180504190.055427.173610@h2g2000hsg.googlegroups.com> <1180554872.3356.30.camel@dot.uniqsys.com> <465DF3DE.40404@cc.umanitoba.ca> <1180566831.239580.199300@m36g2000hse.googlegroups.com> <005401c7a31a$136f7fe0$240110ac@Muse> <135tobve86qj808@corp.supernews.com> <135tru124pie2b3@corp.supernews.com> <135tv1bjqgbmsc9@corp.supernews.com> <135v9liaoqgcf83@corp.supernews.com> Message-ID: Grant Edwards wrote: > [Please quit saying "a container" if you mean lists and tuples. > "A container" is way too general. There most probably _are_ > containers for which c() does not fail.] One example of such a container is any folderish content in Zope: subscripting gets you the contained pages, calling renders the default view. From phil at riverbankcomputing.co.uk Mon Jun 11 05:47:21 2007 From: phil at riverbankcomputing.co.uk (Phil Thompson) Date: Mon, 11 Jun 2007 10:47:21 +0100 Subject: Postpone creation of attributes until needed In-Reply-To: <1181553891.447344.109390@g4g2000hsf.googlegroups.com> References: <1181553891.447344.109390@g4g2000hsf.googlegroups.com> Message-ID: <200706111047.21153.phil@riverbankcomputing.co.uk> On Monday 11 June 2007 10:24 am, Frank Millman wrote: > Hi all > > I have a small problem. I have come up with a solution, but I don't > know if it is a) safe, and b) optimal. > > I have a class with a number of attributes, but for various reasons I > cannot assign values to all the attributes at __init__ time, as the > values depend on attributes of other linked classes which may not have > been created yet. I can be sure that by the time any values are > requested, all the other classes have been created, so it is then > possible to compute the missing values. > > At first I initialised the values to None, and then when I needed a > value I would check if it was None, and if so, call a method which > would compute all the missing values. However, there are a number of > attributes, so it got tedious. I was looking for one trigger point > that would work in any situation. This is what I came up with. > > >>> class A(object): > > ... __slots__ = ('x','y','z') > ... def __init__(self,x,y): > ... self.x = x > ... self.y = y > ... def __getattr__(self,name): > ... print 'getattr',name > ... if name not in self.__class__.__slots__: > ... raise AttributeError,name > ... self.z = self.x * self.y > ... return getattr(self,name) > > >>> a = A(3,4) > >>> a.x > > 3 > > >>> a.y > > 4 > > >>> a.z > > getattr z > 12 > > >>> a.z > > 12 > > >>> a.q > > getattr q > Attribute Error: q > > In other words, I do not declare the unknown attributes at all. This > causes __getattr__ to be called when any of their values are > requested, and __getattr__ calls the method that sets up the > attributes and computes the values. > > I use __slots__ to catch any invalid attributes, otherwise I would get > a 'maximum recursion depth exceeded' error. > > Is this ok, or is there a better way? Properties... @property def z(self): return self.x * self.y Phil From george.sakkis at gmail.com Tue Jun 12 14:17:56 2007 From: george.sakkis at gmail.com (George Sakkis) Date: Tue, 12 Jun 2007 18:17:56 -0000 Subject: Multiline lamba implementation in python. In-Reply-To: <1181662615.875324.98460@o11g2000prd.googlegroups.com> References: <1b0ce1b60706112002i761dc295x9ba9c4f589c41db1@mail.gmail.com> <1181657523.655499.161880@g37g2000prf.googlegroups.com> <1181660080.153532.320600@d30g2000prg.googlegroups.com> <1181662615.875324.98460@o11g2000prd.googlegroups.com> Message-ID: <1181672276.364560.246130@d30g2000prg.googlegroups.com> On Jun 12, 11:36 am, Kay Schluehr wrote: > On 12 Jun., 16:54, George Sakkis wrote: > > > > > On Jun 12, 10:12 am, Kay Schluehr wrote: > > > > On 12 Jun., 14:57, Facundo Batista wrote: > > > > > Remember that the *only* difference between the two functions is that > > > > one is anonymous, and for other you have to came up with a name (name > > > > that if is well thought, actually adds readibility to your code). > > > > The difference is that one can be inlined since it is an expression > > > and the other has to be a statement and a reusable ( named ) > > > abstraction even when you don't need one. I have a very hard time to > > > defend this as a good design decision even when it is just a minor > > > pain point in almost all my practical purposes. > > > I think of it more as a "necessary evil" rather than a conscious > > design choice. IIRC the "official" justification is that nobody came > > up with an acceptable syntax for multiline lambdas; > > Translating this into unofficial language: Guido just didn't care a > lot about lambda and found no one of the alternative proposals > compelling. If he's actually interested in a language feature he fixes > syntax quite fast. > > > TOOWTDI is a > > secondary reason (as one can easily come up with a dozen TOOWTDI > > violations in other parts of the language). I agree though that in > > practice it's a very small limitation. > > > George > > But in the case we are discussing here it is really not obvious. > That's why the community as well as the public opinion when discussing > Python returns to the topic every once in a while. We agree about this > issue being a minor limitation but I'd vote nevertheless +1 for either > removing lambda or liberating it from the restriction of containing an > expressions only. Here we disagree; I prefer the crippled* lambda that covers the majority of my needs for inlined functions anyway than the purist all- or-nothing approach. YMMV. George * Actually you can get far if you're willing to abuse it, e.g.: foo = lambda self,x: setattr(self,'x',x) or x+1 instead of def foo(self, x): self.x = x return x+1 From rustompmody at gmail.com Sat Jun 30 14:52:09 2007 From: rustompmody at gmail.com (Rustom Mody) Date: Sun, 1 Jul 2007 00:22:09 +0530 Subject: trouble with sqlite under debian etch Message-ID: I was trying to follow the sqlalchemy tutorial on my debian etch box and got stuck with installation. Any help/pointers will be welcome. First after installing sqlalchemy needed some sqlite package synaptic showed me packages python-pysqlite, python-pysqlite1.1 and python-pysqlite2. Theres some confusion regarding numbers: python-pysqlite2 is for sqlite3 or some such thing Tried python-pysqlite1.1 and got errors. Tried 2 and got version warnings. Downloaded the tgz and did a setup build followed by a setup install Now the >>> db = create_engine('sqlite:///tutorial.db') gives me no module _sqlite From showell30 at yahoo.com Tue Jun 19 21:45:53 2007 From: showell30 at yahoo.com (Steve Howell) Date: Tue, 19 Jun 2007 18:45:53 -0700 (PDT) Subject: Help With Better Design In-Reply-To: <1182303267.427179.223720@i13g2000prf.googlegroups.com> Message-ID: <757002.54322.qm@web33506.mail.mud.yahoo.com> --- apollonius2 at gmail.com wrote: > > ON = "ON" > OFF = "OFF" > > class LightBulb: > def __init__(self, initial_state): > self.state = initial_state > > def TurnOn(self): > if self.state == OFF: > self.state = ON > else: > print "The Bulb Is Already ON!" > > def TurnOff(self): > if self.state == ON: > self.state = OFF > else: > print "The Bulb Is Aleady OFF!" > I've written code that looks a lot like that, and it's a perfectly acceptable pattern IMHO. I don't bother with the variables ON and OFF, though, as they add no clarity to simply using 'ON' and 'OFF' for the states. > [...] > The test portion of the code is actually longer than > the class > itself :-) That's usually a good thing! It means your code is concise, and your tests are exhaustive. (But that doesn't mean you can't also refactor your tests.) ____________________________________________________________________________________ Be a better Globetrotter. Get better travel answers from someone who knows. Yahoo! Answers - Check it out. http://answers.yahoo.com/dir/?link=list&sid=396545469 From jaeltong at yahoo.co.uk Mon Jun 11 04:53:55 2007 From: jaeltong at yahoo.co.uk (jaeltong at yahoo.co.uk) Date: Mon, 11 Jun 2007 01:53:55 -0700 Subject: Regular Text Message-ID: <1181552035.275951.68010@g4g2000hsf.googlegroups.com> Hallo, I am new to python. I wrote a program to retrieve the filepath. eg. C:\Programs\Python\ and write it in a text file It works fine until the path contains \t or \n. eg. C:\Programs\Python \new\. Because of the regular text format, I didn't get what I want in the text file. I tried to change the separator from \ to / but python only gives C:/ Programs/Python\new/. How should I do to make sure that the program writes the correct path in the text file? From ladynikon at gmail.com Tue Jun 19 11:56:42 2007 From: ladynikon at gmail.com (Danyelle Gragsone) Date: Tue, 19 Jun 2007 11:56:42 -0400 Subject: pydev help Message-ID: <59f9c5160706190856k5793ec2bn7d66ab518fedf1ca@mail.gmail.com> My first post! Greetings all, I am trying to get pydev up and running in linux. I have it up and running in windows but for some strange reason not here. I did install pydev a few months ago on my windows machine so that may be the reason why.. I followed this guide: http://www.fabioz.com/pydev/manual_101_install.html When I get to about the middle of the page where it seemingly loading everything and I get this: Pydev Mylar Integration (0.2.0) requires plug-in "org.eclipse.mylar (2.0.0.v20070403-1300)", or later version." Where do I get that module from? Thanks, Danyelle From doug at alum.mit.edu Wed Jun 20 17:09:00 2007 From: doug at alum.mit.edu (Douglas Alan) Date: Wed, 20 Jun 2007 17:09:00 -0400 Subject: Python's "only one way to do it" philosophy isn't good? References: <1181368143.874341.273140@r19g2000prf.googlegroups.com> Message-ID: Steven D'Aprano writes: > On Tue, 19 Jun 2007 20:16:28 -0400, Douglas Alan wrote: >> Steven D'Aprano writes: >>> On Tue, 19 Jun 2007 17:46:35 -0400, Douglas Alan wrote: >> The problem with using Scheme for real work is that it doesn't come >> with enough batteries included and there isn't a big enough of a >> community behind it that uses it for real work. > And yet there have been so many millions of dollars put into > developing Lisp... > I guess this is another example of perfection being the enemy of the > good. That's probably a valid criticism of Scheme. Not so much of Lisp in general. The reason that Common Lisp hasn't been widely adopted outside of the AI community, for instance, has more to do with most programmers apparently not understanding the joys of Cambridge Polish Notation. Also, Lisp was garbage-collected back when garbage-collection had a bad name, due to it being considered a resource hog. And then a large part of the Lisp community decided to concentrate on building special hardware (i.e. Lisp machines) for developing Lisp applications, rather than making good Lisp development environments for Fortran/C machines (i.e., all normal computers). It was clear to me at the time that it's a very hard sell to convince people to buy expensive hardware to develop in a programming language that hasn't yet been popularized. But apparently what was obvious to me was not so apparent to those who dreamed of IPO riches. > All that development into Lisp/Scheme to make it the best, purest, > most ideal programming language, with such flexibility and > extensibility. that nobody wants to use it. You can write any > library and macro system you need, but nobody has. Lisp in general has had all sorts of fancy macro packages for it since the dawn of time. But Lisp wasn't really standardized until Common Lisp in the early '80s. CLOS (the Common Lisp Object System), which is implemented via macros entirely within Common Lisp itself, was completed in the latter half of the '80s. > I don't mean literally nobody, of course. Its a figure of > speech. But it seems that people tend to program in Scheme for fun, > or to stretch the boundaries of what's possible, and not to Get The > Job Done. Well, most implementations don't have batteries included, the way that Python does. Guile attempts to, as does the Scheme Shell, but for various reasons they didn't catch on the way that Python and Perl and Ruby have. >> Well, go to MIT and take SICP and then the graduate-level sequel to >> the class, Adventures in Advanced Symbolic Programming, and then >> you'll see what some of the advantages would be. > Are you suggesting that the only way to see the advantages of Scheme > is to do a university course? No, I was just suggesting *one* way of seeing the light. I think, though, that it's probably difficult to grasp why Scheme is so interesting without taking a good class or two on the topic. Not that acquiring insight on one's own is impossible, but most people would also have a hard time seeing why group theory or linear algebra are really interesting without taking good classes one the subjects. Python doesn't really require taking a class in it because it's really very similar to many other programming languages. So if you already know any of the others, Python is very easy to pick up. Scheme, on the other hand, is more of a departure from what most people would already be comfortable with. >> A good multimethod system, e.g., would make Python a significantly nicer >> language for my purposes, for instance. > http://en.wikipedia.org/wiki/Multimethod#Python Sure, you can do it in Python, but I bet that it's neither very fun, nor efficient. >> For the record, I have a huge problem with NIH-syndrome, and think that >> every programming language in the world could learn a thing or two from >> what other languages have gotten right. > Of course. And Python, more than most, has shamelessly copied > features from other languages. To make myself a bit more clear, I don't think that Python suffers all that much from NIH. On the other hand, I think that many people in discussion forums in general often do. Here being no exception. > So the question is, are Scheme macros one of those things that > "other languages have gotten right"? Could they be a case of > over-generalization? Or somewhere in between? I don't know of any language that is not a dialect of Lisp that has a good syntax extension mechanism. Lisp dialects tend to get it right, more or less, but solving the issue is much more difficult for any language that doesn't have a Lisp-like syntax. Lisp's syntax is particularly amenable to syntax extension. |>oug From bytter at gmail.com Fri Jun 22 19:24:17 2007 From: bytter at gmail.com (Bytter) Date: Fri, 22 Jun 2007 23:24:17 -0000 Subject: SIMD powered Python Message-ID: <1182554657.444684.268050@i13g2000prf.googlegroups.com> Hi! Is there any I&D ongoing about using SIMD [1] instructions, like SSE [2], to speed up Python, especially regarding functional features, like list comprehension, map and reduce, etc.. ? Best regards, Hugo Ferreira -- [1] http://en.wikipedia.org/wiki/SIMD [2] http://en.wikipedia.org/wiki/Streaming_SIMD_Extensions From weidongtom at gmail.com Wed Jun 20 01:02:39 2007 From: weidongtom at gmail.com (weidongtom at gmail.com) Date: Wed, 20 Jun 2007 05:02:39 -0000 Subject: Permutation over a list with selected elements In-Reply-To: <1hzz4a8.13g72fy1tvbckgN%aleax@mac.com> References: <1182238025.739189.208970@a26g2000pre.googlegroups.com> <1hzz4a8.13g72fy1tvbckgN%aleax@mac.com> Message-ID: <1182315759.788622.230380@n15g2000prd.googlegroups.com> On Jun 20, 12:37 pm, a... at mac.com (Alex Martelli) wrote: > weidong... at gmail.com wrote: > > Hi, > > > I have been working at this problem, and I think I need apermutation > > algorithm that does > > the following: > > > Given a list of elements that are either a character or a character > > follows by a number, e.g. > > > ['a', 'b', 'c1', 'd', 'e1', 'f', 'c2', 'x', 'e2'] > > > find all the permutations that are given by switching the positions of > > the elements that: > > (1) begins with the same letter, and > > (2) follows by a number. > > > With the above list, some possible permutations are: > > > ['a', 'b', 'c2', 'd', 'e1', 'f', 'c1', 'x', 'e2'] > > ['a', 'b', 'c1', 'd', 'e2', 'f', 'c2', 'x', 'e1'] > > ['a', 'b', 'c2', 'd', 'e2', 'f', 'c1', 'x', 'e1'] > > > Can anyone help me out? Thanks in advance. > > I would proceed in 2 steps: > 1. find all the sets of indices that are to be permuted > 2. produce all the permutations given said sets > > Now (1) is pretty easy: > > import collections > > def find_sets_of_indices_to_permute(L): > set_by_letter = collections.defaultdict(list) > for i, elem in enumerate(L): > if len(elem)>1: > set_by_letter[elem[0]].append(i) > return set_by_letter.values() > > For (2), it looks like we need 2 sub-steps: > > 2.1. do all permutations of a list given ONE set of indices to permute > 2.2. apply the function sub (2.1) to all the sets of indices to permute > > let's do 2.1 the lazy way, i.e., recursively: > > def all_permutations_given_indices(L, indices): > yield L > if len(indices) < 2: > return > x = indices.pop() > pivot = L[x] > for y in indices: > L[x] = L[y] > L[y] = pivot > for permut in all_permutations_given_indices(L, indices): > yield permut > L[y] = L[x] > L[x] = pivot > indices.append(x) > > This suggests doing 2.2 recursively as well: > > def all_permutations_with_constraints(L, constraints): > if len(constraints) == 1: > for p in all_permutations_given_indices(L, constraints[0]): > yield L > return > indices = constraints.pop() > for p in all_permutations_given_indices(L, indices): > for pp in all_permutations_with_constraints(p, constraints): > yield pp > constraints.append(indices) > > and, putting it all together: > > def do_it_all(L): > sets_of_indices = find_sets_of_indices_to_permute(L) > for p in all_permutations_with_constraints(L, sets_of_indices): > print p > > Applied to your example list, this gives: > > brain:~ alex$ python cp.py > ['a', 'b', 'c1', 'd', 'e1', 'f', 'c2', 'x', 'e2'] > ['a', 'b', 'c2', 'd', 'e1', 'f', 'c1', 'x', 'e2'] > ['a', 'b', 'c1', 'd', 'e2', 'f', 'c2', 'x', 'e1'] > ['a', 'b', 'c2', 'd', 'e2', 'f', 'c1', 'x', 'e1'] > > Warning: untested beyond this single run, and _definitely_ not optimal > in either clarity, style, or speed -- just a quick hack to get you > started. > > Alex Thanks. From johnmfisher at comcast.net Thu Jun 14 13:21:04 2007 From: johnmfisher at comcast.net (John Fisher) Date: Thu, 14 Jun 2007 10:21:04 -0700 Subject: OS X install confusion Message-ID: <1hzp0kw.4i0y5i1cqnlwoN%johnmfisher@comcast.net> Hi Groupies, I have an Intel Macbook running OS X 10.4. It came installed with Python 2.3.5. I have since installed MacPython with version 2.4.4, cool. When I open a bash terminal session and type python, it brings up version 2.3.5. If I type IDLE it brings up version 2.4.4. My question: what do I have to do to get it to bring up 2.4.4 with the "python" command? Thanks for bringing light to my ignorance. JF From nickjbyrne at gmail.com Thu Jun 21 10:09:44 2007 From: nickjbyrne at gmail.com (Nick) Date: Thu, 21 Jun 2007 07:09:44 -0700 Subject: strip() 2.4.4 In-Reply-To: References: <1182432181.050589.5800@n2g2000hse.googlegroups.com> Message-ID: <1182434984.235746.193340@q69g2000hsb.googlegroups.com> On 21 Jun, 14:53, Neil Cerutti wrote: > On 2007-06-21, Nick wrote: > > > > > strip() isn't working as i expect, am i doing something wrong - > > > Sample data in file in.txt: > > > 'AF':'AFG':'004':'AFGHANISTAN':'Afghanistan' > > 'AL':'ALB':'008':'ALBANIA':'Albania' > > 'DZ':'DZA':'012':'ALGERIA':'Algeria' > > 'AS':'ASM':'016':'AMERICAN SAMOA':'American Samoa' > > > Code: > > > f1 = open('in.txt', 'r') > > > for line in f1: > > print line.rsplit(':')[4].strip("'"), > > > Output: > > > Afghanistan' > > Albania' > > Algeria' > > American Samoa' > > > Why is there a apostrophe still at the end? > > Most likely it's the newline at the end of each record that's > getting in your way. > > You can double-strip it. > > for line in f1: > print line.strip().rsplit(':')[4].strip("'") > > -- > Neil Cerutti > The world is more like it is now than it ever has been before. --Dwight > Eisenhower Thank you all very much for your input, the above solved the problem as most of you had already pointed out. From vriolk at gmail.com Wed Jun 20 05:49:06 2007 From: vriolk at gmail.com (xhm) Date: Wed, 20 Jun 2007 09:49:06 -0000 Subject: Python IDE In-Reply-To: <1182249585.535675.143460@m36g2000hse.googlegroups.com> References: <1182249585.535675.143460@m36g2000hse.googlegroups.com> Message-ID: <1182332946.528172.26590@w5g2000hsg.googlegroups.com> On Jun 19, 1:39 pm, Tom Gur wrote: > Hi, > which IDE would you recommend for a python ? pydev (http://pydev.sourceforge.net) for Eclipse is Ok and has everything you will expect in a commercial IDE, including code refactoring, code intelligence, and a Python debugger. Being a Java SWT application it maybe slow, and make take a long time to start. Nowadays, when I need a quick and dirty solution, or when I need to test some code snippets interactively WITH _code completion_ I typically use PyScripter http://mmm-experts.com/Downloads.aspx?ProductId=4 JEdit (www.jedit.org) is another free and robust alternative with support for Python, if you install all the necessary plugins. I could not get the jPyDebug plugin to work, yet it is the only "IDE" that I know of which has support and syntax highlighting for PSP (Python Server Pages). To sum it up, here are some Python IDEs in my order of preference: PyScripter http://mmm-experts.com/Downloads.aspx?ProductId=4 JEdit (www.jedit.org) + jPyDebug plugin pydev (http://pydev.sourceforge.net) requires Eclipse WingIDE http://www.wingware.com/wingide ActiveState Komodo IDE (commercial) http://www.activestate.com/Products/Komodo/ ActiveState Komodo Edit (freeware, no debugger) http://www.activestate.com/Products/komodo_edit/ DrPython http://drpython.sourceforge.net/ PyPE http://pype.sourceforge.net/ BOA Constructor http://boa-constructor.sourceforge.net/ From i3dmaster at gmail.com Sun Jun 17 02:45:51 2007 From: i3dmaster at gmail.com (i3dmaster) Date: Sun, 17 Jun 2007 06:45:51 -0000 Subject: Is there a way to hook into module destruction? In-Reply-To: <1182060189.246474.128710@j4g2000prf.googlegroups.com> References: <1182060189.246474.128710@j4g2000prf.googlegroups.com> Message-ID: <1182062751.957483.278010@o11g2000prd.googlegroups.com> On Jun 16, 11:03 pm, Gerald Kaszuba wrote: > On Jun 17, 6:16 am, Neal Becker wrote: > > > Code at global scope in a module is run at module construction (init). Is > > it possible to hook into module destruction (unloading)? > > Try the __del__ method. > > Seehttp://docs.python.org/ref/customization.htmlfor the docs. > > -- > Gerald Kaszubahttp://geraldkaszuba.com I doubt python calls __del__ when unloading module... and plus, I don't really think python does module unloading though. del module after import it got it removed from the global namespace but it does not clean reference I bet, so completely unloading a module should take more energy of that... Jim From bruno.desthuilliers at gmail.com Mon Jun 11 16:32:06 2007 From: bruno.desthuilliers at gmail.com (bruno.desthuilliers at gmail.com) Date: Mon, 11 Jun 2007 13:32:06 -0700 Subject: *Naming Conventions* In-Reply-To: References: <1180909218.939713.112010@q69g2000hsb.googlegroups.com> <1180990280.960271.235550@h2g2000hsg.googlegroups.com> <466699e9$0$2308$426a74cc@news.free.fr> <46690c7c$0$32006$426a34cc@news.free.fr> Message-ID: <1181593926.973062.50190@g4g2000hsf.googlegroups.com> On Jun 8, 2:06 pm, Neil Cerutti wrote: > On 2007-06-08, Bruno Desthuilliers wrote: > > Neil Cerutti a ?crit : (snip) > > >> Certainly i and j are just as generic, but they have the > >> advantage over 'item' of being more terse. > > > I'm not sure this is really an "advantage" here. > > Why not? > Because 1/ too much terseness (like too much verbosity) goes against readability, 2/ 'i' and 'j' are canonical names for C-style for loops indices - and Python's for(each) loops are very different... A few special cases aside, one-letter identifiers are bad when it comes to readability. As far as I'm concern, I stopped using 'j' even in C code a long time ago - as soon as I have too distinct loop indices, I can never remember what are 'i' and 'j' supposed to represent, so I prefer to name them more explicitly (ie : 'row' and 'col'). Just make the test: for (i=0; i < mi; i++) for (j-0; j < mj; j++) f(a[i][j]); vs for (row=0; row < nb_rows; row++) { for (col=0; col < nb_cols; col++) { init_item_at(grid[row][col]); } } From nejtak... Tue Jun 5 17:12:34 2007 From: nejtak... (Troels Thomsen) Date: Tue, 5 Jun 2007 23:12:34 +0200 Subject: how to print out each single char from a string in HEX format? References: <1180998219.005688.323200@r19g2000prf.googlegroups.com> <1181001782.216372.78410@r19g2000prf.googlegroups.com> Message-ID: <4665d1c9$0$52190$edfadb0f@dread11.news.tele.dk> > Great! It works. > There is a builtin function called hex() that does the same, but also shares the same problem as the solution above: >>> hex(10) '0xa' >>> This is probably not "nice" in your printouts, it doesn't allign. with the printf inspired solution you can set the precision like this: >>> a = "12\n34" >>> for c in a: ... print "%#04x" % ord(c), ... 0x31 0x32 0x0a 0x33 0x34 >>> regards troels From Darren.Weber at radiology.ucsf.edu Tue Jun 12 20:31:35 2007 From: Darren.Weber at radiology.ucsf.edu (DarrenWeber) Date: Wed, 13 Jun 2007 00:31:35 -0000 Subject: matrix class Message-ID: <1181694695.015143.72390@g37g2000prf.googlegroups.com> Below is a module (matrix.py) with a class to implement some basic matrix operations on a 2D list. Some things puzzle me about the best way to do this (please don't refer to scipy, numpy and numeric because this is a personal programming exercise for me in creating an operational class in pure python for some *basic* matrix operations). 1. Please take a look at the __init__ function and comment on the initialization of the list data with respect to unique memory allocation. 2. In the operator overloading of __add__, __sub__, etc., the statement isinstance(q, Matrix) raises exceptions every time. This statement works fine outside of the class definition, but not during the operator evaluation. What is going here? ## BEGIN MODULE FILE class Matrix: """ Create and manipulate a matrix object Matrix(data, dim) data = list of lists (currently only 2D) dim=(row,col) tuple of int For example, #data = [[0.0] * c for i in xrange(r)] data = [[0.0,0.1],[1.0,1.1],[2.0,2.1]] rowN =len(data) colN =len(data[0]) m = Matrix(data) m = Matrix(data,dim=(rowN, colN)) d1 = [[0.0, 0.1], [1.0, 1.1], [2.0, 2.1]] # 3x2 matrix d2 = [[0.0, 0.1, 0.2], [1.0, 1.1, 1.2]] # 2x3 matrix m1 = Matrix(d1) m2 = Matrix(d2) #m3 = m1 + m2 # dimension error m3 = m1 + m2.transpose() m3 = m1 - m2.transpose() m3 = m1 * m2 # 3x3 m3 = m2 * m1 # 2x2 m1[2,:] m1[:,2] """ def __init__(self, data=None, dim=None): """ create a matrix instance. m = Matrix([data [, dim]]) is a 2D matrix comprised of a nested list of floats is a tuple of int values for the row and column size (r,c) eg: data = [[0.0,0.1],[1.0,1.1],[2.0,2.1]] dim = (3,2) # or (len(data),len(data[0])) """ if data != None: self.data = data r = len(data) c = len(data[0]) # Are all the rows the same length? rowLenCheck = sum([len(data[i]) != c for i in range(r)]) if rowLenCheck > 0: raise ValueError else: self.dim = (r,c) if dim != None: if (dim[0] == r) and (dim[1] == c): self.dim = (r,c) else: # over-ride the dim input, do not reshape data! # print a warning? self.dim = (r,c) else: if dim != None: if len(dim) == 2: self.dim = tuple(dim) r = dim[0] c = dim[1] else: # maybe a new exception type? arg = ("len(dim) != 2: ", dim) raise ValueError, arg # BEGIN ALT ---------------------------------------- # Does this give unique memory for each element? # self.data = [[0.0] * c for i in xrange(r)] # It seems that the initialization does not generate # unique memory elements because all list elements # refer to the same number object (0.0), but # modification of any element creates a unique value, # without changing any other values, eg: ##>>> x = [[0.0] * 3 for i in xrange(2)] ##>>> id(x) # 3079625068L # >>> id(x[0][0]) # 136477300 # >>> id(x[0][1]) # 136477300 # >>> id(x[1][1]) # 136477300 # >>> x[0][0] = 1.0 # >>> x # [[1.0, 0.0, 0.0], [0.0, 0.0, 0.0]] # >>> # END ALT ---------------------------------------- # create a zero row vector, with unique memory for each element self.data = [[x * 0.0 for x in range(c)]] for i in range(1,r): self.data.append([x * 0.0 for x in range(c)]) else: self.data = [] self.dim = (0,0) #print self.__doc__ def __getitem__(self, i): """ matrix[r,c] returns values from matrix.data, eg: >>> data = [[0.0,0.1],[1.0,1.1],[2.0,2.1]] >>> m = Matrix(data) >>> m[2,:] [2.0, 2.1000000000000001] """ r = i[0] c = i[1] #print "index: (%s, %s)" % (r,c) #print "value: ", self.data[r][c] return self.data[r][c] def reshape(self, newdim=None): 'reshape a matrix object: matrix.reshape(newdim)' print "something to implement later" pass def transpose(self): 'transpose a matrix: m2 = m1.transpose()' m = Matrix(dim=(self.dim[1],self.dim[0])) for r in range(self.dim[0]): for c in range(self.dim[1]): m.data[c][r] = self.data[r][c] return m def __add__(self, q): 'matrix addition: m3 = m1 + m2' # if isinstance(q, Matrix): # arg = ("q is not a matrix instance", q) # raise TypeError, arg if self.dim != q.dim: arg = ("p.dim != q.dim", self.dim, q.dim) raise IndexError, arg else: # do the addition m = Matrix(dim=self.dim) for r in range(self.dim[0]): # rows of p and q m.data[r] = map(lambda x, y: x + y, self.data[r], q.data[r]) return m def __sub__(self, q): 'matrix subtraction: matrix - matrix' # if isinstance(q, Matrix): # arg = ("q is not a matrix instance", q) # raise TypeError, arg if self.dim != q.dim: arg = ("p.dim != q.dim", self.dim, q.dim) raise IndexError, arg else: # do the subtraction m = Matrix(dim=self.dim) for r in range(self.dim[0]): # rows of p and q m.data[r] = map(lambda x, y: x - y, self.data[r], q.data[r]) return m def __mul__(self, q): """ multiply two matrices: m = p * q # p and q are matrix objects and p.dim[1] == q.dim[0] """ # if isinstance(q, Matrix): # arg = ("q is not a matrix instance", q) # raise TypeError, arg if self.dim[1] != q.dim[0]: arg = ("p.dim[1] != q.dim[0]", self.dim[1], q.dim[0]) raise IndexError, arg else: # do the multiplication m = Matrix(dim=(self.dim[0], q.dim[1])) for r in range(self.dim[0]): # rows of p for c in range(q.dim[1]): # cols of q # get the dot product of p(r,:) with q(:,c) pVec = self.data[r] qVec = [q.data[a][c] for a in xrange(q.dim[0])] m.data[r][c] = sum(map(lambda x, y: x * y, pVec, qVec)) return m # let's not try to divide for now (leave the inverse stuff to c/c+ +) def __len__(self): return self.dim[0] * self.dim[1] def __str__(self): # print the matrix data s = "" for r in range(self.dim[0]): for c in range(self.dim[1]): s += "%f " % (self.data[r][c]) s += "\n" return s def printFormat(self, format): """ print the matrix data nicely formatted, eg: matrix.printFormat("%8.4f") """ for r in range(self.dim[0]): for c in range(self.dim[1]): print format % (self.data[r][c]), print def __repr__(self): # return something that will recreate the object return "Matrix(%s, %s)" % (self.data, self.dim) # -------------------------------------------------------------------------------- # Explore the functionality - should be unit testing # >>> m = Matrix(dim=(2,2)) # >>> type(m) # # >>> m.dim #(2, 2) # >>> m.len() # 4 # >>> m.data # [[0.0, 0.0], [0.0, 0.0]] # >>> m.dim # (2, 2) # >>> id(m.data[0][0]) # 136477668 # >>> id(m.data[0][1]) # 136477380 # >>> id(m.data[1][0]) # 136477668 # >>> id(m.data[1][1]) # 136477380 # >>> m.data[0][0] = 1.0 # >>> m.data[1][0] = 2.0 # >>> m.data # [[1.0, 0.0], [2.0, 0.0]] testing = 1 if testing: d1 = [[0.0, 0.1], [1.0, 1.1], [2.0, 2.1]] # 3x2 matrix d2 = [[0.0, 0.1, 0.2], [1.0, 1.1, 1.2]] # 2x3 matrix m1 = Matrix(d1) m2 = Matrix(d2) #m3 = m1 + m2 # "dimension" error m3 = m1 + m2.transpose() m3 = m1 - m2.transpose() m3 = m1 * m2 # 3x3 m3 = m2 * m1 # 2x2 ## END MODULE FILE From cam.ac.uk at mh391.invalid Thu Jun 21 05:50:24 2007 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Thu, 21 Jun 2007 10:50:24 +0100 Subject: Can python access windows clipboard In-Reply-To: <1182416346.377857.103540@z28g2000prd.googlegroups.com> References: <1182416346.377857.103540@z28g2000prd.googlegroups.com> Message-ID: MaHL wrote: > Can I use python to copy something(like a string) to the clipboard, so > that I can paste it somewhere else. Is there a way to do this? If you're using Cygwin Python you can just open /dev/clipboard and work on that. -- Michael Hoffman From bdesth.quelquechose at free.quelquepart.fr Sat Jun 30 00:36:34 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sat, 30 Jun 2007 06:36:34 +0200 Subject: appending file In-Reply-To: <0Jchi.16365$2v1.11172@newssvr14.news.prodigy.net> References: <0Jchi.16365$2v1.11172@newssvr14.news.prodigy.net> Message-ID: <46856d41$0$15726$426a74cc@news.free.fr> Kuo a ?crit : > Hi, > I'm trying to read a file (fileA) and append to another file(fileB). > However, I always get "^M" at the end. Does anyone know why ? Here is my > code ? > > os.system("../syn/pin_assign.pl customer_netlist.txt") > shutil.copy("../fileB", "fileB") > ucf = open("fileB", "a") > pin = open("fileA", "r") > ucf.write(pin.read()) > ucf.close; > pin.close; > sys.exit(0); > > Here is what I get. > > # FPGA CLOCK^M > NET "SYSCLK_A" loc = N16 | TNM_NET = SYSCLK_A;^M > NET "SYSCLK_AN" loc = M16 | TNM_NET = SYSCLK_A;^M > Looks like a problem with newline format. Googling for "universal newline" may be a good start. From cjlesh at gmail.com Thu Jun 21 09:47:24 2007 From: cjlesh at gmail.com (cjl) Date: Thu, 21 Jun 2007 06:47:24 -0700 Subject: newbie question: parsing street name from address Message-ID: <1182433644.485185.197690@w5g2000hsg.googlegroups.com> P: I am working on a project that requires geocoding, and have written a very simple geocoder that uses the Google service. I would like to be able to extract the name of the street from the addresses in my data, however they vary significantly. Here a some examples: 25 Main St 2500 14th St 12 Bennet Pkwy Pearl St Bennet Rd and Main st 19th St As you can see, sometimes I have the house number, and sometimes I do not. Sometimes the street name is a number. Sometimes I simply have the names of intersecting streets. I would like to be able to parse the above into the following: Main St 14th St Bennet Pkwy Pearl St Bennet Rd Main St 19th St How might I approach this complex parsing problem? -CJL From nick at craig-wood.com Tue Jun 19 17:30:05 2007 From: nick at craig-wood.com (Nick Craig-Wood) Date: Tue, 19 Jun 2007 16:30:05 -0500 Subject: Using a switch-like if/else construct versus a dictionary? References: <1182282008.522677.269730@g4g2000hsf.googlegroups.com> Message-ID: asincero wrote: > Which is better: using an if/else construct to simulate a C switch or > use a dictionary? Example: Here is a technique I've used a lot. I think I learnt it from "Dive into Python" class foo(object): def do_1(self): print "I'm 1" def do_2(self): print "I'm 2" def do_3(self): print "I'm 3" def do_4(self): print "I'm 4" def do_5(self): print "I'm 5" def dispatch(self, x): getattr(self, "do_"+str(x))() f = foo() f.dispatch(1) f.dispatch(3) f.dispatch(17) It will blow up gracelessly with an AttributeError if you pass it something which it can't handle. That is easy to fix. You could name dispatch, __call__ if you wanted a slightly neater syntax. f = foo() f(1) f(3) f(17) You can do the same thing in a function using locals()["do_"+str(x)] but I always find that if I've got to that point I should be using a class instead. > Note that in this situation using OO polymorphism instead of a switch- > like construct wouldn't be applicable, or at least I can't see how it > could be. If there is a "type" or "id" in your objects and you are switching on it, then you should be using polymorphism. Make each seperate "type" a seperate class type and implement the methods for each one. All the switches will disappear from your code like magic! Post more details if you want more help! -- Nick Craig-Wood -- http://www.craig-wood.com/nick From lesande at gmail.com Wed Jun 13 15:32:13 2007 From: lesande at gmail.com (Lee Sander) Date: Wed, 13 Jun 2007 12:32:13 -0700 Subject: mapping subintervals Message-ID: <1181763133.202079.265790@i38g2000prf.googlegroups.com> hi, I have the following problem which is turning out to be non-trivial. I realize that this is not exactly a python problem but more of an algorithm problem -- but I post it here because I want to implement this in python. I want to write a code that given an interval (integer tuple: start,stop) will find which other interval it matches to. Here is an example, suppose I have the following NON-OVERLAPPING intervals 10 - 21 ==> 'a1' 34 - 51 ==> 'a2' 77 - 101 ==> 'a3' etc So, suppose I'm give an interval such as (42,50), I should go through the list and map it to "a2" etc if the region is a subset of an exiting interval. If the query interval does not exist in the table or maps to two or more intervals (eg, (45, 80)) the program return a None. One naive way to solve this problem is to create an array such as follows: [None, None, None, ...., None, a1, a1, a1, ..., a1, None, None ..., None, a2, ... etc] at indicies 1 2 3 9 10 11 12 21 22 23 33 34, ... now with this in place I can easily solve the problem. However, this is not a feasable solution because the initial list has intervals whose range can go to billions! So I need a smarter idea. So what I can do is sort the initial list and then go through each element from the start and test if the a > X[i][0] and b < X[i][1] where (a,b) is my query start and stop and X is a n x 2 array with the known intervals. I don't like this solution because it can be really really slow as for each query I'm doing a linear search and on average I'll be searching almost half the list before I find the right interval. Is there a smarter way to do this? I've my problem is not clear please let me know and I'll try to explain the unclear parts again. Many thanks Lee From pinkfloydhomer at gmail.com Wed Jun 20 06:30:02 2007 From: pinkfloydhomer at gmail.com (pinkfloydhomer at gmail.com) Date: Wed, 20 Jun 2007 10:30:02 -0000 Subject: Non-blocking keyboard read Message-ID: <1182335402.853626.72150@n60g2000hse.googlegroups.com> I am writing a curses application, but the getch() does not seem to give me all I want. Of course, if I press "d", it returns an ord("d") and so on. But I want to be able to detect whether alt, shift or ctrl has been pressed also. Shift is normally covered by returning an uppercase character instead and ctrl seems to return control codes (as is normal, I guess), but alt I can't detect with getch, it seems. Preferably, I would like one of two things: 1) Having a getch() (or other function) that returns a code like now, but with different codes depending on the status of the ctrl, alt or shift keys, for instance by setting higher bits or something. Just as long as I can differentiate between "d", "D", ctrl+"d", alt+"d", shift +"d" and maybe ctrl+alt+"d" and ctrl+shift+"d" etc. 2) Having a way to read the keyboard status at any given time, for instance just reading a dictionary (or whatever) of bool for each key. So that key[KEY_D] == true when d is being pressed, and key[LEFT_ALT] == true when left alt is being pressed etc. 1) can of course be created from 2) which is lower level, so I would prefer 1) to save me some work. Also, are there problems with using a non-curses method of reading keyboard input, within a curses application? /David From rustompmody at gmail.com Mon Jun 25 11:28:04 2007 From: rustompmody at gmail.com (Rustom Mody) Date: Mon, 25 Jun 2007 20:58:04 +0530 Subject: amara bugs Message-ID: I tried to install amara according to the recommendations on this list. There were evidently compilation errors. The results are below Also the quick reference gives 404 not found errors Thanks $ sudo easy_install amara Searching for amara Best match: Amara 1.2.0.2 Processing Amara-1.2.0.2-py2.4.egg Amara 1.2.0.2 is already the active version in easy-install.pth Installing trimxml script to /usr/bin Installing flextyper script to /usr/bin Installing scimitar script to /usr/bin Using /usr/lib/python2.4/site-packages/Amara-1.2.0.2-py2.4.egg Processing dependencies for amara Searching for 4Suite-XML>=1.0.2 Reading http://www.python.org/pypi/4Suite-XML/ Reading http://4suite.org/ Reading http://www.python.org/pypi/4Suite-XML/1.0.2 Best match: 4Suite-XML 1.0.2 Downloading http://cheeseshop.python.org/packages/source/4/4Suite-XML/4Suite-XML-1.0.2.zip#md5=b5515baa72c1b88613af71d2af0a539a Processing 4Suite-XML-1.0.2.zip Running 4Suite-XML-1.0.2/setup.py -q bdist_egg --dist-dir /tmp/easy_install-w9816x/4Suite-XML-1.0.2/egg-dist-tmp-xg9AOi Ft/Lib/src/number.c:7:20: error: Python.h: No such file or directory Ft/Lib/src/number.c:10: error: expected '=', ',', ';', 'asm' or '__attribute__' before '*' token Ft/Lib/src/number.c:14: error: expected '=', ',', ';', 'asm' or '__attribute__' before '*' token Ft/Lib/src/number.c:36: error: expected '=', ',', ';', 'asm' or '__attribute__' before '*' token Ft/Lib/src/number.c:57: error: expected '=', ',', ';', 'asm' or '__attribute__' before '*' token Ft/Lib/src/number.c:75: error: expected '=', ',', ';', 'asm' or '__attribute__' before 'numberMethods' Ft/Lib/src/number.c:82: warning: return type defaults to 'int' Ft/Lib/src/number.c: In function 'DL_EXPORT': Ft/Lib/src/number.c:82: error: expected declaration specifiers before 'initnumber' Ft/Lib/src/number.c:99: error: expected '{' at end of input error: Setup script exited with error: command 'gcc' failed with exit status 1 From jadestar at idiom.com Tue Jun 12 20:28:04 2007 From: jadestar at idiom.com (James T. Dennis) Date: Wed, 13 Jun 2007 00:28:04 -0000 Subject: logging module and threading References: Message-ID: <1181694483.996767@smirk> Ross Boylan wrote: > I would like my different threads to log without stepping on each > other. > Past advice on this list (that I've found) mostly says to send the > messages to a Queue. That would work, but bypasses the logging > module's facilities. > The logging module itself is "thread-safe", but I think that just > means that individual output is protected. If I have, in temporarly > sequence: > thread 1: warning("A") > thread 2: info("something") > thread 1: warning("B") > then I think I'll get them output in this order. It's thread-safe in > that the log will not end up with an entry like > A > some > B > thing > (I think). But I want to get, for example, > A > B > something > What I would like is for each thread to emit a chunk of log messages > when it finishes a unit of work. This sounds like a job for the Queue class/module to me. Could you create a Queue such that all your worker threads are producers to it and you have one dedicated thread as a consumer that relays log entries from the Queue into your loggers? -- Jim Dennis, Starshine: Signed, Sealed, Delivered From john at datavoiceint.com Fri Jun 15 11:40:58 2007 From: john at datavoiceint.com (HMS Surprise) Date: Fri, 15 Jun 2007 08:40:58 -0700 Subject: Re printing on same line. In-Reply-To: References: <1181920861.071568.4860@w5g2000hsg.googlegroups.com> Message-ID: <1181922058.191315.164090@g4g2000hsf.googlegroups.com> >... ruining the > output? > ? None. From warren at muse.com Fri Jun 1 00:55:57 2007 From: warren at muse.com (Warren Stringer) Date: Thu, 31 May 2007 21:55:57 -0700 Subject: c[:]() In-Reply-To: References: <1180504190.055427.173610@h2g2000hsg.googlegroups.com> <1180554872.3356.30.camel@dot.uniqsys.com> <465DF3DE.40404@cc.umanitoba.ca> <1180566831.239580.199300@m36g2000hse.googlegroups.com> <005401c7a31a$136f7fe0$240110ac@Muse> <135tobve86qj808@corp.supernews.com> <135tru124pie2b3@corp.supernews.com> <135tv1bjqgbmsc9@corp.supernews.com> <002801c7a3fb$56cc8030$240110ac@Muse> Message-ID: <002b01c7a409$2494f030$240110ac@Muse> Steve Holden Wrote > The general rule in Python is that you provide the right objects and > expect error tracebacks if you do something wrong. So I don't really see > why you feel it's necessary to "[be] unambiguous about using a > container" when you don't appear to feel the same about its containing > only functions. Give that everything is a first class object "Look ma! I'm an object"() # causes Traceback (most recent call last) ... TypeError: 'str' object is not callable def funky(): lookma() funky() # causes Traceback (most recent call last)... NameError: global name 'lookma' is not defined Means that any exception can be caught, thus equal. `c[:]()` is unambiguous because: def c(): print 'yo' c() # works, but c[:]() # causes: Traceback (most recent call last)... c[:]() # causes: TypeError: unsubscriptable object There are many `c()` to be found in the wild and no `c[:]()`, thus unambiguous. To be honest, I wasn't sure, until testing this, just now. > > You're right. At the same time, version 3 is coming up soon. There is a > > short window of opportunity for profound changes. > > > Which closed at the end of April as far as PEPs affecting the initial > implementation of version 3 was concerned. The python3000 and > python-ideas lists are the correct forum for those issues, though you > will of course get all sorts of opinions on c.l.py. Oh well. Perhaps I can relax and actually write functioning code ;-) What do you mean by 'c.l.py' ? The first thing that comes to mind is 'clippy' that helpful little agent in Word that helped pay for Simonyi's trip into space. Ching ching, Warren From jaywgraves at gmail.com Thu Jun 21 11:41:36 2007 From: jaywgraves at gmail.com (jay graves) Date: Thu, 21 Jun 2007 15:41:36 -0000 Subject: newbie question: parsing street name from address In-Reply-To: <1182433644.485185.197690@w5g2000hsg.googlegroups.com> References: <1182433644.485185.197690@w5g2000hsg.googlegroups.com> Message-ID: <1182440496.238200.310900@n2g2000hse.googlegroups.com> On Jun 21, 8:47 am, cjl wrote: > I would like to be able to extract the name of the street from the > addresses in my data, however they vary significantly. Here a some > examples: > > 25 Main St > 2500 14th St > 12 Bennet Pkwy > Pearl St > Bennet Rd and Main st > 19th St > > As you can see, sometimes I have the house number, and sometimes I do > not. Sometimes the street name is a number. Sometimes I simply have > the names of intersecting streets. > > How might I approach this complex parsing problem? In the past, I used the data cleansing routines from Febrl to do this with some success. http://www.google.com/search?q=febrl HTH. ... Jay Graves From cgwalters at gmail.com Sun Jun 3 18:07:52 2007 From: cgwalters at gmail.com (cgwalters at gmail.com) Date: Sun, 03 Jun 2007 22:07:52 -0000 Subject: another thread on Python threading In-Reply-To: References: <1180906374.041535.296410@k79g2000hse.googlegroups.com> Message-ID: <1180908472.253193.22870@k79g2000hse.googlegroups.com> On Jun 3, 5:52 pm, Steve Howell wrote: > The pitfall here is that to reduce code duplication, > you might initialize certain variables in a method > called by __init__, because your object might want to > return to its initial state. This is a good point. I was thinking that this analysis would occur during module loading; i.e. it would be the equivalent of Java's classloading. What if the startup code analysis just extended to methods called during __init__? That seems like a relatively straightforward extension. Remember we aren't actually *executing* the startup code in my proposal; we are just analyzing it for all possible execution paths which cause a member variable assignment. From stefan.behnel-n05pAM at web.de Mon Jun 25 16:25:58 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Mon, 25 Jun 2007 22:25:58 +0200 Subject: Which XML? In-Reply-To: <1182774321.157937.289700@n2g2000hse.googlegroups.com> References: <1182774321.157937.289700@n2g2000hse.googlegroups.com> Message-ID: <468024D6.3010109@web.de> Paul Boddie wrote: > On 25 Jun, 02:04, Bruno Barberi Gnecco > wrote: >> I've found a lot of XML libraries for Python. Any advices on which >> one to use (or *not* to use)? My requirements are: support for XPath, >> stability (a must, segfaults are not an option), with DOM API and good >> performance desirable. > > You might be interested in libxml2dom: > > http://www.python.org/pypi/libxml2dom > > It uses libxml2 under the covers, meaning that it has good performance > and supports XPath, but I can't always guarantee stability: libxml2 > can get quite upset in some situations, but I've worked fairly hard to > avoid triggering them. True, that's actually pretty hard work. lxml also does loads of stuff under the hood to keep libxml2 happy. But that's what a good Python wrapper is for: keep the people who use it from worrying about segfaults and memory management and let them concentrate on their own problems. It's more important to make the users happy than the libs. :) Stefan From gagsl-py2 at yahoo.com.ar Mon Jun 11 15:30:58 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 11 Jun 2007 16:30:58 -0300 Subject: Accessing global namespace from module References: <1181577768.728377.262720@m36g2000hse.googlegroups.com> <1181583469.562064.29440@p77g2000hsh.googlegroups.com> <1181585938.144294.119790@w5g2000hsg.googlegroups.com> Message-ID: En Mon, 11 Jun 2007 15:18:58 -0300, reubendb escribi?: > The problem is I don't define the functions AddPlot() and DrawPlots(). > It's built into the python interpreter of the CLI version of the > program I mentioned, and they are defined on the main script. I load > the main script using something like "software -cli -s > mainscript.py". > In the mainscript.py I import myModule, but of course myModule does > not have access to the functions defined in the global namespace of > mainscript.py. Don't you have some import statements at the top of mainscript.py that are responsible for bringing AddPlot and DrawPlots into the current namespace? Import the same things in your second module. -- Gabriel Genellina From sk8in_zombi at yahoo.com.au Fri Jun 8 15:58:41 2007 From: sk8in_zombi at yahoo.com.au (Mr SZ) Date: Sat, 9 Jun 2007 05:58:41 +1000 (EST) Subject: How to use TLS lite Message-ID: <114037.93309.qm@web54507.mail.re2.yahoo.com> I'm using tls lite to send mail using gmail's smtp.This is what I've done: from tlslite.api import * import tlslite.integration.SMTP_TLS connection= tlslite.integration.SMTP_TLS.SMTP_TLS('smtp.gmail.com',587) connection.set_debuglevel(1) msg = "Subject:Testing \n Hello" connection.starttls('emailid at gmail.com','password') connection.sendmail("from at gmail.com","to at gmail.com",msg) In return this is what I get: wiki at wiki-desktop:~/Desktop$ python smtp2.py send: 'STARTTLS\r\n' reply: '503 5.5.1 EHLO/HELO first m75sm2193378wrm\r\n' reply: retcode (503); Msg: 5.5.1 EHLO/HELO first m75sm2193378wrm send: 'ehlo [127.0.1.1]\r\n' reply: '250-mx.google.com at your service, [59.93.118.190]\r\n' reply: '250-SIZE 28311552\r\n' reply: '250-8BITMIME\r\n' reply: '250-STARTTLS\r\n' reply: '250 ENHANCEDSTATUSCODES\r\n' reply: retcode (250); Msg: mx.google.com at your service, [59.93.118.190] SIZE 28311552 8BITMIME STARTTLS ENHANCEDSTATUSCODES send: 'mail FROM: size=23\r\n' reply: '530 5.7.0 Must issue a STARTTLS command first m75sm2193378wrm\r\n' reply: retcode (530); Msg: 5.7.0 Must issue a STARTTLS command first m75sm2193378wrm send: 'rset\r\n' reply: '250 2.1.0 Flushed m75sm2193378wrm\r\n' reply: retcode (250); Msg: 2.1.0 Flushed m75sm2193378wrm Traceback (most recent call last): File "smtp2.py", line 7, in connection.sendmail("email at gmail.com","to at gmail.com",msg) File "/usr/lib/python2.5/smtplib.py", line 684, in sendmail raise SMTPSenderRefused(code, resp, from_addr) smtplib.SMTPSenderRefused: (530, '5.7.0 Must issue a STARTTLS command first m75sm2193378wrm', 'email at gmail.com') Where am I going wrong? " life isn't heavy enough,it flies away and floats far above action" --------------------------------- How would you spend $50,000 to create a more sustainable environment in Australia? Go to Yahoo!7 Answers and share your idea. -------------- next part -------------- An HTML attachment was scrubbed... URL: From anonymisiert85 at mymail.ch Fri Jun 22 15:15:49 2007 From: anonymisiert85 at mymail.ch (anonymisiert85 at mymail.ch) Date: Fri, 22 Jun 2007 12:15:49 -0700 Subject: EMBEDDING > Run Python & Run C Function In-Reply-To: References: <1182524980.596661.228390@c77g2000hse.googlegroups.com> Message-ID: <1182539749.316281.134010@x35g2000prf.googlegroups.com> i readed this before but not understand it - but now - the second time it works THANK YOU!!!!!! From MrJean1 at gmail.com Fri Jun 15 13:41:45 2007 From: MrJean1 at gmail.com (MrJean1) Date: Fri, 15 Jun 2007 17:41:45 -0000 Subject: Subprocess Not Working on Solaris In-Reply-To: <1181919646.102465.77490@g4g2000hsf.googlegroups.com> References: <1181919646.102465.77490@g4g2000hsf.googlegroups.com> Message-ID: <1181929305.090770.311370@o11g2000prd.googlegroups.com> FWIIW, on my Solaris 10 (Opteron) machine, there are no import subprocess errors, not with Python 2.4.3 nor with Python 2.5. /Jean Brouwers PS) Python 2.4.3 is the ActivePython Solaris build 11 from ActivState. Python 2.5 was built from source using SUN compilers, not GNU. There is an ActivePython Solaris build for 2.5.1 but I have not tried that one yet. See On Jun 15, 8:00 am, Lee wrote: > Has anyone ran into this problem? I've done extensive googling and > research and I cannot seem to find the answer. > > I downloaded the source for 2.5.1 from python.org compiled and > installed it on a Solaris box, > > uname -a returns > > SunOS unicom5 5.8 Generic_117350-26 sun4u sparc SUNW,Sun-Fire-V210 > > When I launch the python interpreter, I try the following: > > " > Python 2.5.1 (r251:54863, Jun 13 2007, 13:40:52) > [GCC 3.2.3] on sunos5 > Type "help", "copyright", "credits" or "license" for more information.>>> import subprocess > > Traceback (most recent call last): > File "", line 1, in > File "/usr/local/lib/python2.5/subprocess.py", line 401, in > import select > ImportError: No module named select > " > > The subprocess module works just fine on a BSD box I have and after > doing a 'find' I notice there is a select.so module. This does not > exist on the Solaris box, only subprocess exists. Within subprocess.py > on the Solaris box, exists the following: > > " > else: > import select > import errno > import fcntl > import pickle > " > > Any ideas? I'd like to get the subprocess module working... > > -Lee From evan at yelp.com Thu Jun 21 22:47:48 2007 From: evan at yelp.com (Evan Klitzke) Date: Thu, 21 Jun 2007 19:47:48 -0700 Subject: Error while installing Python2.5.1 In-Reply-To: <1182479927.467515.216720@g37g2000prf.googlegroups.com> References: <1182413023.924197.302390@o11g2000prd.googlegroups.com> <1182479927.467515.216720@g37g2000prf.googlegroups.com> Message-ID: On 6/21/07, zaperaj at gmail.com wrote: > I dont understand.... What are my distribution repositories? AFAIK there aren't any repositories for Red Hat 9. But there should be a gcc rpm on your installation media. -- Evan Klitzke From steven.bethard at gmail.com Wed Jun 13 11:36:31 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 13 Jun 2007 09:36:31 -0600 Subject: SimplePrograms challenge In-Reply-To: <1181735763.199492.164760@q19g2000prn.googlegroups.com> References: <466F9329.2020306@gmail.com> <1181735763.199492.164760@q19g2000prn.googlegroups.com> Message-ID: Rob Wolfe wrote: > Steve Howell wrote: > >> I suggested earlier that maybe we post multiple >> solutions. That makes me a little nervous, to the >> extent that it shows that the Python community has a >> hard time coming to consensus on tools sometimes. > > We agree that BeautifulSoup is the best for parsing HTML. :) > >> This is not a completely unfair knock on Python, >> although I think the reason multiple solutions tend to >> emerge for this type of thing is precisely due to the >> simplicity and power of the language itself. >> >> So I don't know. What about trying to agree on an XML >> parsing example instead? >> >> Thoughts? > > I vote for example with ElementTree (without xpath) > with a mention of using ElementSoup for invalid HTML. Sounds good to me. Maybe something like:: import xml.etree.ElementTree as etree dinner_recipe = ''' 24slicesbaguette 2+tbspolive_oil 1cuptomatoes 1-2tbspgarlic 1/2cupParmesan 1jarpesto ''' pantry = set(['olive oil', 'pesto']) tree = etree.fromstring(dinner_recipe) for item_elem in tree.getiterator('item'): if item_elem.text not in pantry: print item_elem.text Though I wouldn't know where to put the ElementSoup link in this one... STeVe From cousinstanley at hotmail.com Sat Jun 16 11:25:39 2007 From: cousinstanley at hotmail.com (Cousin Stanley) Date: Sat, 16 Jun 2007 10:25:39 -0500 Subject: Python's "only one way to do it" philosophy isn't good? References: <1181368143.874341.273140@r19g2000prf.googlegroups.com> <1hzrsp4.7vjuav1aegg0tN%aleax@mac.com> <1hzsdrr.wxcx771jwicv5N%aleax@mac.com> Message-ID: <1182007539_10897@sp12lax.superfeed.net> > Steven D'Aprano wrote: > ... >> > perception that, at their roots, Scheme, C and Python share one >> > philosophical underpinning (one that's extremely rare among programming >> > languages as a whole) -- an appreciation of SIMPLICITY AND UNIFORMITY as >> > language characteristics. >> >> Out of curiosity, what do you consider some of the worst offenders as far >> as overly complex and inconsistent languages go, and why? > > I think the Original Sin in that regard was PL/I: it tried to have all > the "cool features" of the three widespread languages of the time, > Cobol, Algol _and_ Fortran (and then some), because it aimed to replace > all three and become the "one programming language". As a result, it > tended to have two or more ways to perform any given task, typically > inspired by some of the existing languages, often with the addition of > new ones made out of whole cloth. > > PL/I (mostly in various subset and "extended subset" forms) was widely > used in the implementation of Multics, and I believe that the statement > in the "Spirit of C" was at least partly inspired by that experience > (just like "Unix" was originally intended as a pun on "Multics" > underscoring the drastically simpler philosophy of the new OS). Cousin Alex .... With regards to PL/I a phrase from an old ( 1969 ) song named "The Night They Drove Old Dixie Down" comes to mind .... Ya take what you need and ya leave the rest .... I really liked programming in pl/1 and did a little over 3 years of Multics time in San Juan, Puerto Rico .... http://multicians.org/site-prha.html -- Stanley C. Kitching Human Being Phoenix, Arizona ----== Posted via Newsfeeds.Com - Unlimited-Unrestricted-Secure Usenet News==---- http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ Newsgroups ----= East and West-Coast Server Farms - Total Privacy via Encryption =---- From borud-news at borud.no Fri Jun 22 11:30:53 2007 From: borud-news at borud.no (Bjorn Borud) Date: 22 Jun 2007 17:30:53 +0200 Subject: The Modernization of Emacs: terminology buffer and keybinding References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182272495.990807.99110@a26g2000pre.googlegroups.com> <87tzt3ihev.fsf@kobe.laptop> <1182370216.961241.6960@n60g2000hse.googlegroups.com> <85zm2ufjpb.fsf@lola.goethe.zz> <1182372592.803332.288260@u2g2000hsc.googlegroups.com> <1182373919.262388.100740@c77g2000hse.googlegroups.com> <85r6o6fhkb.fsf@lola.goethe.zz> <1182375045.626510.188170@m36g2000hse.googlegroups.com> <1182453375.531950.141460@m36g2000hse.googlegroups.com> <1182456618.763414.219080@g4g2000hsf.googlegroups.com> Message-ID: [Kaldrenon ] | | I don't think anyone can make the argument that any (past or current) | graphics-based editor is as efficient when being used to its fullest | as a text-based editor. It's basic math - it takes measurably more | time to move a hand to the mouse, move/click the mouse, and more the | hand back to the touch-typing position than it does to execute even a | moderately complex series of keystrokes. Maybe not large amounts of | time -per action-, but it doesn't take too long for it to add up if | you spend a lot of time editing. a lot of IDE's are getting quite good and you don't have to mouse around all that much. I think the main reason I stick to Emacs is because I use it for a wider range of tasks -- not just programming. also, the IDE's I've used in the past were sluggish and for some reason the font-rendering was really hard to get right (if at all). when you spend the majority of your waking hours editing text, interactive response time and "editing ergonomics" matter a lot. this reminds me that it is probably time to give IDEs another chance. it has been a couple of years since the last time I tried a couple for Java. -Bj?rn From tfb+google at tfeb.org Mon Jun 11 17:36:57 2007 From: tfb+google at tfeb.org (Tim Bradshaw) Date: Mon, 11 Jun 2007 14:36:57 -0700 Subject: The Concepts and Confusions of Prefix, Infix, Postfix and Fully Functional Notations In-Reply-To: <1181545345.788665.191690@q66g2000hsg.googlegroups.com> References: <1179936917.652372.24780@q69g2000hsb.googlegroups.com> <1180508453.226022.44230@q19g2000prn.googlegroups.com> <1181335574.107472.229370@x35g2000prf.googlegroups.com> <1181358616.792797.97720@k79g2000hse.googlegroups.com> <1181414625.121073.203940@g4g2000hsf.googlegroups.com> <0uHai.176367$nh4.13819@newsfe20.lga> <1181448558.120521.63250@g4g2000hsf.googlegroups.com> <0G_ai.1970$xg4.809@trnddc08> <1181525392.369255.138460@h2g2000hsg.googlegroups.com> <1181545345.788665.191690@q66g2000hsg.googlegroups.com> Message-ID: <1181597817.867161.10510@h2g2000hsg.googlegroups.com> On Jun 11, 8:02 am, Twisted wrote: > On Jun 11, 2:42 am, Joachim Durchholz wrote: > > > It is possible to write maintainable Perl. > > Interesting (spoken in the tone of someone hearing about a purported > sighting of Bigfoot, or maybe a UFO). > I think it's just obvious that this is the case. What would *stop* you writing maintainable Perl? From bruno.42.desthuilliers at wtf.websiteburo.oops.com Fri Jun 29 08:53:08 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Fri, 29 Jun 2007 14:53:08 +0200 Subject: It is not possible to create a recursive function over a pyGTK treeStore In-Reply-To: <1183116619.785972.175720@k29g2000hsd.googlegroups.com> References: <1183116619.785972.175720@k29g2000hsd.googlegroups.com> Message-ID: <4685009b$0$23149$426a34cc@news.free.fr> sebastien.abeille at gmail.com a ?crit : > Hello, > > I would like to create a minimalist file browser using pyGTK. > > Having read lot of tutorials, it seems to me that that in my case, the > best solution is > to have a gtk.TreeStore containing all the files and folders so that > it would map the > file system hierarchy. > > I wrote a recursive function that would go through the file system > tree. > > My problem is that a sub-node of a gtk.TreeStore is not a > gtk.TreeStore, but > a gtk.TreeIter. And gtk.treeter has almost no functions I would be > able to use (like "append") > Therefore I can not explore the whole file system. > > Do you have another way so that I would be able to put all the file > system hierarchy > into a gtk.TreeStore? Sorry, no anwser to that - I don't do much GUI programming. But asking on GTK mailing-list may be a good idea. > I was quite happy with my recursive solution ... A couple of comments on the code: > #!/usr/bin/env python > import pygtk > pygtk.require('2.0') > import gtk, gobject, os > > > prefdir="/tmp/a" > > class InfoModele: Do yourself (and the world) a favour: use new-styles classes. And while we're at it, be consistant wrt/ naming: class InfoModel(object): > def matchPathTreetoModelTree(self, path, treeStoreNode): You're of course free to use mixedCase, but unless this is a project-specific (or workplace-specific) convention, it might be better to stick to pep08 (all_lower_with_underscores). But if you choose mixedCase, at least be consistant (ie : self.tree_store => self.treeStore) > files = [f for f in os.listdir(path) if f[0] <> '.'] could also use str.startswith here: files = [f for f in os.listdir(path) \ if not f.startswith('.')] But I don't see the point of this listcomp when you could filter out special names in the for loop. > for i in range(len(files)): Coming from a C-like language ?-) The for loop in Python is much smarter than this. You don't have to use an explicit indexing, you can just iterate over the sequence, ie, instead of: for i in range(len(files)): the_file = files[i] do_something_with(the_file) You can do: for the_file in files: do_something_with(the_file) NB : if you need the index for any other reason, you can use enumerate(seq): for i, the_file in enumerate(files): print >> sys.stderr, "file #%s" % i do_something_with(the_file) > if os.path.isfile(path+'/'+files[i]): > print path+'/'+files[i]+" is a file" > treeStoreNode.append( None, (path+'/'+files[i], None) ) My... 1/: use os.path.join() 2/: avoid recomputing the same value thrice or more, especially if within a loop 3/ (optional, but good to know): within loops, make the often used methods locals - this will save *a lot* of lookup time (since Python is highly dynamic, the compiler cannot optimize much here). 4/ stdout is for normal program outputs. Error messages, debug informations et al should go to stderr > if os.path.isdir(path+'/'+files[i]): Note that you should'nt do this test if the previous succeeded, since both are exclusive. IOW, use a elif. > print path+'/'+files[i]+" is a directory" > mother = self.tree_store.append(None, (path+'/'+files[i], None)) You certainly have an error here. If you're already in a subdirectory, you don't want to create the node on the root but on the parent's directory node - IOW, dont use self.tree_store, but treeStoreNode. Which allow to further simplify the code (cf below) > self.matchPathTreetoModelTree(path+'/'+files[i], mother) > > def __init__(self): > self.tree_store = gtk.TreeStore( gobject.TYPE_STRING, > gobject.TYPE_STRING) > path=prefdir This should be an argument of the initializer > self.matchPathTreetoModelTree(prefdir, self.tree_store) (snip) Suggestion: class InfoModel(object): def __init__(self, path): self.basepath = path self.treeStore = gtk.TreeStore( gobject.TYPE_STRING, gobject.TYPE_STRING ) self.matchPathTreetoModelTree(path, self.treeStore) def matchPathTreetoModelTree(self, path, treeStoreNode): isdir = os.path.isdir join = os.path.join append= treeStoreNode.append recurse = self.matchPathTreetoModelTree filenames = os.listdir(path) for filename in filenames: if filename.startswith('.'): continue filepath = join(path, filename) # tracing for debug - assuming this will disappear # before going to prod, it's ok to repeat the call # to isdir() here print >> sys.stderr, "%s is a %s" \ % (filepath, ('file', 'dir')[isdir(filepath)]) # nb: you may want to filter out non-regular files # like devices, sockects etc here newnode = append(None, (filepath, None)) if isdir(filepath): recurse(filepath, newnode) HTH From cbmeeks at gmail.com Fri Jun 1 13:34:38 2007 From: cbmeeks at gmail.com (cbmeeks) Date: Fri, 01 Jun 2007 17:34:38 -0000 Subject: Resize image NO PIL!! In-Reply-To: References: <1180406398.615904.22230@g4g2000hsf.googlegroups.com> Message-ID: <1180719278.858815.27630@g4g2000hsf.googlegroups.com> Thanks for the suggestions. I checked out webfaction.com and they looked nice. Might move from Pair over there. I think what I am going to do is splurge and go with Amazon's EC2 ($72/ month). But it's root level access so I can do anything. Last night I got a Python daemon running that monitored the MySQLdb every 10 seconds (just for testing) and it would process "thumb_jobs" by calling PIL. Worked nicely. I will have to experiment with tight batch control (as in, not processing the same pic more than once) and threading. cbmeeks http://www.signaldev.com On May 30, 5:50 pm, a... at pythoncraft.com (Aahz) wrote: > In article <1180406398.615904.22... at g4g2000hsf.googlegroups.com>, > > cbmeeks wrote: > > >My stupid host (pair.com) doesn't have PIL installed and I'm too much > >of a stupid newbie to figure out how to get it to work with them > >(access denied while installing it, of course). > > >Also, they don't have any python interface setup for GD. > > >Anyway, I don't know what my options are. I'm thinking: > > >1) Find another host with mod_python, PIL, and other Python goodies > > webfaction.com -- I almost went with pair.com because they're reliable, > but I decided to choose a provider that supports Python. > -- > Aahz (a... at pythoncraft.com) <*> http://www.pythoncraft.com/ > > "as long as we like the same operating system, things are cool." --piranha From deets at nospam.web.de Mon Jun 11 11:19:38 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 11 Jun 2007 17:19:38 +0200 Subject: skip next item in list References: <1181573389.186279.108590@g37g2000prf.googlegroups.com> Message-ID: <5d57gaF32l00gU1@mid.uni-berlin.de> ahlongxp wrote: > list=('a','d','c','d') > for a in list: > if a=='a' : > #skip the letter affer 'a' > > what am I supposed to do? First - don't use list as name, as it is a builtins-name and shadowing is likely to produce errors at some point. list_iterator = iter(('a','d','c','d')) for a in list_iterator: if a == 'a': list_iterator.next() ... should do the trick. Diez From xavier_berard at hotmail.com Fri Jun 8 10:07:17 2007 From: xavier_berard at hotmail.com (=?iso-8859-1?q?Xavier_B=E9rard?=) Date: Fri, 08 Jun 2007 07:07:17 -0700 Subject: Tkinter custom drawing In-Reply-To: References: <1181224696.484887.29980@q66g2000hsg.googlegroups.com> Message-ID: <1181311637.010300.43380@p77g2000hsh.googlegroups.com> > from Tkinter import Invisiblecanvas ? The whole web never mentions this Invisiblecanvas. Do you have anything alike to share ? ;) Xavier From dwahler at gmail.com Wed Jun 20 16:56:30 2007 From: dwahler at gmail.com (David Wahler) Date: Wed, 20 Jun 2007 21:56:30 +0100 Subject: need help with re module In-Reply-To: References: <46795CBA.9040807@gmail.com> Message-ID: On 6/20/07, Gabriel Genellina wrote: > En Wed, 20 Jun 2007 13:58:34 -0300, linuxprog > escribi?: > > > i have that string "helloworldok" and i want to > > extract all the text , without html tags , the result should be some > > thing like that : helloworldok > > > > i have tried that : > > > > from re import findall > > > > chaine = """helloworldok""" > > > > print findall('[a-zA-z][^(<.*>)].+?[a-zA-Z]',chaine) > > >>> ['html', 'hell', 'worl', 'anyt', 'ag>o'] > > > > the result is not correct ! what would be the correct regex to use ? > > You can't use a regular expression for this task (no matter how > complicated you write it). [snip] I agree that BeautifulSoup is probably the best tool for the job, but this doesn't sound right to me. Since the OP doesn't care about tags being properly nested, I don't see why a regex (albeit a tricky one) wouldn't work. For example: regex = re.compile(r''' <[^!] # beginning of normal tag ([^'">]* # unquoted text... |'[^']*' # or single-quoted text... |"[^"]*")* # or double-quoted text > # end of tag | contains table definitions etc. Manager.py from Registry import * class Manager(object): def __init__(self, model, table=None): self.model = model self.table = table def get(self, slice): pass def all(self): print "1" mapper(self.model, interpro_table) print "2" session = create_session() print "3" query = session.query(self.model) print "4" return query.select() Models.py from Manager import * class ModelBase(type): def __new__(cls, name, bases, dict): print cls setattr(cls, 'objects', Manager(cls)) return type.__new__(cls, name, bases, dict) class Model(object): __metaclass__=ModelBase class InterPro(Model): _tableName = interpro_table def __init__(self, interpro_ac): self.interpro_ac = interpro_ac def __str__(self): return "InterPro: %s" %(self.interpro_ac) def __repr__(self): return "InterPro: %s" %(self.interpro_ac) if __name__=='__main__': a = Manager(InterPro) print a print a.all() --> this prints out all of the objects in the database i = InterPro('IPR014697') print InterPro.objects print InterPro.objects.all() --> this fails and produces the exception. Traceback (most recent call last): File "Model.py ", line 28, in ? print InterPro.objects.all() File "/home/skeg/workspace/test/src/Manager.py", line 17, in all return query.select() File "/usr/lib/python2.4/site-packages/sqlalchemy/orm/query.py", line 247, in select return self.select_whereclause(whereclause=arg, **kwargs) File "/usr/lib/python2.4/site-packages/sqlalchemy/orm/query.py", line 252, in select_whereclause return self._select_statement(statement, params=params) File "/usr/lib/python2.4/site-packages/sqlalchemy/orm/query.py", line 378, in _select_statement return self.execute(statement, params=params, **kwargs) File "/usr/lib/python2.4/site-packages/sqlalchemy/orm/query.py", line 310, in execute return self.instances(result, **kwargs) File "/usr/lib/python2.4/site-packages/sqlalchemy/orm/query.py", line 329, in instances self.mapper._instance(context, row, result) File "/usr/lib/python2.4/site-packages/sqlalchemy/orm/mapper.py", line 1213, in _instance instance = self._create_instance(context.session) File "/usr/lib/python2.4/site-packages/sqlalchemy/orm/mapper.py", line 1234, in _create_instance obj = self.class_.__new__(self.class_) TypeError: __new__() takes exactly 4 arguments (1 given) Does anyone know what the problem is? Is it the way I ve programmed this using metaclasses or is it sqlalchemy and the way in instantiates objects or even both? Many Thanks in advance, From apatheticagnostic at gmail.com Sun Jun 3 00:55:20 2007 From: apatheticagnostic at gmail.com (kaens) Date: Sun, 3 Jun 2007 00:55:20 -0400 Subject: int vs long In-Reply-To: <7xr6otiv4l.fsf@ruckus.brouhaha.com> References: <1180839659.196587.194200@p77g2000hsh.googlegroups.com> <7xr6otiv4l.fsf@ruckus.brouhaha.com> Message-ID: <163f0ce20706022155y385141f6v4db753d7958b1158@mail.gmail.com> On 02 Jun 2007 20:18:02 -0700, Paul Rubin <"http://phr.cx"@nospam.invalid> wrote: > Dan Bishop writes: > > Note that recent versions of Python automatically promote the results > > of integer arithmetic to long if necessary, so the distinction is less > > relevant than it used to be. > > Note however that even in recent versions, there are still parts of > Python that get stuck at sys.maxint, for example the enumerate function. > -- > http://mail.python.org/mailman/listinfo/python-list > I didn't know that - I'll keep it in mind though. I can imagine that causing some pretty nasty annoyances if you ran into it unexpectedly From rajenpn at gmail.com Sat Jun 16 08:35:23 2007 From: rajenpn at gmail.com (Rajendran) Date: Sat, 16 Jun 2007 05:35:23 -0700 Subject: Database Access using pyodbc. I've a problem Message-ID: <1181997323.384882.149020@i13g2000prf.googlegroups.com> Hi all, I've installed pyodbc module to access my database (MS Access). I've setup a User level DSN to the database.mdb file. When I run my python code in the command prompt it is retrieving the database contents and displaying it (HTML output). But when I run that python from webserver (http://localhost/cgi-bin/ database.py) there comes an entry in the error log of Apache server that says: [Sat Jun 16 17:55:57 2007] [error] [client 127.0.0.1] Premature end of script headers: database.py [Sat Jun 16 17:55:57 2007] [error] [client 127.0.0.1] Traceback (most recent call last):\r [Sat Jun 16 17:55:57 2007] [error] [client 127.0.0.1] File "C:/ Apache Software Foundation/Apache2.2/cgi-bin/database.py", line 10, in \r [Sat Jun 16 17:55:57 2007] [error] [client 127.0.0.1] cnxn = pyodbc.connect('DSN=Emp')\r [Sat Jun 16 17:55:57 2007] [error] [client 127.0.0.1] pyodbc.Error: ('HY000', "[HY000] [Microsoft][ODBC Microsoft Access Driver] The Microsoft Jet database engine cannot open the file '(unknown)'. It is already opened exclusively by another user, or you need permission to view its data. (-1032); [HY000] [Microsoft][ODBC Microsoft Access Driver] The Microsoft Jet database engine cannot open the file '(unknown)'. It is already opened exclusively by another user, or you need permission to view its data. (-1032)")\r Even though the MS Access file is closed. I've no administrator rights and I've installed all these as a normal windows user. I don't have problem when I write a similar kind of code in PHP. What could be the reason? Is it because I don't have administrator rights? or something else? Please help me out. From no_spam at no_spam.com Mon Jun 25 21:07:46 2007 From: no_spam at no_spam.com (James Alan Farrell) Date: Tue, 26 Jun 2007 01:07:46 GMT Subject: Looking for an interpreter that does not request internet access Message-ID: Hello, I recently installed new anti-virus software and was surprised the next time I brought up IDLE, that it was accessing the internet. I dislike software accessing the internet without telling me about it, especially because of my slow dial up connection (there is no option where I live), but also because I feel it unsafe. Can anyone recommend an interpreter that does not access the internet when it starts (or when it is running, unless I specifically write a program that causes it to do so, so as a browser)? James Alan Farrell From http Mon Jun 25 10:17:30 2007 From: http (Paul Rubin) Date: 25 Jun 2007 07:17:30 -0700 Subject: comparing two lists and returning "position" References: <1182481876.028589.71710@x35g2000prf.googlegroups.com> <7xvedg4n2d.fsf@ruckus.brouhaha.com> <467b624e$0$16271$c30e37c6@lon-reader.news.telstra.net> <1182493019.795629.108860@w5g2000hsg.googlegroups.com> <1182534010.884992.119690@u2g2000hsc.googlegroups.com> <467f8dab$0$67427$c30e37c6@lon-reader.news.telstra.net> Message-ID: <7x1wg0p18l.fsf@ruckus.brouhaha.com> Charles Sanders writes: > from itertools import izip, count > d = dict(izip(l2,count())) > pos = [ d[i] for i in l1 ] > > or the more memory intensive > > d = dict(zip(l2,range(len(l2)))) > pos = [ d[i] for i in l1 ] If you're itertools-phobic you could alternatively write d = dict((x,i) for i,x in enumerate(l2)) pos = [ d[i] for i in l1 ] dict access and update is supposed to take approximately constant time, btw. They are implemented as hash tables. From paul at boddie.org.uk Wed Jun 13 07:26:46 2007 From: paul at boddie.org.uk (Paul Boddie) Date: Wed, 13 Jun 2007 04:26:46 -0700 Subject: Why can't easy_install Django In-Reply-To: <1181697717.146174.32240@j4g2000prf.googlegroups.com> References: <1181697717.146174.32240@j4g2000prf.googlegroups.com> Message-ID: <1181734006.977256.87570@q19g2000prn.googlegroups.com> On 13 Jun, 03:21, kernel1983 wrote: > I look it up in PyPI [...] > Django is a big project. Why no one maintain this? Did the guy lost > his password? Who knows? But then, if you're running a GNU/Linux distribution like Debian, it's quite possible to use a system package, anyway: http://packages.debian.org/python-django http://packages.ubuntu.com/python-django Paul From martin at see.sig.for.address Thu Jun 21 14:26:00 2007 From: martin at see.sig.for.address (Martin Gregorie) Date: Thu, 21 Jun 2007 19:26:00 +0100 Subject: The Modernization of Emacs In-Reply-To: References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182344981.372713.298580@w5g2000hsg.googlegroups.com> <1182370884.853838.321440@c77g2000hse.googlegroups.com> <2jpok4-ajt.ln1@zoogz.gregorie.org> Message-ID: Bjorn Borud wrote: > [Martin Gregorie ] > | > | As for documentation, lets look at vi. Not a great editor, but every > | *nix variation has it installed and any fool can learn to use it in > | about 2 hours flat and it does at least have good pattern matching. > > there's also the "info" system in Emacs, which not only covers Emacs > itself, but usually also a lot of documentation available for Emacs > extensions and other programs. again, this predates a lot of things > that people are used to today, so just because it seems (and sometimes > is) a bit more fiddly, it must necessarily be inferior. > I thought it might be in "info", like most GNUish things but I couldn't check because I don't have it installed. > for instance, Linux has come a long way in addressing the needs of > desktop users, yet some people refuse to use Linux because it doesn't > behave *exactly* like Windows (as if that was a worthwhile goal) and > they are too lazy or don't think they can manage, to learn a new > system. > Yep, and the same people think a command line is to be avoided at all costs. "I mean, its so /last century/ and you can't do anything useful with it anyway". Obligatory OT comment: right now I have two xterm sessions open with which I've been writing a Swing/JDBC app using nowt but a bash shell, cvs, microEmacs and (of course) J2SE. I don't need no steenking IDE. -- martin@ | Martin Gregorie gregorie. | Essex, UK org | From pjb at informatimago.com Fri Jun 22 18:15:50 2007 From: pjb at informatimago.com (Pascal Bourguignon) Date: Sat, 23 Jun 2007 00:15:50 +0200 Subject: The Modernization of Emacs: terminology buffer and keybinding References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182272495.990807.99110@a26g2000pre.googlegroups.com> <87tzt3ihev.fsf@kobe.laptop> <1182370216.961241.6960@n60g2000hse.googlegroups.com> <85zm2ufjpb.fsf@lola.goethe.zz> <1182372592.803332.288260@u2g2000hsc.googlegroups.com> <5dtk4tF34jrimU1@mid.dfncis.de> <1182375388.814275.227380@n2g2000hse.googlegroups.com> <87645h73ei.fsf@W0053328.mgh.harvard.edu> <1182548563.561252.82480@i13g2000prf.googlegroups.com> Message-ID: <87sl8jiqjt.fsf@thalassa.lan.informatimago.com> Twisted writes: > The Windows world may have a fair bit to learn from the Unix world > about software reliability and QA, and also about better supporting > task automation. But not about user interface design for when tasks > are done manually. That's the point. Manual tasks have nothing to do in computers. Computers are there to automatize tasks, not to give you more manual work. -- __Pascal Bourguignon__ http://www.informatimago.com/ NOTE: The most fundamental particles in this product are held together by a "gluing" force about which little is currently known and whose adhesive power can therefore not be permanently guaranteed. From kf9150 at gmail.com Fri Jun 22 03:34:29 2007 From: kf9150 at gmail.com (kf9150 at gmail.com) Date: Fri, 22 Jun 2007 07:34:29 -0000 Subject: sqlite newbie questions In-Reply-To: <1182462847.490538.252270@w5g2000hsg.googlegroups.com> References: <1182453849.251898.127630@d30g2000prg.googlegroups.com> <1182462847.490538.252270@w5g2000hsg.googlegroups.com> Message-ID: <1182497669.181645.274900@q19g2000prn.googlegroups.com> On Jun 21, 11:54 am, Luis M. Gonz?lez wrote: > You need to learn sql if you want to deal with databases. > Don't worry, it's very easy, and here is a very good resource to get > you up and running in a few minutes:http://www.sqlcourse.com > > Good luck! > Luis Thanks Luis, will check out the site you recommended. From sjmachin at lexicon.net Mon Jun 11 08:37:49 2007 From: sjmachin at lexicon.net (John Machin) Date: Mon, 11 Jun 2007 05:37:49 -0700 Subject: ANN: xlrd 0.6.1 final is now available Message-ID: The final release of version 0.6.1 of xlrd is now available from http://www.lexicon.net/sjmachin/xlrd.htm and from the Cheeseshop (http://cheeseshop.python.org/pypi/xlrd). What is xlrd? It's a small (download approx 0.1 Mb) pure-Python library for extracting information from Microsoft Excel (tm) files, anywhere Python 2.1 or later will run -- no need for Excel itself, nor COM, nor even Windows. Further info: follow the links on the home page. This major release incorporates the functionality of 0.6.0 which was not released independently for various reasons including the need to push ahead with the 0.6.1 functionality. New in 0.6.0: facility to access named cell ranges and named constants (Excel UI: Insert/Name/Define). New in 0.6.1: extracts formatting information for cells (font, "number format", background, border, alignment and protection) and rows/ columns (height/width etc). To save memory and time for those who don't need it, this information is extracted only if formatting_info=1 is supplied to the open_workbook() function. The cell records BLANK and MULBLANKS which contain no data, only formatting information, will continue to be ignored in the default (no formatting info) case. There have been several changes made to handle anomalous files (written by 3rd party software) which Excel will open without complaint, but failed with xlrd, usually because an assertion fails or xlrd deliberately raises an exception. Refer to HISTORY.html for details. These have been changed to accept the anomaly either silently or with a NOTE message or a WARNING message, as appropriate. Many thanks are due to Simplistix Ltd (http://www.simplistix.co.uk). for funding the new functionality in 0.6.1. Since 0.6.1a4 was released in February, only one bug-fix and some tidying up have been done -- see HISTORY.html for details. Feedback: general discussion on the python-excel newsgroup (sign up at http://groups.google.com.au/group/python-excel?lnk=li&hl=en) or mailto: sjmac... at lexicon.net preferably with [xlrd] as part of the message subject. Cheers, John From hosam030 at gmail.com Sun Jun 17 06:20:58 2007 From: hosam030 at gmail.com (asm) Date: Sun, 17 Jun 2007 03:20:58 -0700 Subject: very important for your life... Message-ID: <1182075658.779709.59760@k79g2000hse.googlegroups.com> Hi there ... Thank you for reading this message . Did you here about Islam? I mean the real Islam... Do you have some questions in your religion and you don't have the answers for them? Do you know that you have to condemns in Islam? Ok... just visit these sites, read and download any thing you want for free and I wish that you will have a good time with the sites below: http://www.islamhouse.com http://www.islam-qa.com/index.php?ln=eng http://www.islamtoday.net/english http://www.islam-guide.com http://www.islamhouse.com/library/?p...eb5324d19c1609 You can read about prophet Mohammad in this site: http://www.islamway.com/mohammad And: http://www.islamhouse.com/en/modules...&bookno=378 7 Also you can see this wonderful site : http://www.islamawareness.net/Science/ If you have other questions you can send them to : rabwahoffice at yahoo.com or rabwah at www.com Or you can ask in this site: http://www.en.islamhouse.com/modules.php?name=Feedback And if you want to read more and more see these sites: http://www.ahmed-deedat.co.za/frameset.asp http://www.todayislam.com http://www.beconvinced.com http://www.thetruereligion.org http://www.it-is-truth.org http://www.islamunveiled.org http://www.discoverislam.com http://www.lordswrds.com http://www.plaintruth.org http://www.sultan.org http://www.prophetmuhammed.org http://www.religionofislam.com/english/index.htm http://lordswords.com/ If you need to ask me about something just send it to my email: factislam at gmail.com ***Here I'm asking you to carefully analyze and look deeply at this religion; you shall discover new findings - even concerning yourself - and also that this religion is completely different from what is portrayed in the media and from what you have heard or read about it. So I leave you now with these links and hope you enjoy them.... I wish that you will visit the above sites and take it seriously. Thank you for your time. From python at rcn.com Thu Jun 14 23:52:37 2007 From: python at rcn.com (Raymond Hettinger) Date: Thu, 14 Jun 2007 20:52:37 -0700 Subject: inverting a dictionary of lists In-Reply-To: <1181877633.471386.196380@i38g2000prf.googlegroups.com> References: <1181877633.471386.196380@i38g2000prf.googlegroups.com> Message-ID: <1181879557.407990.197830@j4g2000prf.googlegroups.com> On Jun 14, 8:20 pm, bpo... at gmail.com wrote: > I have a very large dictionary of lists: > d = {a:[1,2], b:[2,3], c:[3]} > and i want to reverse the associativity of the integers thusly: > inverse(d) makes {1:[a], 2:[a,b], 3:[b,c]} Try using setdefault: >>> d = {'a':[1,2], 'b':[2,3], 'c':[3]} >>> r = {} >>> for k in d: for e in d[k]: r.setdefault(e, []).append(k) >>> r {1: ['a'], 2: ['a', 'b'], 3: ['c', 'b']} Raymond From gagsl-py2 at yahoo.com.ar Wed Jun 20 15:11:59 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 20 Jun 2007 16:11:59 -0300 Subject: need help with re module References: <46795CBA.9040807@gmail.com> Message-ID: En Wed, 20 Jun 2007 13:58:34 -0300, linuxprog escribi?: > i have that string "helloworldok" and i want to > extract all the text , without html tags , the result should be some > thing like that : helloworldok > > i have tried that : > > from re import findall > > chaine = """helloworldok""" > > print findall('[a-zA-z][^(<.*>)].+?[a-zA-Z]',chaine) > >>> ['html', 'hell', 'worl', 'anyt', 'ag>o'] > > the result is not correct ! what would be the correct regex to use ? You can't use a regular expression for this task (no matter how complicated you write it). Use BeautifulSoup, that can handle invalid HTML like yours: py> from BeautifulSoup import BeautifulSoup py> chaine = """helloworldok""" py> soup = BeautifulSoup(chaine) py> soup.findAll(text=True) [u'hello', u'world', u'ok'] Get it from -- Gabriel Genellina From kaldrenon at gmail.com Thu Jun 21 16:13:06 2007 From: kaldrenon at gmail.com (Kaldrenon) Date: Thu, 21 Jun 2007 20:13:06 -0000 Subject: The Modernization of Emacs: terminology buffer and keybinding In-Reply-To: <1182456618.763414.219080@g4g2000hsf.googlegroups.com> References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182272495.990807.99110@a26g2000pre.googlegroups.com> <87tzt3ihev.fsf@kobe.laptop> <1182370216.961241.6960@n60g2000hse.googlegroups.com> <85zm2ufjpb.fsf@lola.goethe.zz> <1182372592.803332.288260@u2g2000hsc.googlegroups.com> <1182373919.262388.100740@c77g2000hse.googlegroups.com> <85r6o6fhkb.fsf@lola.goethe.zz> <1182375045.626510.188170@m36g2000hse.googlegroups.com> <1182453375.531950.141460@m36g2000hse.googlegroups.com> <1182456618.763414.219080@g4g2000hsf.googlegroups.com> Message-ID: <1182456786.515889.40590@c77g2000hse.googlegroups.com> > I don't think anyone can make the argument that any (past or current) > graphics-based editor is as efficient when being used to its fullest > as a text-based editor. Clarifying - this part of the claim assumes a fairly similar feature set, naturally. From squabbit8 at gmail.com Fri Jun 29 11:44:28 2007 From: squabbit8 at gmail.com (felix seltzer) Date: Fri, 29 Jun 2007 08:44:28 -0700 Subject: Shed Skin Python-to-C++ Compiler 0.0.21, Help needed In-Reply-To: <8180ef690706290348m4418d226l482e9a36474b3697@mail.gmail.com> References: <8180ef690703310255q55572efaqc512b968504e2c1b@mail.gmail.com> <8180ef690706290348m4418d226l482e9a36474b3697@mail.gmail.com> Message-ID: does this project include support for pygtk type GUI's? On 6/29/07, Mark Dufour wrote: > > Hi all, > > I have just released version 0.0.22 of Shed Skin, an experimental > Python-to-C++ compiler. Among other things, it has the exciting new > feature of being able to generate (simple, for now) extension modules, > so it's much easier to compile parts of a program and use them (by > just importing them). Here's the complete changelog: > > -support for generating simple extension modules (linux/windows; see > README) > -dos text format fix (long overdue) > -improved detection of dynamic types (avoid hanging on them) > -improved overloading (__nonzero__, __int__, __abs__ etc.) > -add str(ing).{capitalize, capwords, swapcase, center, ato*) > -fix string.maketrans > -several other minor bug fixes > > For more details about Shed Skin and a collection of 27 programs, at a > total of about 7,000 lines, that it can compile (resulting in an > average speedup of about 39 times over CPython and 11 times over Psyco > on my computer), please visit the homepage at: > > http://mark.dufour.googlepages.com > > I could really use some help in pushing Shed Skin forward. Please try > the latest release and send in bug reports, or join the project via > the homepage. > > > Thanks, > Mark Dufour. > > > On 3/31/07, Mark Dufour wrote: > > Hi all, > > > > I have recently released version 0.0.20 and 0.0.21 of Shed Skin, an > > optimizing Python-to-C++ compiler. Shed Skin allows for translation of > > pure (unmodified), implicitly statically typed Python programs into > > optimized C++, and hence, highly optimized machine language. Besides > > many bug fixes and optimizations, these releases add the following > > changes: > > > > -support for 'bisect', 'collections.deque' and 'string.maketrans' > > -improved 'copy' support > > -support for 'try, else' construction > > -improved error checking for dynamic types > > -printing of floats is now much closer to CPython > > > > For more details about Shed Skin and a collection of 27 programs, at a > > total of about 7,000 lines, that it can compile (resulting in an > > average speedup of about 39 times over CPython and 11 times over Psyco > > on my computer), please visit the homepage at: > > > > http://mark.dufour.googlepages.com > > > > I could really use more help it pushing Shed Skin further. Simple ways > > to help out, but that can save me lots of time, are to find smallish > > code fragments that Shed Skin currently breaks on, and to help > > improve/optimize the (C++) builtins and core libraries. I'm also > > hoping someone else would like to deal with integration with CPython > > (so Shed Skin can generate extension modules, and it becomes easier to > > use 'arbitrary' external CPython modules such as 're' and 'pygame'.) > > Finally, there may be some interesting Master's thesis subjects in > > improving Shed Skin, such as transforming heap allocation into stack- > > and static preallocation, where possible, to bring performance even > > closer to manual C++. Please let me know if you are interested in > > helping out, and/or join the Shed Skin mailing list. > > > > > > Thanks! > > Mark Dufour. > > -- > > "One of my most productive days was throwing away 1000 lines of code" > > - Ken Thompson > > > > Mark Dufour. > -- > "One of my most productive days was throwing away 1000 lines of code" > - Ken Thompson > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From twisted0n3 at gmail.com Fri Jun 22 17:42:43 2007 From: twisted0n3 at gmail.com (Twisted) Date: Fri, 22 Jun 2007 21:42:43 -0000 Subject: The Modernization of Emacs: terminology buffer and keybinding In-Reply-To: <87645h73ei.fsf@W0053328.mgh.harvard.edu> References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182272495.990807.99110@a26g2000pre.googlegroups.com> <87tzt3ihev.fsf@kobe.laptop> <1182370216.961241.6960@n60g2000hse.googlegroups.com> <85zm2ufjpb.fsf@lola.goethe.zz> <1182372592.803332.288260@u2g2000hsc.googlegroups.com> <5dtk4tF34jrimU1@mid.dfncis.de> <1182375388.814275.227380@n2g2000hse.googlegroups.com> <87645h73ei.fsf@W0053328.mgh.harvard.edu> Message-ID: <1182548563.561252.82480@i13g2000prf.googlegroups.com> On Jun 21, 11:06 am, jadam... at partners.org (Joel J. Adamson) wrote: > And it's baloney! No one in my office that uses one of these supposedly > user-friendly machines thinks that it's actually easy to use. They > slam their keyboards and throw their hands up *every* day. Because of bugs or the network going down or stuff like that, I'll bet, not because they can't find out or remember how to do some basic task. That's entirely orthogonal to the issue of interface learning curve OR interface ease-of-use. Emacs has deficiencies in both areas, if principally the former. (For an example of the latter, consider opening a file. Can't remember the exact spelling and capitalization of the file name? Sorry, bud, you're SOL. Go find it in some other app and memorize the name, then return to emacs. Now THAT is what I call disruptive context switching. Meanwhile even the lowly Notepad responds to "open" by displaying a list of text files and tools to navigate the folder hierarchy without having to do it blind, while still letting you blind-type a path if you remember it. And you can also paste the path in from the clipboard. Unix systems don't even *have* a proper system-wide clipboard and copy/paste capability. Under X there's a weak, text-only imitation, which doesn't help you much when you want to copy a selection from an image in a paint program and paste it into a CAD or web-design or specialized image-manipulation tool or whatever...you have to save it to a file and load it, which is a pain in the butt and slowly clutters your hard drive with "temporary" files you occasionally forget to delete. > The only solution that really works is for people to _learn_ how to > use computers, and to accept that it will be a challenge. How much learning it takes can be varied by the programmer, however. They can choose to make the learning curve steeply vertical at takeoff, or they can make it start out shallow and climb steeply only when the user desires expert functionality. (They can also, stupidly, choose to leave out fancier functionality entirely, of course.) As for bugs and other frustrations, better robustness in the key areas of memory management and concurrency control is needed. Most serious (especially crash-causing, data-losing, or data-corrupting) bugs involve memory mismanagement and a lot more, as well as other serious bugs, result from race conditions. These sorts of bugs are also responsible for a lot of security holes -- buffer overrun exploits are only possible against targets with memory management and input validation bugs. Java apps, due to Java's memory management model, are immune to these. The Windows world may have a fair bit to learn from the Unix world about software reliability and QA, and also about better supporting task automation. But not about user interface design for when tasks are done manually. > And as for the arcane commands needed to get to the help page, their > on the splash screen. Have you used Emacs recently? Of course not. It's too hard to get started using it, so I gave up on it years ago. From python-url at phaseit.net Mon Jun 25 13:46:09 2007 From: python-url at phaseit.net (Gabriel Genellina) Date: Mon, 25 Jun 2007 17:46:09 +0000 (UTC) Subject: Python-URL! - weekly Python news and links (Jun 25) Message-ID: QOTW: "[R]edundant/useless/misleading/poor code is worse than wrong." - Michele Simionato http://groups.google.com/group/comp.lang.python/msg/74adbb471826a245 "Unit tests are not a magic wand that discover every problem that a program could possibly have." - Paul Rubin http://groups.google.com/group/comp.lang.python/msg/6e683105172b2ca7 Some tricks to automatically enter the debugger when an exception happens: http://groups.google.com/group/comp.lang.python/browse_thread/thread/3ffc25cbd3d1947/ A recurring topic: using uniform collections of objects: http://groups.google.com/group/comp.lang.python/browse_thread/thread/f7eebeb1ebe17a4/ Some concerns about eggs, the way they handle dependencies, and restrictive environments: http://groups.google.com/group/comp.lang.python/browse_thread/thread/50e06542f2452c9e/ Four different answers from four different persons to the same problem: how to modify a variable in an outer scope from inside the inner function http://groups.google.com/group/comp.lang.python/browse_thread/thread/9cdb4af5755e4daa/ A conspicuous Pythonista shows his italian temper discussing why redundant statements aren't any good: http://groups.google.com/group/comp.lang.python/browse_thread/thread/a8c170e10c643f27/ A long thread about function annotations in Python 3.0 and its actual usefulness for argument type checking: http://groups.google.com/group/comp.lang.python/browse_thread/thread/1b2a416d6fbe5b61/ This loooong thread started more than two weeks ago: still about macros, programmable syntax, and what is good for Scheme is not necesarily good for Python: http://groups.google.com/group/comp.lang.python/browse_thread/thread/e587471d08dbfcbb/ ======================================================================== 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. The Python Papers aims to publish "the efforts of Python enthusiats". http://pythonpapers.org/ 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 Steve Bethard continues the marvelous tradition early borne by Andrew Kuchling, Michael Hudson, Brett Cannon, Tony Meyer, and Tim Lesher of intelligently summarizing action on the python-dev mailing list once every other week. http://www.python.org/dev/summary/ The Python Package Index catalogues packages. http://www.python.org/pypi/ The somewhat older Vaults of Parnassus ambitiously collects references to all sorts of Python resources. http://www.vex.net/~x/parnassus/ Much of Python's real work takes place on Special-Interest Group mailing lists http://www.python.org/sigs/ 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 twisted0n3 at gmail.com Sun Jun 24 00:57:20 2007 From: twisted0n3 at gmail.com (Twisted) Date: Sun, 24 Jun 2007 04:57:20 -0000 Subject: The Modernization of Emacs: terminology buffer and keybinding In-Reply-To: References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182272495.990807.99110@a26g2000pre.googlegroups.com> <87tzt3ihev.fsf@kobe.laptop> <1182370216.961241.6960@n60g2000hse.googlegroups.com> <85zm2ufjpb.fsf@lola.goethe.zz> <1182372592.803332.288260@u2g2000hsc.googlegroups.com> <1182373919.262388.100740@c77g2000hse.googlegroups.com> <85r6o6fhkb.fsf@lola.goethe.zz> <1182375045.626510.188170@m36g2000hse.googlegroups.com> <85myyufgwj.fsf@lola.goethe.zz> <1182375528.985142.293900@q69g2000hsb.googlegroups.com> <1182545268.055596.228700@i38g2000prf.googlegroups.com> Message-ID: <1182661040.286559.150880@q75g2000hsh.googlegroups.com> On Jun 23, 2:04 am, Robert Uhl wrote: > Of course, emacs doesn't take years of mastery. It takes 30, 40 > minutes. I gave it twice that, and it failed to grow on me in that amount of time. > > Besides, ANY interface that involves fumbling around in the dark > > trying to find a light switch is clunky. > > That sounds like vi, not emacs. That sounds like any application where you need to read the help, but "f1" does not bring up a separate help window, switchable with the main one using alt-tab or the mouse, and navigable using arrows, pageup, pagedn, and the mouse. The result of that is invariably that when the document has the focus, the help is open to "help on switching windows" rather than whatever you need it to be on once the document has the focus. You can read the help on doing what you want to do with the document, but to apply it you need to transfer focus back to the document. If doing that isn't second-nature, you have to navigate the help away from where you need it to get the focus back to the document. Now the focus is on the document, but the help you need isn't displayed next to it anymore. Frustrating? You can't begin to imagine, I suspect. Apparently, some people are born somehow able to avoid this problem without having to memorize one or the other piece of help. You're clearly one of those. I am equally clearly NOT one of those. Of course, if emacs let you keep THREE windows open and visible at the same time, instead of being limited to one or a horizontally split two ... and a cramped 80x10 or so each, at that ... > > Applications that not only eschew normal methods of navigation of the > > interface, but force you to fumble your way between the help and the > > task you're trying to do, are definitely clunky. > > a) emacs doesn't 'eschew normal methods of navigation'; it's been doing > its own thing since before there _were_ Mac OS or Windows I'll admit that it didn't USED TO 'eschew normal methods of navigation', but at a certain point in time there began to be 'normal methods of navigation' and emacs naturally began eschewing them promptly and has done so ever since. > b) I believe you've never used the emacs tutorial, which is quite > definitely designed for you _not_ to have to fumble around between > windows If I haven't, it must be the case that finding this tutorial (or even discovering that it exists) was nontrivial, or it wasn't built into emacs, one or the other. My memory is somewhat fuzzy after all these years so you'll forgive me if I don't make a definite statement about which. On the flip side, if I have, the tutorial can't have been all it's cracked up to be. Especially given I can program Java proficiently, including some fairly sophisticated network-using tools, and clearly am not an idiot or untalented in technically demanding areas involving substantial amounts of arcana. Of course, I might have put more effort into learning effective Java; effort like that in learning some language is necessary to being a programmer. Thanks to modern editors and IDEs, putting a comparable amount into learning the mere mechanics of operating a text editor is not necessary, and I chose to spend the time and effort elsewhere, where it was necessary, such as on learning a programming language. The technical term for managing limited resources, such as time and effort, first where needed and never where avoidable, is "efficiency", in case you were unaware. > > The interface never improved over that time -- the biggest problem > > consistently being that whenever focus was successfully transferred to > > the document window, the help window was invariably open to the > > instructions for switching windows, so you could never be doing > > something with the document and have the help for that something > > available at a glance. > > That doesn't even make sense. Either your memory is faulty Impossible > you've never actually used emacs Untrue > or you're just making things up. Also untrue, and you've just accused me of incompetence once and of lying twice, which in a formerly civil discussion constitutes behavior that I consider to be in poor taste. > If I'm browsing the manual > online, I can switch from said manual to my document buffer without > making the manual scroll to the documentation for switch-to-buffer. Apparently because you find the switch second nature, despite its not being the obvious (which is ctrl-tab, to switch between documents in an MDI app). Cheat sheet? Memorized with painstaking months of hard effort? Thanks for proving my point, either way. > In fact, I am not aware of any package which auto-changes the *info* or > *Help* buffers to reflect the last keyboard command. I didn't say it auto-changes. It manual-changes. The exact sequence of events that causes this with a novice user being: * Need to do X, and the usual command doesn't work (e.g. go to save document and get search prompt) * Now nothing much works (typing stuff bleeps), hit esc a bunch of times * Now it complains of hitting esc too many times, but typing into the document at least works again * OK, time to resort to *gulp* the help. * Oh, great, now what did it do? I hit F1 and ... * Eh. Try random stuff. Help starts with h. Alt-h? Ctrl-h? ... * Oh, right. I seem to remember the help popping up unwanted when I tried to backspace over a typo earlier, so I'll just do that. * Hrm, now how to search the bloody thing? * * Ah. "How to do Foobar to your open document". Perfect! * Oh crap. How do I do anything to my open document, when the focus is on the help instead of the document? * * Ah, I hit this. It worked! * Oh, fudge. Where did "How to do Foobar to your open document" go? The help's open to "How to switch windows". For shame. * Switch back, scroll ... there it is. * Crap, now I don't remember how to put the focus back on the document window. * More scrolling. * Oh, fudge. Where did "How to do Foobar to your open document" go? The help's open to "How to switch windows". For shame. * * Error: Stack overflow. Dumping core. I trust you get the picture. [snip] Whoa, what did you just say? Page 899 of the ... good Christ. Er ... Run! Flee! It's a monster! Head for the hills! Sound the civil defense sirens, tornado TORNADO! *runs* > > Infrequently used commands you can stand to hunt for in menus. When > > you find you use one frequently, you can try to learn the keyboard > > shortcut -- and you can find it without even consulting the help, > > simply by finding the command's menu item. > > This is no different from emacs. There's a menu bar What are you blithering about? Oh, great, now I'm using the term "blithering". :P But ... WHAT menu bar? We're discussing emacs. As in, a text-mode editor. As in a cramped little 80x24 grid of letters, numbers, spaces, and punctuation with no menus, no concept of a pointing device, and a bad attitude. Actually, the big thing the GUI and mouse did was rescue us from escalating UI problems with tasks complex enough to require modes. You needed either separate components with separate associated functionality and a "focus" to move among them, or you needed commands and keyboard-toggled modes. The former got you an emacs and the "can't switch back from the help" syndrome, and the latter got you ... something vile. Until the GUI-with-pointing device, which made user control of a "focus" a snap requiring virtually zero learning curve, and better yet, what little learning there was being transferred readily across applications. Unified windowing systems, with Macs and Windows, cemented the victory of the pointing device over the problem of focus management. Point at the thing you want to use next and click; that simple. A child can do it. Using a GUI is like doing a job yourself, such as washing the car. Using something from the dinosaur age, especially afterwards, feels like sitting back and directing some hired help. Help that happens to be blind as a bat as well as having the usual poor grasp of English. "Left, Senor. Right, Senor. No not THAT far right! Now you've gotten it all into the open drivers-side window, and those documents I left on the front seat are ruined!" Ouch. Yet trying to control old text-mode tools is pretty much exactly the same, only the flawless English it speaks belies an even dodgier grasp of same, or even the need to speak to it in some obscure dialect of Greek full of "meta" instead...and it doesn't apologize when there's a screwup a more hands-on interface would easily have prevented. If you want a job right, do it yourself. With a mouse, you can; no need to speak an obscure variant of Swahili into a keyboard just to get the focus to the document from the help or wherever. And to top it off, every Windows app understands tab and alt-tab and most understand ctrl-tab. Actually, the OS GUI components themselves understand alt- tab, and the applications just get told the focus went elsewhere or came back, making it one less area for application designers to screw things up. (All too often, they screw up ctrl-tab in tabbed/MDI apps, or screw up tab by using a dodgy tab order or controls with no visual indication of focus, mind. And then you can just resort to the mouse, rather than throw up your hands or find something non-electronic to sob into so as to avoid ruining another $40 keyboard.) > You've actually hit on another advantage of emacs: consider emacs itself > as an operating system hosting multiple applications, in which the vast > majority of commands are the same. It's an "operating system" to precisely the extent Windows 3.1 was. It's like Windows 3.1 in a number of other ways too, including size and aesthetics, though not stability. Even more like its predecessor DOSShell. Take that however you wish. At least Windows 3.1 had most apps have the same keys for the vast majority of commands, and those were the right keys. Emacs has all the applications have the vast majority of their commands use the same WRONG keys. Including whatever you'd use to rebind them. And the help you'd use to find out what the damn keys are in the first place. ;) And let's not forget that to someone with a 17" LCD monitor and a blisteringly fast graphics card, 80x24 text in a terminal emulator is somewhat underwhelming, and doesn't provide anything like the information density needed to make truly complex software interfaces usable. The human optic nerves have about 100Mbps of bandwidth *each*; that's a couple of ethernet cables directly into the cortex. Even a large, high resolution, big-color-gamut display with a decent refresh rate doesn't use more than a fraction of that capacity to deliver information to the user, even when the display is used to maximum advantage by the software to provide state information and navigation cues (and document views!). Those dim old greenly-glowing 80x24 terminals flickering at 20-odd Hz, by contrast ... barely adequate to design their own replacements on, though necessary for same. It's a good thing some people are apparently very good at maintaining most of the state information in their head that that tiny little box of text isn't displaying to them, and "reading between the lines" to make use of even fairly complex applications through such a tiny interface. Or those replacements might never have been built. > I can use the same text-editing > commands for reading & writing emails, reading & writing Usenet posts, > reading & writing code, browsing the web, organising my schedule and so > forth. I'm not sure that's such an advantage. Sometimes, unifying tasks too much creates security holes, especially when some of those tasks are network-facing and some are not. Some proposed or actual Windows features result in an unclear boundary between "my computer" and "the net out there", and that's bound to result in leaked passwords and credit-card numbers and all manner of other accidental breaches, as well as enable a variety of new social engineering attacks to purposely compromise more of the same. Phishing and similar attacks already pose a problem, but if the "phishing" looks like it's local applications or content instead of online, it's even more likely to be mistakenly trusted. One sometimes wonders if Microsoft has more sinister motives than "get rich with as shoddy and cheap a product as possible" in light of things like this. I do hope the unified stuff you describe in emacs isn't the open source equivalent. There's frank danger in making it too easy to mix up local stuff and online stuff while at work at a computer. > The vast majority of what we do on a computer is reading & writing > text--wouldn't it be cool to have a full-fledged text editing > environment always available for that sort of thing? Define "we". It can't be "people", because a substantial fraction of people use computers heavily for image or even 3D manipulation, or sound, rather than text, or a mixture with text not predominant, and a much larger fraction use computers for absolutely nothing at all. "Programmers" maybe. Even so, some people program from time to time but do a lot of, say, image manipulation. I expect even most programmers like to be able to see what the heck they're doing, rather than resorting to fumbling around with a flashlight or grunting terse instructions to a blind butler with an IQ in the mid-zeros. > Wouldn't it be cool not to have one program implement search in one way, and another a > second way, and yet another a third? Wouldn't it be cool to have access > to a proper text editor when editing text on a web page? Search is usually ctrl+f, type something, hit enter in my experience. And I can use any text editor I want to edit HTML. > That's how I learnt emacs. I was 13, and had only ever used Mac > software up until that point. I had a fairly limited command set > (basically, C-x C-f, C-x C-s & C-x C-c). That looks like three commands, although I can't be sure -- my Swahili is a little rusty from years of disuse. ;) I'd normally use at least eight -- open, save, quit, find/find next, replace, cut, copy, and paste. That's not counting arrows, page up, page down, del, backspace, and the like, and unixy tools don't let you take even THOSE for granted. And if I needed more, add help. Add the four arrows, page up, page down, delete-forwards, backspace, and help to the original eight and we now have 17 commands. I seriously doubt that your short chunk of Swahili up above encompasses all of them. > Do you realise that emacs has a GUI these days? I'm writing this in a > 70-line window, with gtk+ widgets. Which means full-resolution, > full-colour. What are you talking about? Clearly not emacs, which is a console app for unix systems (with the inevitable MS-DOS ports and others). Some sort of bastardized Windows port I suppose? I've seen the occasional attempt at a Windows port of a unix tool, and the results are fairly uniformly awful. Everything looks mostly right, and nothing works quite right. They're often actually more unstable than native Windows apps, probably because the porters don't know half as many of the landmines littering the windoze APIs as real Windows application programmers do (and *they* only know maybe half of the total, to judge by the stability of even higher-quality Windows apps) and because they are bolting on a thin layer of Windows widgets onto a core that works in ways fundamentally alien to those same APIs. No real Windows app dares to try spawning around 700 threads to service a request to copy two lines of text to the clipboard, for example. :) From tjreedy at udel.edu Mon Jun 11 18:40:08 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 11 Jun 2007 18:40:08 -0400 Subject: Python's "only one way to do it" philosophy isn't good? References: <1181368143.874341.273140@r19g2000prf.googlegroups.com> Message-ID: "Antoon Pardon" wrote in message news:slrnf6q9ah.cf9.apardon at rcpc42.vub.ac.be... | On 2007-06-09, Terry Reedy wrote: | > For him to imply that Python is anti-flexibility is wrong. Very wrong.. | > He should look in a mirror. See below. | | My impression is that python supporters often enough show | some anti-flexibility attitude. More so than supporters of most other languages, in particular Scheme? Here's the situation. Python is making inroads at MIT, Scheme home turf. The co-developer of Scheme, while writing about some other subject, tosses in an off-the-wall slam against Python. Someone asks what we here think. I think that the comment is a crock and the slam better directed, for instance, at Scheme itself. Hence 'he should look in a mirror'. | Yes science is different. The difference is the following. Should | science only know the Newtonian vectoral mechanics and someone | would come up with the Lagrangian approach, nobody would protest | against this new approach by remarking that there should only be | one obvious approach, The history of science is a history of innovation and resistance to innovation. Do you have information that the introduction of the Lagrangian approach was exceptional? Do you really think that no college student has ever groused about having to learn another approach that is only equivalent to what he already knows? | Yet these kind of remarks are made often enough when someone suggest a | change to python. So? Tim wrote 'There should be one-- and preferably only one --obvious way to do it'. The primary clause is that there should at least one. The secondary clause is that once there is a good and obvious way to do something, we take a hard look before adding another. As it is, there are already multiple ways to do many things. And there are probably at least 10 suggested innovations for everyone accepted. tjr From apatheticagnostic at gmail.com Fri Jun 1 22:38:07 2007 From: apatheticagnostic at gmail.com (kaens) Date: Fri, 1 Jun 2007 22:38:07 -0400 Subject: Examples of high-quality python code? In-Reply-To: <1180619916.951795.110180@g4g2000hsf.googlegroups.com> References: <1180619916.951795.110180@g4g2000hsf.googlegroups.com> Message-ID: <163f0ce20706011938m5dc10669t183a496b78552674@mail.gmail.com> On 31 May 2007 06:58:36 -0700, kyosohma at gmail.com wrote: > On May 31, 8:38 am, Larry Bates wrote: > > kaens wrote: > > > Hey everyone, I'm relatively new to python - I actually picked it up > > > to see how quickly I could start building non-trivial apps with it. > > > > > Needless to say, I was quite pleased. > > > > > Anyhow, I'm looking to expand my understanding of python, and I feel > > > that one of the best ways to do that is looking at other peoples code. > > > > > Unfortunately, I don't feel like I grok the python mindset quite well > > > enough to fully distinguish between awesome, average, and not-pythony > > > code, so I was hoping some of the more experienced python people could > > > point me to some (preferably FOSS) non-trivial apps written in python > > > that are examples of great python code. > > > > > I realize this may be a bit ambiguous - basically I don't want to go > > > randomly downloading other people's source and end up assimilating > > > techniques that aren't . . . well . . . pythonistic. > > > > > So, who wants to hook me up? > > > > You should consider picking up a copy of Python Cookbook. Alex and > > others have reviewed the code it contains and IMHO it is well written. > > > > I've also learned quite a lot from: > > > > Python on Win32 (book by Mark Hammond/Andy Robinson) > > Reading source code to standard library > > Reading ReportLab source (www.reportlab.org) > > Reading PIL source (www.effbot.org) > > Reading wxPython source (www.wxpython.org) > > Monitoring this list on a daily basis > > > > -Larry > > Also "Python Programming" by Lutz has some great code to learn from as > it also explains most of it. > > Mike > > -- > http://mail.python.org/mailman/listinfo/python-list > Thanks for the replies everyone - I don't have the spare cash to buy a book right now, but I've started studying the standard library, and I do monitor this list on a regular basis. From stefan.behnel-n05pAM at web.de Thu Jun 21 04:09:53 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Thu, 21 Jun 2007 10:09:53 +0200 Subject: Looking to embed python into html like mason In-Reply-To: References: Message-ID: <467A3251.1050006@web.de> Steven W. Orr wrote: > Does something like that exist? Many of them, as usual :) http://wiki.python.org/moin/WebProgramming Stefan From stuart.tett at gmail.com Sat Jun 23 14:56:14 2007 From: stuart.tett at gmail.com (stuart.tett at gmail.com) Date: Sat, 23 Jun 2007 18:56:14 -0000 Subject: C API: passing by reference In-Reply-To: <467d66e5$0$2795$9b622d9e@news.freenet.de> References: <1182623135.952521.174410@w5g2000hsg.googlegroups.com> <467d66e5$0$2795$9b622d9e@news.freenet.de> Message-ID: <1182624974.042330.226150@w5g2000hsg.googlegroups.com> Thanks for that clarification Martin. When I googled it before, the first page I read said "Python passes all arguments using 'pass by reference'." However, after seeing your reply and further searching I see that this is not true. I have a python function insertEdge which takes to 2-tuples of (faceid,vertexid) and returns the edgeid. But upon execution of the function the two vertexid's end up sharing the same faceid. So right now my solution is just to also return the two new (faceid,vertexid). These will both have the same vertexid as before, but have a different faceid then before (sharing the same faceid). Here for example is a script to create a triangle: v1 = createVertex((0,0,0)) v2 = createVertex((1,0,0)) e1,v1,v2 = insertEdge(v1,v2) v3 = createVertex((0,1,0)) e2,v2,v3 = insertEdge(v2,v3) e3,v3,v1 = insertEdge(v3,v1) Here is the C++ code: static PyObject * dlfl_insert_edge(PyObject *self, PyObject *args) { uint faceId1; int vertId1; uint faceId2; int vertId2; int edgeId = -1; if( !PyArg_ParseTuple(args, "(ii)(ii)", &faceId1, &vertId1, &faceId2, &vertId2) ) return NULL; if( currObj ) { edgeId = DLFL::insertEdge( currObj, faceId1, vertId1, faceId2, vertId2 ); currObj->clearSelected( ); } return Py_BuildValue("i,(ii)(ii)", edgeId, faceId1, vertId1, faceId2, vertId2 ); } This works, but... Any suggestions if there is a cleaner way? Thanks! On Jun 23, 1:31 pm, "Martin v. L?wis" wrote: > stuart.t... at gmail.com schrieb: > > > I'm writing my own python extension module with the C API. In python > > all functions pass arguments by reference > > Can you please show an example what you mean by that? There is no > "pass-by-reference" in Python: a function can not normally modify > the variable in the caller. > > When you show what precisely you want to achieve, it should be easy > to say how to do that in C. > > Regards, > Martin From robert.rawlins at thinkbluemedia.co.uk Fri Jun 22 10:47:23 2007 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins - Think Blue) Date: Fri, 22 Jun 2007 15:47:23 +0100 Subject: Strange Thread Issue Message-ID: <017801c7b4dc$4014fab0$c03ef010$@rawlins@thinkbluemedia.co.uk> Hello Guys, I'm having an issue with a thread which I've not come across before and it has be baffled. The thread doesn't really do a lot, it simple contains a popen command to run something from cmd, now then i trigger the thread form my main application using the .start() method nothing happens, the command prompt program isn't triggered, yet as soon as a ctrl+c to close my application the thread then seems to kick into life and work. Any ideas what is causing this? Thanks guys, Rob -------------- next part -------------- An HTML attachment was scrubbed... URL: From emin.shopper at gmail.com Tue Jun 19 16:10:36 2007 From: emin.shopper at gmail.com (Emin.shopper Martinian.shopper) Date: Tue, 19 Jun 2007 16:10:36 -0400 Subject: how does one use pdb and doctest.testmod(raise_on_error=True)? Message-ID: <32e43bb70706191310m32c5eb9u3188e618a70f88bf@mail.gmail.com> Dear Experts, How does one use pdb and doctest.testmod(raise_on_error=True)? What I would like to happen is that when a doctest fails (e.g., by raising an exception), I can do import pdb; pdb.pm() to figure out what went wrong. But when I do pdb.pm() I end up in doctest.DebugRunner.report_unexpected_exception and can't see the actual code in my module which failed. Thanks, -Emin -------------- next part -------------- An HTML attachment was scrubbed... URL: From zaperaj at gmail.com Thu Jun 21 22:37:09 2007 From: zaperaj at gmail.com (zaperaj at gmail.com) Date: Thu, 21 Jun 2007 19:37:09 -0700 Subject: Error while installing Python2.5.1 In-Reply-To: References: <1182413023.924197.302390@o11g2000prd.googlegroups.com> Message-ID: <1182479829.920633.239290@j4g2000prf.googlegroups.com> I dont understand.... What are my distribution repositories? From leehinde at gmail.com Fri Jun 15 15:51:27 2007 From: leehinde at gmail.com (Lee Hinde) Date: Fri, 15 Jun 2007 19:51:27 -0000 Subject: Html parser In-Reply-To: <1181916716.258484.74070@p77g2000hsh.googlegroups.com> References: <1181916716.258484.74070@p77g2000hsh.googlegroups.com> Message-ID: <1181937087.067928.12540@k79g2000hse.googlegroups.com> On Jun 15, 7:11 am, HMS Surprise wrote: > Could you recommend an html parser that works with python (jython > 2.2)? HTMLParser does not seem to be in this library. To test some > of our browser based (mailnly php) code I seek for field names and > values associated with them. > > Thanks, > > jh Twill: http://twill.idyll.org/ Don't know about the jython part.... From vasudevram at gmail.com Mon Jun 4 10:08:35 2007 From: vasudevram at gmail.com (vasudevram) Date: Mon, 04 Jun 2007 14:08:35 -0000 Subject: python unix install, sqlite3 In-Reply-To: <1180464013.989484.165910@q69g2000hsb.googlegroups.com> References: <1180443141.119281.304880@q66g2000hsg.googlegroups.com> <1180447556.474075.12800@q19g2000prn.googlegroups.com> <1180464013.989484.165910@q69g2000hsb.googlegroups.com> Message-ID: <1180966115.853017.155980@q19g2000prn.googlegroups.com> On May 29, 11:40 pm, Simon wrote: > On May 29, 7:05 am, vasudevram wrote: > > > > > > > On May 29, 5:52 pm, Simon wrote: > > > > I installed the source code on unix for python 2.5.1. The install went > > > mainly okay, except for some failures regarding: > > > _ssl, _hashlib, _curses, _curses_panel. > > > > No errors regarding sqlite3. > > > However, when I start python and do an import sqlite3 I get: > > > > /ptmp/bin/> python > > > Python 2.5.1 (r251:54863, May 29 2007, 05:19:30) > > > [GCC 3.3.2] on sunos5 > > > Type "help", "copyright", "credits" or "license" for more information.>>> import sqlite3 > > > > Traceback (most recent call last): > > > File "", line 1, in > > > File "/ptmp/Python-2.5.1/lib/python2.5/sqlite3/__init__.py", line > > > 24, in > > > from dbapi2 import * > > > File "/ptmp/Python-2.5.1/lib/python2.5/sqlite3/dbapi2.py", line 27, > > > in > > > from _sqlite3 import * > > > ImportError: No module named _sqlite3 > > > Some ideas: > > > I don't know if sqlite3 comes bundled with the standard Python source > > bundle. My guess is not. If not, that's the cause of the error - you > > need to install sqlite3 (and probably pysqlite3 (not sure of the name > > (whether it has a trailing 3) which, if I remember, is the Python > > binding/wrapper for sqlite3 (which is a C library, I think). Other > > possible cause of the error (if sqlite3 _is_ bundled with Python and > > no Python binding/wrapper is needed, is that sqlite3 depends on one of > > those other libraries you mention (such as _hashlib) for which you got > > errors while installing Python from source. > > > HTH > >VasudevRam > > Dancing Bison Enterpriseswww.dancingbison.com-Hide quoted text - > > > - Show quoted text - > > Vasudev, > Thanks so much for the reply. I went to their website and your guess > was correct. Python 2.5 has included support for sqlite but it only > includes the PySqlite interface module (now called sqlite3). It does > not include sqlite3 with the source distribution. > > Simon You're welcome, Simon. Good to hear that it worked :-) Vasudev From evan at yelp.com Thu Jun 21 20:40:42 2007 From: evan at yelp.com (Evan Klitzke) Date: Thu, 21 Jun 2007 17:40:42 -0700 Subject: rsync module? Message-ID: Are there any python modules for accessing rsync from python? I would like to be able to rsync files from a python script to a remote server running an rsync daemon. I'm well aware that I can invoke rsync using subprocess, os.system, etc., but I am curious if there is a way to do it directly. -- Evan Klitzke From dak at gnu.org Thu Jun 21 11:04:37 2007 From: dak at gnu.org (David Kastrup) Date: Thu, 21 Jun 2007 17:04:37 +0200 Subject: The Modernization of Emacs References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182370894.001918.36590@k79g2000hse.googlegroups.com> <1182372821.298343.316860@g4g2000hsf.googlegroups.com> <1182375321.067664.190780@o61g2000hsh.googlegroups.com> <86hcp1l6hb.fsf@lola.quinscape.zz> Message-ID: <864pl1l56i.fsf@lola.quinscape.zz> notbob writes: > On 2007-06-21, David Kastrup wrote: > >> You know you can use something like >> C-x C-f /su::/etc/fstab RET >> (or /sudo::/etc/fstab) in order to edit files as root in a normal >> Emacs session? > > As I understand it, this will only work for ver 22 and later or if > you have tramp(?) installed. I have 2.3.1 (no tramp) and all I get is: > > ftp> open su > ftp: su: Unknown host I should think that version 2.3.1 would not even try ftp. Is that on Multics? > I'm looking at upgrading to 22 for a couple other features, too. You'll find that the last 30 years of development indeed make a difference. -- David Kastrup From paul at boddie.org.uk Mon Jun 25 11:58:36 2007 From: paul at boddie.org.uk (Paul Boddie) Date: Mon, 25 Jun 2007 08:58:36 -0700 Subject: Chroot Jail Not Secure for Sandboxing Python? In-Reply-To: <1182782910.811850.284350@u2g2000hsc.googlegroups.com> References: <1182748892.916068.146780@p77g2000hsh.googlegroups.com> <467f55f7$0$20850$9b622d9e@news.freenet.de> <1182782910.811850.284350@u2g2000hsc.googlegroups.com> Message-ID: <1182787116.717732.35390@q75g2000hsh.googlegroups.com> On 25 Jun, 16:48, "gregpin... at gmail.com" wrote: > > I followed up with my ISP. Here's the answer I got: > > The os.exec call prepends the chroot directory to the absolute path, > but does NOT provide chroot for the child process. However, as long > as the environment is maintained, which contains an LD_PRELOAD, the > "chroot" will also be maintained. If LD_PRELOAD is removed or > ignored, then the chroot is ineffective. So it appears that as long as LD_PRELOAD is set (possibly to link the process to some other libraries than is usually the case), any affected processes are effectively jailed. This doesn't really sound like a traditional chroot environment, though. > Another way of saying it is that every process is responsible for > providing and maintaining the chroot through the LD_PRELOAD variable. > Those processes only maintain the chroot if that variable remains set. Right. > The only solution that would bypass this problem altogether would be a > statically linked python. (is that possible?) It would have to be > statically linked to a custom-modified glibc to provide the virtual > chroot environment. Some solutions depend on linking to restricted libraries, and the Wiki page you referenced probably talks about them as well. I was thinking that if I were to attempt to properly sandbox any current version of CPython, I'd start off linking it to restricted libraries which provide compatible interfaces for things like opening file handles; then I'd put various policy controls in those libraries so that you can have some control over what your programs do. Finally, you'd have to stop arbitrary (extension) module loading in order to prevent programs importing some nice modules and getting round the controls: for example, importing socket or os to get access to file handles (or to process creation which might get around the controls as suggested above). Eventually, this arrives more or less at where Brett Cannon is supposed to be right now with his sandboxed Python, perhaps by a different route and with some different outcomes. I notice that you've mailed me about a solution that I mentioned in the past, but I'll respond here in order to air the ideas in public. I looked into chroot "jails" and saw that some solutions exist for populating directories with enough files for things like daemons or services to be executed within the chroot environment. I also looked at ways to break out of chroot environments, and there's a fairly well- known trick involving open file handles which will do this effectively for non-root users. What I then considered was the possibility of avoiding population of a chroot filesystem by calling chroot and setuid on a minimal "jailer" process which then loads a jailed program after having imported a permitted set of modules. I don't have the details with me now, but I'll probably upload the code in the near future and post some kind of explanation of what it does here. I'm tempted to say that the better solution involves the restricted libraries solution mentioned above, and a nice side-effect of that could be a more modular CPython that would benefit people using the software in embedded environments: you'd have to insulate the virtual machine from even the most central modules, meaning that they could potentially be detached completely in places where memory and storage are better used on other things. Paul From phil at riverbankcomputing.co.uk Wed Jun 20 11:54:40 2007 From: phil at riverbankcomputing.co.uk (Phil Thompson) Date: Wed, 20 Jun 2007 16:54:40 +0100 Subject: QPainter In-Reply-To: <1182354299.328151.193300@j4g2000prf.googlegroups.com> References: <1182354299.328151.193300@j4g2000prf.googlegroups.com> Message-ID: <200706201654.40701.phil@riverbankcomputing.co.uk> On Wednesday 20 June 2007 4:44 pm, luca72 wrote: > Hello > using qt3 i do the follow for paint some line in a frame > > gr = QPainter(self.frame3) > gr drawLine(30,10,30,490) > and the line is draw. > > Whit qt4 : > gr = QtGui.QPainter(self.frame3) > #gr.setPen(QtGui.QPen(QtCore.Qt.black, 1, QtCore.Qt.SolidLine)) > gr.drawLine(30,10,30,490) > and nothing is draw but i have no error > > The frame is the same with the same dimension and relative dimension. > > where is the error? Impossible to tell with so little information. One guess is that Qt4 requires you to paint from a reimplementation of paintEvent(). Post a small but complete example to the PyQt mailing list. Phil From alextabone at gmail.com Fri Jun 1 04:03:43 2007 From: alextabone at gmail.com (Alchemist) Date: Fri, 01 Jun 2007 01:03:43 -0700 Subject: calling Postgresql stored procedure (written in plpython) In-Reply-To: References: <1180516688.022056.70220@q69g2000hsb.googlegroups.com> Message-ID: <1180685023.802141.168680@h2g2000hsg.googlegroups.com> Thanks for your help. My stored procedure is written in pythonpl. I noticed that SELECT queries are executed correctly (results are returned to my script) whereas UPDATE queries are not being performed as the data is not updated. I am using a database user with read/write access to the database. Is there a commit statement in plpython? (e.g. plpy.commit()) Why are UPDATEs failing? From borud-news at borud.no Tue Jun 26 10:52:54 2007 From: borud-news at borud.no (Bjorn Borud) Date: 26 Jun 2007 16:52:54 +0200 Subject: The Modernization of Emacs: terminology buffer and keybinding References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182272495.990807.99110@a26g2000pre.googlegroups.com> <87tzt3ihev.fsf@kobe.laptop> <1182370216.961241.6960@n60g2000hse.googlegroups.com> <85zm2ufjpb.fsf@lola.goethe.zz> <1182372592.803332.288260@u2g2000hsc.googlegroups.com> <1182373919.262388.100740@c77g2000hse.googlegroups.com> <85r6o6fhkb.fsf@lola.goethe.zz> <1182375045.626510.188170@m36g2000hse.googlegroups.com> <1182546050.465987.115740@q19g2000prn.googlegroups.com> <871wg3k8c8.fsf@thalassa.lan.informatimago.com> <1182546979.295368.146110@q19g2000prn.googlegroups.com> <87wsxviqol.fsf@thalassa.lan.informatimago.com> <1182552172.406571.116390@i38g2000prf.googlegroups.com> Message-ID: [Robert Uhl ] | | Agreed. Stallman got sidetracked by Scheme, which IMHO was a | dead-end. too many people buying SICP and believing what they heard about it being an important book. I too spent some time exploring Scheme, or should I say, wasted some time, years ago, and nothing came of it other than a profound irritation. these people seemed to be completely disconnected from reality. Scheme, and thus Guile, might have been a viable path if these people had only been practical instead of stubbornly insisting on being odd. | A Common Lisp emacs would be pretty sweet. There's a Climacs project, | but they're just focused on providing an editor, not on providing a | full-fledged emacs. if nothing else, a proper Emacs in Common Lisp might give me a reason to learn Lisp properly. -Bj?rn From andreengels at gmail.com Sat Jun 2 00:46:10 2007 From: andreengels at gmail.com (Andre Engels) Date: Sat, 2 Jun 2007 06:46:10 +0200 Subject: c[:]() In-Reply-To: <005f01c7a471$6f4b8b30$240110ac@Muse> References: <1180504190.055427.173610@h2g2000hsg.googlegroups.com> <135tv1bjqgbmsc9@corp.supernews.com> <9qudnbFRU9QHJsLbnZ2dnUVZ_rKvnZ2d@speakeasy.net> <005f01c7a471$6f4b8b30$240110ac@Muse> Message-ID: <6faf39c90706012146l551dfe60o6358f48dd5127505@mail.gmail.com> 2007/6/1, Warren Stringer : > I am not insisting on anything. I use ``c[:]()`` as shorthand way of saying > "c() for c in d where d is a container" > > Having c() support containers seems obvious to me. It jibes with duck > typing. Perhaps the title of this thread should have been: "Why don't > containers quack?" > > A change is surprising only if it breaks something. I still haven't seen any > code that breaks by making such a change. Seeing such code would teach a > great deal. I think it very much bites duck typing. Currently, if I try to execute a string or a list or whatever, I get: TypeError: 'str' object is not callable But under your proposed semantics, suppose a is a list with some executable and some non-executable elements. What should a() now give? It cannot be a TypeError, because a list (in your semantics) is callable. Whatever error it gives, and whether or not the preceding executables are executed first, it will not be an existing error acting the way it normally does - there is no Python error for "you cannot do this with this object, but you can do it with other objects of the same type". And that does not seem to be a case of "We have never needed it yet" - the join method seems to have been specifically tailored so that no such error is needed. -- Andre Engels, andreengels at gmail.com ICQ: 6260644 -- Skype: a_engels From gagsl-py2 at yahoo.com.ar Fri Jun 22 02:58:32 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 22 Jun 2007 03:58:32 -0300 Subject: why __repr__ affected after __getattr__ overloaded? References: <1182483043.850101.110890@i13g2000prf.googlegroups.com> <1182491330.343267.122010@q19g2000prn.googlegroups.com> Message-ID: En Fri, 22 Jun 2007 02:48:50 -0300, Roc Zhou escribi?: > I know what's wrong. Thank you. And I think > try: > return self.__dict__[attr_name] > is unnecessary, because python will do it itself for us. Exactly; by the time __getattr__ is called, you already know attr_name is not there. > So now I have to overload __str__, but how can I make self.__str__ > print as builtin str(): at here, I want get the result like: > > ? I would do the opposite: *only* create inexistent attributes when they are not "special". This way you don't mess with Python internals. ... def __getattr__(self, name): ... if name[:2]!='__' or name[-2:]!='__': ... self.__dict__[name] = 'inexistent' ... return self.__dict__[name] ... raise AttributeError,name This way you don't create "fake" attributes for things like __bases__ by example, and dir(), vars(), repr() etc. work as expected. -- Gabriel Genellina From newsgroups at debain.org Sun Jun 17 05:53:13 2007 From: newsgroups at debain.org (Samuel) Date: Sun, 17 Jun 2007 09:53:13 +0000 (UTC) Subject: Trivial string substitution/parser Message-ID: Hi, How would you implement a simple parser for the following string: --- In this string $variable1 is substituted, while \$variable2 is not. --- I know how to write a parser, but I am looking for an elegant (and lazy) way. Any idea? -Samuel From robert.kern at gmail.com Fri Jun 29 00:20:30 2007 From: robert.kern at gmail.com (Robert Kern) Date: Thu, 28 Jun 2007 23:20:30 -0500 Subject: Rappresenting infinite In-Reply-To: <20070628234618.2907b52d@localhost> References: <1182940919.351011.267020@n2g2000hse.googlegroups.com> <1182945569.081290.40870@c77g2000hse.googlegroups.com> <20070628234618.2907b52d@localhost> Message-ID: mmanns at gmx.net wrote: > On Wed, 27 Jun 2007 11:59:29 -0000 > Rob De Almeida wrote: > >> On Jun 27, 6:41 am, andrea wrote: >>> I would like to have a useful rappresentation of infinite, is there >>> already something?? >> from numpy import inf > > $ python > Python 2.4.4 (#2, Apr 5 2007, 20:11:18) > [GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-21)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. >>>> from numpy import inf >>>> inf == inf > True >>>> type(inf) > > > > This looks like the floating point inf to me. It is. > Does it differ from the > built-in inf? What built-in inf? > I would like to second the OP's question if there is a generic inf and > add the wish that that is not equal to itself (inf == inf would yield > nan). No. You can make one that fits your requirements, though. > Ideally, it would not be of type float and work with gmpy mpq. > But I might have rare requirements... Possibly. -- 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 anamax at earthlink.net Wed Jun 27 10:35:01 2007 From: anamax at earthlink.net (Andy Freeman) Date: Wed, 27 Jun 2007 07:35:01 -0700 Subject: Python's "only one way to do it" philosophy isn't good? In-Reply-To: <7x4pkt4xuz.fsf@ruckus.brouhaha.com> References: <1182750077.570603.160240@q69g2000hsb.googlegroups.com> <7xir9cbm0g.fsf@ruckus.brouhaha.com> <7xejjzmk7u.fsf@ruckus.brouhaha.com> <7xy7i7xjl5.fsf@ruckus.brouhaha.com> <7x4pkt4xuz.fsf@ruckus.brouhaha.com> Message-ID: <1182954901.132287.33420@j4g2000prf.googlegroups.com> On Jun 27, 1:15 am, Paul Rubin wrote: > Dennis Lee Bieber writes: > > > What happens when two individuals release "libraries" using these > > proposed macros -- and have implement conflicting macros using the same > > identifiers -- and you try to use both libraries in one application? > > Something like the current situation with Python web frameworks ;) Actually, no. For python, the most reasonable macro scope would be the file, so different files in the same application could easily use conflicting macros without any problems. From warren at muse.com Fri Jun 1 05:20:17 2007 From: warren at muse.com (Warren Stringer) Date: Fri, 1 Jun 2007 02:20:17 -0700 Subject: c[:]() In-Reply-To: <9qudnbBRU9SHIcLbnZ2dnUVZ_rLinZ2d@speakeasy.net> References: <1180504190.055427.173610@h2g2000hsg.googlegroups.com> <1180554872.3356.30.camel@dot.uniqsys.com> <465DF3DE.40404@cc.umanitoba.ca> <1180566831.239580.199300@m36g2000hse.googlegroups.com> <005401c7a31a$136f7fe0$240110ac@Muse> <135tobve86qj808@corp.supernews.com> <135tru124pie2b3@corp.supernews.com> <135tv1bjqgbmsc9@corp.supernews.com> <002801c7a3fb$56cc8030$240110ac@Muse> <9qudnbBRU9SHIcLbnZ2dnUVZ_rLinZ2d@speakeasy.net> Message-ID: <003001c7a42e$12107db0$240110ac@Muse> > Warren Stringer wrote: > > > `c[:]()` is unambiguous because: > > > > def c(): print 'yo' > > > > c() # works, but > > c[:]() # causes: > > > > Traceback (most recent call last)... > > c[:]() # causes: > > TypeError: unsubscriptable object > > > > There are many `c()` to be found in the wild and no `c[:]()`, thus > > unambiguous. To be honest, I wasn't sure, until testing this, just now. > > >>> c = 'not quite' > >>> c[:] > 'not quite' > >>> c[:]() > Traceback (most recent call last): > File "", line 1, in ? > TypeError: 'str' object is not callable Interesting example. By extension #------------------------- >>> def c(): print 'yo' ... >>> c >>> c(bad) Traceback (most recent call last): File "", line 1, in ? NameError: name 'bad' is not defined #------------------------- Both your example and mine show well formed and ill formed statements at the command line. > You also seem to be under the impression that `x[:]()` is somehow > special syntax that is treated differently than `y = x[:]; y()`. It is > not. No; I was under the impression that `x[:]()` didn't work and the reason why it didn't work wasn't obvious. I like your use case. Am I correct in assuming that `y = x[:]; y()` is NOT to be found in working code? If that is the case, then nothing gets broken. It would be instructive to have a use case where enabling c[:]() would break existing code. > Besides, _ambiguity_ was never the problem. _Functionality_ is the > problem. Ambiguity is one of many parameters. It was a problem with another poster. I wish I had McConnel's Code Complete book handy. Let's see ... a search yields: debugging, testing, performance, portability, design, interfaces, style, and notation. My use case is this: do(orchestra(score)).pickle() do(orchestra(conductor)).sequence() And so now, that I can, I am happy. Life is good. Time to sleep. From bscrivener42 at gmail.com Fri Jun 22 17:21:58 2007 From: bscrivener42 at gmail.com (BartlebyScrivener) Date: Fri, 22 Jun 2007 21:21:58 -0000 Subject: The Modernization of Emacs: terminology buffer and keybinding In-Reply-To: <1182545268.055596.228700@i38g2000prf.googlegroups.com> References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182272495.990807.99110@a26g2000pre.googlegroups.com> <87tzt3ihev.fsf@kobe.laptop> <1182370216.961241.6960@n60g2000hse.googlegroups.com> <85zm2ufjpb.fsf@lola.goethe.zz> <1182372592.803332.288260@u2g2000hsc.googlegroups.com> <1182373919.262388.100740@c77g2000hse.googlegroups.com> <85r6o6fhkb.fsf@lola.goethe.zz> <1182375045.626510.188170@m36g2000hse.googlegroups.com> <85myyufgwj.fsf@lola.goethe.zz> <1182375528.985142.293900@q69g2000hsb.googlegroups.com> <1182545268.055596.228700@i38g2000prf.googlegroups.com> Message-ID: <1182547318.325617.16370@o11g2000prd.googlegroups.com> On Jun 22, 3:47 pm, Twisted wrote: > If it requires years of mastery, it is clunky Well, now you keep harping on this, but it's just not true. I use vim myself, but for purposes of this argument it doesn't matter. If you take the Vim tutorial and use the help (which appears in a split window anytime you want it), you can use Vim like any other text editor within a day or so, especially if you use Cream, which is set up to hold your Windows hands and act like any other Windows text editor on the surface. But if you use Vim for YEARS you get better and faster and more efficient precisely BECAUSE of its arcane capabilities. If you are going to keep your hands on the keyboard where they belong, if you REALLY want to go fast, then there's no alternative to having complex key commands, which become second nature over time, and take the place of repetitive, totally inefficient mousing around. You might enjoy this. Especially the link to an old essay called "Interface Zen" http://tinyurl.com/2da3om rd From rocksportrocker at googlemail.com Wed Jun 13 07:02:41 2007 From: rocksportrocker at googlemail.com (rocksportrocker) Date: Wed, 13 Jun 2007 11:02:41 -0000 Subject: How to format a string from an array? In-Reply-To: <1181725887.936450.108920@n15g2000prd.googlegroups.com> References: <1181725887.936450.108920@n15g2000prd.googlegroups.com> Message-ID: <1181732561.373929.62020@z28g2000prd.googlegroups.com> On Jun 13, 11:11 am, Allen wrote: > a = range(256) > I want to output the formated string to be: > 00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f > 10 11 12 13 14 15 16 17 18 19 1a 1b 1c 1d 1e 1f > ........................................................................ > f0 f1 f2 f3 f4 f5 6 f7 f8 f9 fa fb fc fd fe ff > > How to do it? You can start with hex_list = [ ("0"+hex(i)[2:])[-2:] for i in a ] This statement generates a list [ "00", "01", ... "ff"]. Now you only have to print this list. Greetings, Uwe From sjmachin at lexicon.net Fri Jun 8 21:33:45 2007 From: sjmachin at lexicon.net (John Machin) Date: Fri, 08 Jun 2007 18:33:45 -0700 Subject: DAO and Access97 WHERE clause fails In-Reply-To: References: Message-ID: <1181352825.656023.229680@z28g2000prd.googlegroups.com> On Jun 9, 10:17 am, "v.davis2" wrote: > Hi all, > > I am attempting to use Access97 as the database to hold the results of a > python script. I seem to be able to make simple SELECT clauses work (like > SELECT * FROM TableName), but have not been able to figure out how to add a > WHERE clause to that (e.g., SELECT * FROM TableName WHERE myFieldName = 34) > This fails complaining that the wrong number of parameters are present. > I haved tried DAO36 and I have tried the ADO version with the same results. > Therefore I have to conclude it is my screwup! > Help in the forum or via email would sure be appreciated! (v.dav... at cox.net) > > Here is the skeleton code: > > import win32com.client > daoEngine = win32com.client.Dispatch('DAO.DBEngine.35') > sDBname = 'vpyAnalyzeDirectorySize.mdb' > sDB = 'c:\\documents and settings\\vic\\my > documents\\tools\\python25\\_myscripts\\'+sDBname > daoDB = daoEngine.OpenDatabase(sDB) > > sSQL1 = 'SELECT * FROM T_Index2DirName' > daoRS = daoDB.OpenRecordset(sSQL1) # this works FINE and I can play > with the record set > > # > > hsDB = hash(sDB) > sSQL3 = 'SELECT * FROM T_Index2DirName WHERE iIndex = hsDB' # names are > all correct in mdb file Disclaimer: I've never used DAO. That SQL statement appears to be incorrect/meaningless. Don't you need something like sSQL3 = 'SELECT * FROM T_Index2DirName WHERE iIndex = %d' % hsDB ? You may need to read this (changing Office10 to whatever you have): C:\Program Files\Common Files\Microsoft Shared \Office10\1033\DAO360.CHM From walterbyrd at iname.com Sat Jun 23 13:45:34 2007 From: walterbyrd at iname.com (walterbyrd) Date: Sat, 23 Jun 2007 10:45:34 -0700 Subject: Collections of non-arbitrary objects ? In-Reply-To: <87wsxvrzsj.fsf@benfinney.id.au> References: <1182449993.223262.229500@z28g2000prd.googlegroups.com> <87k5twx4hf.fsf@benfinney.id.au> <1182559502.069773.321620@i38g2000prf.googlegroups.com> <87wsxvrzsj.fsf@benfinney.id.au> Message-ID: <1182620734.940718.196520@e16g2000pri.googlegroups.com> On Jun 22, 11:43 pm, Ben Finney wrote: > Can you help us understand, by showing a use case that would in your > estimation be improved by the feature you're describing? > Suppose you are sequentially processing a list with a routine that expects every item to be of a certain type. Something in the list that doesn't conform to the type could give you unexpected results, maybe crash your application. In python, as far as I know, there is nothing built into the language to keep any type of item from being included in a list - or any such structure. To me, that seems like a potentially vulnerability. Especially since variables in python do not have to be explicitly assigned - another variable that points to the same thing, could change the data that a variable points to. From toddw at activestate.com Mon Jun 11 19:28:35 2007 From: toddw at activestate.com (Todd Whiteman) Date: Mon, 11 Jun 2007 16:28:35 -0700 Subject: Python in the Mozilla world In-Reply-To: References: Message-ID: <466DDAA3.5080206@activestate.com> Eric S. Johansson wrote: > this morning I was looking at Python and XUL. I was impressed by the very > interesting projects that were happening around 2005 but it seems like they have > all died. Integrating Python at the Mozilla was also very intriguing as it held > the promise of eliminating JavaScript for extension development (yaaa). But > that seems to have died as well. In fact, it looks like that almost all of the > alternative languages for browsers have died for lack of interest or something. > I was really looking forward to pyax Not quite true. Mark Hammond has been working on integrating Python into Mozilla to work as a JavaScript near equivalent for use with XUL. This is currently integrated into the mozilla trunk and expected to be ready/included for Firefox 3. I have seen this in action, so it is not just hype. Check PyDom info for a brief overview: http://developer.mozilla.org/en/docs/PyDOM There are also a few projects that make use of PyXPCOM in the current mozilla/firefox/xulrunner builds, such as Democracy and Komodo. Cheers, Todd From kyosohma at gmail.com Mon Jun 11 11:07:47 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Mon, 11 Jun 2007 08:07:47 -0700 Subject: with as a reserved word In-Reply-To: <1181574196.682123.291010@a26g2000pre.googlegroups.com> References: <1181574196.682123.291010@a26g2000pre.googlegroups.com> Message-ID: <1181574467.412903.61100@g4g2000hsf.googlegroups.com> On Jun 11, 10:03 am, BBands wrote: > I gather that 'with' is on its way to becoming a reserved word. Is > this something that will break? > > import Gnuplot > gp = Gnuplot.Gnuplot(debug=1) > data = Gnuplot.Data([1,2,3,4,3,2,3,4,3,2,1], with='linespoints') > gp.plot(data) > > >>> :3: Warning: 'with' will become a reserved keyword in Python 2.6 > > http://www.gnuplot.info/http://gnuplot-py.sourceforge.net/ > > This was run by PyScripter 1.8.7.1 with Python 2.5. > > jab Looks that way since you can assign anything to 'for' or 'if' or other reserved words. Mike From carsten at uniqsys.com Wed Jun 20 09:08:04 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Wed, 20 Jun 2007 09:08:04 -0400 Subject: caseless dictionary howto ? In-Reply-To: References: <4dc64$46782a84$d443bb3a$4629@news.speedlinq.nl> <4678E021.9040709@web.de> Message-ID: <1182344884.3383.4.camel@dot.uniqsys.com> On Wed, 2007-06-20 at 11:14 +0200, stef wrote: > Stefan Behnel wrote: > Serial_HW_Read = the name of a function > "F" = the type of that function (procedure / function / pseudo variable > / interrupt /..) > "++" = the direction of each parameters, (input / output / input+output ) > T = a tupple, containing the type of each of the parameters (bit / byte/ > sbyte / word / ...) > > maybe a class to hold them would look better), > maybe, but no human is looking at it ;-) But humans might look at the code that looks at the thing. thing.func_type is self-documenting, thing[0] is not. -- Carsten Haese http://informixdb.sourceforge.net From john at datavoiceint.com Fri Jun 15 10:31:19 2007 From: john at datavoiceint.com (HMS Surprise) Date: Fri, 15 Jun 2007 07:31:19 -0700 Subject: MySQL - Jython2.2 Message-ID: <1181917879.186507.176140@u2g2000hsc.googlegroups.com> I thought I had a winner mySql-python but it require2 python 2.3-5 and the tool I am using (maxq) is based on jython 2.2. Is there another way that I could perform queries from python? thanx, jh From dak at gnu.org Sat Jun 23 13:22:03 2007 From: dak at gnu.org (David Kastrup) Date: Sat, 23 Jun 2007 19:22:03 +0200 Subject: The Modernization of Emacs: terminology buffer and keybinding References: <1182272495.990807.99110@a26g2000pre.googlegroups.com> <87tzt3ihev.fsf@kobe.laptop> <1182370216.961241.6960@n60g2000hse.googlegroups.com> <85zm2ufjpb.fsf@lola.goethe.zz> <1182372592.803332.288260@u2g2000hsc.googlegroups.com> <1182549094.366282.286740@m37g2000prh.googlegroups.com> <87bqf7fwmg.fsf@telesippa.clsnet.nl> <1182553682.197778.138500@g37g2000prf.googlegroups.com> <877ipvfswe.fsf@telesippa.clsnet.nl> <5e50ltF356nbjU1@mid.dfncis.de> Message-ID: <851wg2h9hg.fsf@lola.goethe.zz> Matthias Buelow writes: > Tim Roberts wrote: > >> Editors are like underwear. We each have our own favorite brand, and >> nothing you say will convince me to change mine. > > You really should have stopped here.... :) Well if "It stinks!" is not incentive enough for him to change his underwear, what will? -- David Kastrup, Kriemhildstr. 15, 44793 Bochum From jstroud at mbi.ucla.edu Wed Jun 6 21:03:53 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Wed, 06 Jun 2007 18:03:53 -0700 Subject: Determinant of Large Matrix In-Reply-To: References: Message-ID: Steven D'Aprano wrote: [Valuable Response] Thank you Steven for your helpful comments. Please see my reply to Bjoern Schliessmann where I have restated my problem. James From rupole at hotmail.com Sat Jun 30 13:55:49 2007 From: rupole at hotmail.com (Roger Upole) Date: Sat, 30 Jun 2007 13:55:49 -0400 Subject: How do I remotely access Scheduled Tasks from Windows XP to Windows Server 2003? References: <1183152711.161151.285960@i13g2000prf.googlegroups.com> Message-ID: <1183226243_18235@sp12lax.superfeed.net> "kj7ny" wrote: > How can I access and manipulate Scheduled Tasks in Windows using > Python? > > I have a Windows XP workstation running Python 2.4.4 using the > win32all modules to control the windows services on multiple Windows > 2003 servers. It works great. > > However, I also need to remotely collect the settings for the > scheduled tasks (on those same Windows 2003 servers) and then > manipulate those task settings. > > At the very least, I need to find out which ones are enabled and then > be able to disable and re-enable those tasks at will. It would be > better to be able to also detect the account each task runs as so that > I could only disable selected tasks, but I'll any help I can get. > > Thanks, > Pywin32 comes with a module that lets you do this, win32com.taskscheduler. You can use PyITaskScheduler.SetTargetComputer to access tasks on remote machines. Roger ----== Posted via Newsfeeds.Com - Unlimited-Unrestricted-Secure Usenet News==---- http://www.newsfeeds.com The #1 Newsgroup Service in the World! >100,000 Newsgroups ---= East/West-Coast Server Farms - Total Privacy via Encryption =--- From jadamson at partners.org Thu Jun 21 13:10:48 2007 From: jadamson at partners.org (Joel J. Adamson) Date: Thu, 21 Jun 2007 13:10:48 -0400 Subject: The Modernization of Emacs References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182370894.001918.36590@k79g2000hse.googlegroups.com> <1182372821.298343.316860@g4g2000hsf.googlegroups.com> <1182375321.067664.190780@o61g2000hsh.googlegroups.com> <86hcp1l6hb.fsf@lola.quinscape.zz> <86d4zpl5bz.fsf@lola.quinscape.zz> Message-ID: <871wg5b5d3.fsf@W0053328.mgh.harvard.edu> I just tried it: works for me. Joel David Kastrup writes: > Lew writes: > >> Bjorn Borud writes: >>>> so if the context was system administration, I'd vote for vi as >>>> well. if the context was programming I'd vote Emacs. >> >> David Kastrup wrote: >>> You know you can use something like >>> C-x C-f /su::/etc/fstab RET >>> (or /sudo::/etc/fstab) in order to edit files as root in a normal >>> Emacs session? >> >> I've been using emacs for something like twenty years and never knew >> that before. > > The package "tramp" will provide that (as well as editing files over > ssh, scp, rsync, telnet, plink...). It is already preinstalled in > Emacs 22.1, but can also be installed for earlier versions. > > -- > David Kastrup -- Joel J. Adamson Biostatistician Pediatric Psychopharmacology Research Unit Massachusetts General Hospital Boston, MA 02114 (617) 643-1432 (303) 880-3109 A webpage of interest: http://www.gnu.org/philosophy/sylvester-response.html From wgwigw at gmail.com Sat Jun 2 23:01:16 2007 From: wgwigw at gmail.com (momobear) Date: Sun, 03 Jun 2007 03:01:16 -0000 Subject: monitoring the filesystem for changes In-Reply-To: <1180796900.356829.31050@i13g2000prf.googlegroups.com> References: <1180796900.356829.31050@i13g2000prf.googlegroups.com> Message-ID: <1180839676.119233.199860@x35g2000prf.googlegroups.com> > i have designed a desktop search utility in python and a file system > monitoring using readdirectorychangesw from win32api but for eg. it > has a high cpu utilization (using a 2GHz processor). I don't think so. I just build a service to monitor a directory changes using readdirectorychangesw, the cpu usage is not above 1.9% for this service(my computer's cpu is 1.7GHz). if you still think 1.9% is high cpu utilization, I think you can use the c to implements this function, the cpu usage seems none for this application(I tried c dll solution first). Wish this help to you. Wang Wei From berteun at NO_SPAMdds.nl Thu Jun 28 05:19:20 2007 From: berteun at NO_SPAMdds.nl (Berteun Damman) Date: Thu, 28 Jun 2007 09:19:20 +0000 (UTC) Subject: textwrap and combining diacritical marks Message-ID: Hello, When using the textwrap module, the wrap will always use len() to determine the length of the string being wrapped. This might be a sensible thing to do in many circumstances, but I think there are circumstances where this does not lead to the desired result. I assume many applications of this module are found in applications where text is formatted to be presented to a user, e.g. a console application. The number of characters in the string, as determined by len() might not be the number of columns occupied. Some of the characters might be combining diacritical marks, which go on top of the previous character, i.e. the string de'ge'ne're' (where the ' indicate combing accute accents) will only display with a width of 8 characters. The string might also include some characters that'll switch the console to bold or underline mode, which have zero display width. If this happens a lot, the resuling text might seem very badly formatted because of all these zerowidth character-strings. It is of course impossible to handle all these scenario's in which some characters might influence the width of the displayed string, but wouldn't it be convenient to have a 'chunk_width' method or something which can be overridden in a derived class, so that a user might give a custom implementation? The default of this chunk_width might just be 'len()'. And that leasts to another question, does Python have a function akin to wcwidth() which gives the number of column positions a unicode character needs? Berteun