From steven at REMOVE.THIS.cybersource.com.au Thu Apr 1 00:28:32 2010 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 01 Apr 2010 04:28:32 GMT Subject: sorting ascending/descending with operator.attrgetter References: <96712ef1-5c10-455b-904c-c2436736c9d2@35g2000yqm.googlegroups.com> <4bb3d346$0$8827$c3e8da3@news.astraweb.com> Message-ID: On Wed, 31 Mar 2010 22:19:27 -0400, Steve Holden wrote: > Steven D'Aprano wrote: >> On Wed, 31 Mar 2010 17:21:18 -0700, Patrick Maupin wrote: >> >>> Doesn't matter though. The OP was sorting lists, not strings, so he >>> knew what I meant. >> >> I have found that when people ask basic questions about fundamental >> Python operations like sorting, it is risky to assume that they will >> know what I meant if I say something different. >> >> Since I've been on both the giving and receiving end of carelessly >> inaccurate answers, I know how frustrating it is to spend significant >> time trying to work out what I was doing wrong, only to be told much >> later "Oh, I meant you should do Y, not X. I thought you would >> understand what I meant." >> > But you surely will admit that you could be held to, well rather than > "be pedantic" perhaps we should say "tend towards the literal"? I wouldn't so much say "literal" as "precise". *wink* > I'm the same myself, and I know from personal experience that while I am > (simply?) seeking accuracy and truth it sometimes bugs the hell out of > people ... If you think I'm pedantic, you should see some of the guys I work with. I'm frequently on the receiving end of technical corrections. Yes, it's annoying to be in full flow explaining something, only to have somebody point out that you've made a silly mistake, or totally got something wrong, or what you've been calling a NAT device (including to the client) for a week is actually a NAS device *cough*. Annoying or not, if somebody had corrected me earlier, I wouldn't have looked quite so ignorant for quite so long, so all things considered I'd prefer to have my mistakes pointed out so I can stop making them. > It's a geek thing. Heavens, geeks on a programming forum! Who could possibly have expected such a thing? -- Steven From rantingrick at gmail.com Thu Apr 1 00:28:54 2010 From: rantingrick at gmail.com (rantingrick) Date: Wed, 31 Mar 2010 21:28:54 -0700 (PDT) Subject: Getting a Python program to run of off a flash drive? References: Message-ID: <06abf049-098b-4095-996b-619dacbe143d@r18g2000yqd.googlegroups.com> On Mar 31, 10:33?pm, a... at pythoncraft.com (Aahz) wrote: > In article , > Alf P. Steinbach wrote: > > > > >I think it was EMI who once distributed a nasty rootkit (and yes, it ? > >was theirs, it was not an accident) as a copy protection scheme on a ? > >music CD. ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? > > Sony, and I still (mostly) boycott Sony. ?(I buy no Sony hardware, but > because Sony owns a movie studio, it's a little more difficult to boycott > Sony DVDs.) Yea and i love how MS ships with autorun default to "ON" for EVERYTHING!. Not to mention remote registry, and many other atrocities. I have a whole list of unsafe settings i have to turn off evry time i do a clean install. Of course they *claim* it's because the lemmings are not smart enough to open "my computer" and double click the CD icon (which has *some* merits) but come on microsoft, with all the other crap you ship wide open don't play coy with us! And what did ever happen to Sony for such evil malware spreading practices, a slap on the wrist thats what, filthy pigs! From hidura at gmail.com Thu Apr 1 00:32:51 2010 From: hidura at gmail.com (hidura at gmail.com) Date: Thu, 01 Apr 2010 04:32:51 +0000 Subject: Fetch files from mail in python In-Reply-To: Message-ID: <0016e68de9f906ed590483255b7d@google.com> Ok, I will take your advice and implemented in my project. Thank you all for your help. On Mar 31, 2010 3:03am, Dennis Lee Bieber wrote: > On Wed, 31 Mar 2010 00:47:47 +0000, hidura at gmail.com declaimed the > following in gmane.comp.python.general: > > I did that but i want to know if i have a file inside the mail how > could i > > download that file from my mail. > Top posting is undesirable... > As for "downloading"... At least with POP3 (I don't do IMAP), there > is NO "downloading" -- all attachments come down with the message. > What you need to do is parse out the portion of the body that > contains the "attachment". > -- > Wulfraed Dennis Lee Bieber AF6VN > wlfraed at ix.netcom.com HTTP://wlfraed.home.netcom.com/" > eudora="autourl">HTTP://wlfraed.home.netcom.com/ > -- > http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- An HTML attachment was scrubbed... URL: From steven at REMOVE.THIS.cybersource.com.au Thu Apr 1 00:40:03 2010 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 01 Apr 2010 04:40:03 GMT Subject: sorting ascending/descending with operator.attrgetter References: <96712ef1-5c10-455b-904c-c2436736c9d2@35g2000yqm.googlegroups.com> <4bb3d346$0$8827$c3e8da3@news.astraweb.com> Message-ID: On Wed, 31 Mar 2010 22:19:27 -0400, Steve Holden wrote: > I'm the same myself, and I know from personal experience that while I am > (simply?) seeking accuracy and truth it sometimes bugs the hell out of > people ... By the way, why are we acting as if seeking accuracy and truth is a bad thing? Personally, if I were interviewing job applicants, one of the things I'd like to know is how well they react to criticism. This especially applies to technical and programming roles. I've managed thin-skinned prima donnas who spit the dummy if someone dares point out they made a mistake, and so long as I'm involved in the hiring process I won't be doing so again. Give me a pedantic, technically precise, obnoxiously *correct* coder over a sloppy one any time. -- Steven From ded.utility at gmail.com Thu Apr 1 00:40:56 2010 From: ded.utility at gmail.com (d d) Date: Thu, 1 Apr 2010 04:40:56 +0000 (UTC) Subject: how to build with --enable-shared so that binary knows where =?utf-8?b?CWxpYnJhcmllcw==?= are. References: Message-ID: d d gmail.com> writes: > I found this: > http://koansys.com/tech/building-python-with-enable-shared-in-non-standard-location > It recommends LDFLAGS="-rpath ", and mentions that you > get a "compiler cannot create executables" error unless you first > create the empty directory. But I get that error even when I do > create the empty directory. I typed -W1 instead of -Wl. Works now. :-) From pmaupin at gmail.com Thu Apr 1 00:54:40 2010 From: pmaupin at gmail.com (Patrick Maupin) Date: Wed, 31 Mar 2010 21:54:40 -0700 (PDT) Subject: sorting ascending/descending with operator.attrgetter References: <96712ef1-5c10-455b-904c-c2436736c9d2@35g2000yqm.googlegroups.com> <4bb3d346$0$8827$c3e8da3@news.astraweb.com> Message-ID: On Mar 31, 11:28?pm, Steven D'Aprano wrote: > I wouldn't so much say "literal" as "precise". Being precise in your own words is an admirable trait. Asking others to be more precise can be done politely when necessary, but in this case it obviously wasn't necessary, since even you, who deliberately misinterpret everything I write, knew that I was really talking about lists. > If you think I'm pedantic, you should see some of the guys I work with. I can well imagine that everybody who has to work with you thoroughly enjoys proving you wrong as often as possible. I would expect they are probably much gentler to each other in your absence. OTOH, if I am wrong, I certainly wouldn't last long there -- I've left less poisonous workplaces for less cause. > I'm frequently on the receiving end of technical corrections. Yes, it's > annoying to be in full flow explaining something, only to have somebody > point out that you've made a silly mistake, or totally got something > wrong, or what you've been calling a NAT device (including to the client) > for a week is actually a NAS device *cough*. Annoying or not, if somebody > had corrected me earlier, I wouldn't have looked quite so ignorant for > quite so long, so all things considered I'd prefer to have my mistakes > pointed out so I can stop making them. There is a (not very subtle) difference between saying "Oh, you meant a list, not a string" (especially when the context was a discussion of list processing), and printing a traceback for something that nobody was discussing, based on a single word slip. > > It's a geek thing. > > Heavens, geeks on a programming forum! Who could possibly have expected > such a thing? Mr. Holden was being unfailingly polite, in trying to point out that many individuals who have a reasonably high intellect, yet zero social skills, will gravitate toward technical fields. When he was asking you to admit that you "tend toward the literal" (which naturally you refused to do) I think he may have been trying to gently explain that introspection is not just for Python anymore. Regards, Pat From pmaupin at gmail.com Thu Apr 1 01:07:37 2010 From: pmaupin at gmail.com (Patrick Maupin) Date: Wed, 31 Mar 2010 22:07:37 -0700 (PDT) Subject: sorting ascending/descending with operator.attrgetter References: <96712ef1-5c10-455b-904c-c2436736c9d2@35g2000yqm.googlegroups.com> <4bb3d346$0$8827$c3e8da3@news.astraweb.com> Message-ID: <260f0d30-ceb0-4bf9-a1ef-6020f56b3261@g11g2000yqe.googlegroups.com> On Mar 31, 11:40?pm, Steven D'Aprano wrote: > By the way, why are we acting as if seeking accuracy and truth is a bad > thing? I don't think anybody is acting like that is a bad thing. It's all how you choose to interpret things. > Personally, if I were interviewing job applicants, one of the things I'd > like to know is how well they react to criticism. This especially applies > to technical and programming roles. I've managed thin-skinned prima > donnas who spit the dummy if someone dares point out they made a mistake, > and so long as I'm involved in the hiring process I won't be doing so > again. Give me a pedantic, technically precise, obnoxiously *correct* > coder over a sloppy one any time. It's interesting you should mention this. In my experience, the best coders accept criticism well, and aren't usually very critical themselves, except when asked to be. Also, they are usually capable of reading between the lines and discerning and appropriately reacting to subtle behavioral criticism, not just technical criticism. But then, I have the best boss and group of co-workers in the world, so what would I know? Regards, Pat From steve at holdenweb.com Thu Apr 1 01:50:02 2010 From: steve at holdenweb.com (Steve Holden) Date: Thu, 01 Apr 2010 01:50:02 -0400 Subject: sorting ascending/descending with operator.attrgetter In-Reply-To: References: <96712ef1-5c10-455b-904c-c2436736c9d2@35g2000yqm.googlegroups.com> <4bb3d346$0$8827$c3e8da3@news.astraweb.com> Message-ID: Patrick Maupin wrote: > On Mar 31, 11:28 pm, Steven D'Aprano > wrote: > >> I wouldn't so much say "literal" as "precise". > > Being precise in your own words is an admirable trait. Asking others > to be more precise can be done politely when necessary, but in this > case it obviously wasn't necessary, since even you, who deliberately > misinterpret everything I write, knew that I was really talking about > lists. > >> If you think I'm pedantic, you should see some of the guys I work >> with. > > I can well imagine that everybody who has to work with you thoroughly > enjoys proving you wrong as often as possible. I am glad I wasn't drinking when I read this. Liquid in one's nose is so uncomfortable. > I would expect they are probably much gentler to each other in your > absence. OTOH, if I am wrong, I certainly wouldn't last long there > -- I've left less poisonous workplaces for less cause. > >> I'm frequently on the receiving end of technical corrections. Yes, >> it's annoying to be in full flow explaining something, only to have >> somebody point out that you've made a silly mistake, or totally got >> something wrong, or what you've been calling a NAT device >> (including to the client) for a week is actually a NAS device >> *cough*. Annoying or not, if somebody had corrected me earlier, I >> wouldn't have looked quite so ignorant for quite so long, so all >> things considered I'd prefer to have my mistakes pointed out so I >> can stop making them. > > There is a (not very subtle) difference between saying "Oh, you meant > a list, not a string" (especially when the context was a discussion > of list processing), and printing a traceback for something that > nobody was discussing, based on a single word slip. > >>> It's a geek thing. >> Heavens, geeks on a programming forum! Who could possibly have >> expected such a thing? > > Mr. Holden was being unfailingly polite, in trying to point out that > many individuals who have a reasonably high intellect, yet zero > social skills, will gravitate toward technical fields. When he was > asking you to admit that you "tend toward the literal" (which > naturally you refused to do) I think he may have been trying to > gently explain that introspection is not just for Python anymore. > Nicely put (though I have to question the accuracy of "unfailingly polite" if it was intended as a generic description of my behavior. I guess we have to value the good that's in Steven (few would deny that he *is* technically very competent) and try and ignore his more annoying side. I have toyed many times with the idea of giving a presentation at PyCon called something like "Humanity 101". It would include such advice as "When I say 'use soap' I am not talking about the Simple Object Access Protocol" and "Being wrong is usually survivable; offending a homicidal maniac often isn't". Perhaps I should just add it to the Holden Web course schedule? regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 See PyCon Talks from Atlanta 2010 http://pycon.blip.tv/ Holden Web LLC http://www.holdenweb.com/ UPCOMING EVENTS: http://holdenweb.eventbrite.com/ From steve at holdenweb.com Thu Apr 1 01:54:39 2010 From: steve at holdenweb.com (Steve Holden) Date: Thu, 01 Apr 2010 01:54:39 -0400 Subject: sorting ascending/descending with operator.attrgetter In-Reply-To: References: <96712ef1-5c10-455b-904c-c2436736c9d2@35g2000yqm.googlegroups.com> <4bb3d346$0$8827$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano wrote: > On Wed, 31 Mar 2010 22:19:27 -0400, Steve Holden wrote: > >> I'm the same myself, and I know from personal experience that while I am >> (simply?) seeking accuracy and truth it sometimes bugs the hell out of >> people ... > > By the way, why are we acting as if seeking accuracy and truth is a bad > thing? > We aren't. Or, at least, I'm not trying to convey that. But you have to remember you aren't conversing with robots here. People have emotions, and they will affect the way they react to your utterances whether you like or not, and whether you think it's reasonable or not. > Personally, if I were interviewing job applicants, one of the things I'd > like to know is how well they react to criticism. This especially applies > to technical and programming roles. I've managed thin-skinned prima > donnas who spit the dummy if someone dares point out they made a mistake, > and so long as I'm involved in the hiring process I won't be doing so > again. Give me a pedantic, technically precise, obnoxiously *correct* > coder over a sloppy one any time. > As an employee, possibly (though the expense of stopping his colleagues from killing him may make the cost prohibitive). As a friend, one might be prepared to be forgiving. As a Usenet correspondent I find that too much pedantry becomes tiresome after a while, and can detract from the pleasures of the correspondence. It should hardly be necessary to point out that you *aren't* interviewing job applicants on c.l.py (or at least not overtly). regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 See PyCon Talks from Atlanta 2010 http://pycon.blip.tv/ Holden Web LLC http://www.holdenweb.com/ UPCOMING EVENTS: http://holdenweb.eventbrite.com/ From rami.chowdhury at gmail.com Thu Apr 1 02:02:20 2010 From: rami.chowdhury at gmail.com (Rami Chowdhury) Date: Wed, 31 Mar 2010 23:02:20 -0700 Subject: sorting ascending/descending with operator.attrgetter In-Reply-To: References: Message-ID: <201003312302.20809.rami.chowdhury@gmail.com> On Wednesday 31 March 2010 22:50:02 Steve Holden wrote: > "When I say 'use soap' "*use* soap"? Sounds awfully Perlish to me, perhaps you meant "import soap" ;-)? ---- Rami Chowdhury "Ninety percent of everything is crap." -- Sturgeon's Law 408-597-7068 (US) / 07875-841-046 (UK) / 01819-245544 (BD) From kse.listed.co1 at gmail.com Thu Apr 1 02:27:14 2010 From: kse.listed.co1 at gmail.com (Naeem) Date: Wed, 31 Mar 2010 23:27:14 -0700 (PDT) Subject: "jobs in australia" "jobs in australia for pakistanis" "jobs in australia melbourne" "jobs in australia for immigrants" "jobs in australia for international students" "jobs in australia for foreigners" ON http://jobsinaustralia-net.blogspot.com/ Message-ID: "jobs in australia" "jobs in australia for pakistanis" "jobs in australia melbourne" "jobs in australia for immigrants" "jobs in australia for international students" "jobs in australia for foreigners" ON http://jobsinaustralia-net.blogspot.com/ "jobs in australia" "jobs in australia for pakistanis" "jobs in australia melbourne" "jobs in australia for immigrants" "jobs in australia for international students" "jobs in australia for foreigners" ON http://jobsinaustralia-net.blogspot.com/ "jobs in australia" "jobs in australia for pakistanis" "jobs in australia melbourne" "jobs in australia for immigrants" "jobs in australia for international students" "jobs in australia for foreigners" ON http://jobsinaustralia-net.blogspot.com/ "jobs in australia" "jobs in australia for pakistanis" "jobs in australia melbourne" "jobs in australia for immigrants" "jobs in australia for international students" "jobs in australia for foreigners" ON http://jobsinaustralia-net.blogspot.com/ "jobs in australia" "jobs in australia for pakistanis" "jobs in australia melbourne" "jobs in australia for immigrants" "jobs in australia for international students" "jobs in australia for foreigners" ON http://jobsinaustralia-net.blogspot.com/ "jobs in australia" "jobs in australia for pakistanis" "jobs in australia melbourne" "jobs in australia for immigrants" "jobs in australia for international students" "jobs in australia for foreigners" ON http://jobsinaustralia-net.blogspot.com/ "jobs in australia" "jobs in australia for pakistanis" "jobs in australia melbourne" "jobs in australia for immigrants" "jobs in australia for international students" "jobs in australia for foreigners" ON http://jobsinaustralia-net.blogspot.com/ "jobs in australia" "jobs in australia for pakistanis" "jobs in australia melbourne" "jobs in australia for immigrants" "jobs in australia for international students" "jobs in australia for foreigners" ON http://jobsinaustralia-net.blogspot.com/ "jobs in australia" "jobs in australia for pakistanis" "jobs in australia melbourne" "jobs in australia for immigrants" "jobs in australia for international students" "jobs in australia for foreigners" ON http://jobsinaustralia-net.blogspot.com/ "jobs in australia" "jobs in australia for pakistanis" "jobs in australia melbourne" "jobs in australia for immigrants" "jobs in australia for international students" "jobs in australia for foreigners" ON http://jobsinaustralia-net.blogspot.com/ "jobs in australia" "jobs in australia for pakistanis" "jobs in australia melbourne" "jobs in australia for immigrants" "jobs in australia for international students" "jobs in australia for foreigners" ON http://jobsinaustralia-net.blogspot.com/ "jobs in australia" "jobs in australia for pakistanis" "jobs in australia melbourne" "jobs in australia for immigrants" "jobs in australia for international students" "jobs in australia for foreigners" ON http://jobsinaustralia-net.blogspot.com/ "jobs in australia" "jobs in australia for pakistanis" "jobs in australia melbourne" "jobs in australia for immigrants" "jobs in australia for international students" "jobs in australia for foreigners" ON http://jobsinaustralia-net.blogspot.com/ "jobs in australia" "jobs in australia for pakistanis" "jobs in australia melbourne" "jobs in australia for immigrants" "jobs in australia for international students" "jobs in australia for foreigners" ON http://jobsinaustralia-net.blogspot.com/ "jobs in australia" "jobs in australia for pakistanis" "jobs in australia melbourne" "jobs in australia for immigrants" "jobs in australia for international students" "jobs in australia for foreigners" ON http://jobsinaustralia-net.blogspot.com/ "jobs in australia" "jobs in australia for pakistanis" "jobs in australia melbourne" "jobs in australia for immigrants" "jobs in australia for international students" "jobs in australia for foreigners" ON http://jobsinaustralia-net.blogspot.com/ "jobs in australia" "jobs in australia for pakistanis" "jobs in australia melbourne" "jobs in australia for immigrants" "jobs in australia for international students" "jobs in australia for foreigners" ON http://jobsinaustralia-net.blogspot.com/ "jobs in australia" "jobs in australia for pakistanis" "jobs in australia melbourne" "jobs in australia for immigrants" "jobs in australia for international students" "jobs in australia for foreigners" ON http://jobsinaustralia-net.blogspot.com/ "jobs in australia" "jobs in australia for pakistanis" "jobs in australia melbourne" "jobs in australia for immigrants" "jobs in australia for international students" "jobs in australia for foreigners" ON http://jobsinaustralia-net.blogspot.com/ "jobs in australia" "jobs in australia for pakistanis" "jobs in australia melbourne" "jobs in australia for immigrants" "jobs in australia for international students" "jobs in australia for foreigners" ON http://jobsinaustralia-net.blogspot.com/ "jobs in australia" "jobs in australia for pakistanis" "jobs in australia melbourne" "jobs in australia for immigrants" "jobs in australia for international students" "jobs in australia for foreigners" ON http://jobsinaustralia-net.blogspot.com/ "jobs in australia" "jobs in australia for pakistanis" "jobs in australia melbourne" "jobs in australia for immigrants" "jobs in australia for international students" "jobs in australia for foreigners" ON http://jobsinaustralia-net.blogspot.com/ "jobs in australia" "jobs in australia for pakistanis" "jobs in australia melbourne" "jobs in australia for immigrants" "jobs in australia for international students" "jobs in australia for foreigners" ON http://jobsinaustralia-net.blogspot.com/ "jobs in australia" "jobs in australia for pakistanis" "jobs in australia melbourne" "jobs in australia for immigrants" "jobs in australia for international students" "jobs in australia for foreigners" ON http://jobsinaustralia-net.blogspot.com/ "jobs in australia" "jobs in australia for pakistanis" "jobs in australia melbourne" "jobs in australia for immigrants" "jobs in australia for international students" "jobs in australia for foreigners" ON http://jobsinaustralia-net.blogspot.com/ "jobs in australia" "jobs in australia for pakistanis" "jobs in australia melbourne" "jobs in australia for immigrants" "jobs in australia for international students" "jobs in australia for foreigners" ON http://jobsinaustralia-net.blogspot.com/ "jobs in australia" "jobs in australia for pakistanis" "jobs in australia melbourne" "jobs in australia for immigrants" "jobs in australia for international students" "jobs in australia for foreigners" ON http://jobsinaustralia-net.blogspot.com/ "jobs in australia" "jobs in australia for pakistanis" "jobs in australia melbourne" "jobs in australia for immigrants" "jobs in australia for international students" "jobs in australia for foreigners" ON http://jobsinaustralia-net.blogspot.com/ "jobs in australia" "jobs in australia for pakistanis" "jobs in australia melbourne" "jobs in australia for immigrants" "jobs in australia for international students" "jobs in australia for foreigners" ON http://jobsinaustralia-net.blogspot.com/ "jobs in australia" "jobs in australia for pakistanis" "jobs in australia melbourne" "jobs in australia for immigrants" "jobs in australia for international students" "jobs in australia for foreigners" ON http://jobsinaustralia-net.blogspot.com/ "jobs in australia" "jobs in australia for pakistanis" "jobs in australia melbourne" "jobs in australia for immigrants" "jobs in australia for international students" "jobs in australia for foreigners" ON http://jobsinaustralia-net.blogspot.com/ "jobs in australia" "jobs in australia for pakistanis" "jobs in australia melbourne" "jobs in australia for immigrants" "jobs in australia for international students" "jobs in australia for foreigners" ON http://jobsinaustralia-net.blogspot.com/ "jobs in australia" "jobs in australia for pakistanis" "jobs in australia melbourne" "jobs in australia for immigrants" "jobs in australia for international students" "jobs in australia for foreigners" ON http://jobsinaustralia-net.blogspot.com/ "jobs in australia" "jobs in australia for pakistanis" "jobs in australia melbourne" "jobs in australia for immigrants" "jobs in australia for international students" "jobs in australia for foreigners" ON http://jobsinaustralia-net.blogspot.com/ "jobs in australia" "jobs in australia for pakistanis" "jobs in australia melbourne" "jobs in australia for immigrants" "jobs in australia for international students" "jobs in australia for foreigners" ON http://jobsinaustralia-net.blogspot.com/ "jobs in australia" "jobs in australia for pakistanis" "jobs in australia melbourne" "jobs in australia for immigrants" "jobs in australia for international students" "jobs in australia for foreigners" ON http://jobsinaustralia-net.blogspot.com/ "jobs in australia" "jobs in australia for pakistanis" "jobs in australia melbourne" "jobs in australia for immigrants" "jobs in australia for international students" "jobs in australia for foreigners" ON http://jobsinaustralia-net.blogspot.com/ "jobs in australia" "jobs in australia for pakistanis" "jobs in australia melbourne" "jobs in australia for immigrants" "jobs in australia for international students" "jobs in australia for foreigners" ON http://jobsinaustralia-net.blogspot.com/ "jobs in australia" "jobs in australia for pakistanis" "jobs in australia melbourne" "jobs in australia for immigrants" "jobs in australia for international students" "jobs in australia for foreigners" ON http://jobsinaustralia-net.blogspot.com/ "jobs in australia" "jobs in australia for pakistanis" "jobs in australia melbourne" "jobs in australia for immigrants" "jobs in australia for international students" "jobs in australia for foreigners" ON http://jobsinaustralia-net.blogspot.com/ "jobs in australia" "jobs in australia for pakistanis" "jobs in australia melbourne" "jobs in australia for immigrants" "jobs in australia for international students" "jobs in australia for foreigners" ON http://jobsinaustralia-net.blogspot.com/ "jobs in australia" "jobs in australia for pakistanis" "jobs in australia melbourne" "jobs in australia for immigrants" "jobs in australia for international students" "jobs in australia for foreigners" ON http://jobsinaustralia-net.blogspot.com/ "jobs in australia" "jobs in australia for pakistanis" "jobs in australia melbourne" "jobs in australia for immigrants" "jobs in australia for international students" "jobs in australia for foreigners" ON http://jobsinaustralia-net.blogspot.com/ "jobs in australia" "jobs in australia for pakistanis" "jobs in australia melbourne" "jobs in australia for immigrants" "jobs in australia for international students" "jobs in australia for foreigners" ON http://jobsinaustralia-net.blogspot.com/ "jobs in australia" "jobs in australia for pakistanis" "jobs in australia melbourne" "jobs in australia for immigrants" "jobs in australia for international students" "jobs in australia for foreigners" ON http://jobsinaustralia-net.blogspot.com/ From steven at REMOVE.THIS.cybersource.com.au Thu Apr 1 02:54:42 2010 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 01 Apr 2010 06:54:42 GMT Subject: sorting ascending/descending with operator.attrgetter References: <96712ef1-5c10-455b-904c-c2436736c9d2@35g2000yqm.googlegroups.com> <4bb3d346$0$8827$c3e8da3@news.astraweb.com> Message-ID: On Wed, 31 Mar 2010 21:54:40 -0700, Patrick Maupin wrote: > There is a (not very subtle) difference between saying "Oh, you meant a > list, not a string" (especially when the context was a discussion of > list processing), and printing a traceback for something that nobody was > discussing, based on a single word slip. I wondered about that. I almost asked whether or not you would have reacted with less anger if I hadn't included the tracebacks, but decided against it. I thought that, given how you dropped a nuke on me for what was a very trivial social faux pas, you would probably interpret a question about the tracebacks as me being condescending and go on the attack yet again. So far you've dropped a ton of sarcasm on me for being "the smartest, sharpest guy in the world", accused me of "deliberately misinterpret[ing] everything [you] write", and declared that my work- mates (who you don't know) take great pleasure in putting me down. Such repeated attacks, over something as trivial as me pointing out you mistook list.sort for str.sort puts your comment: "I've left less poisonous workplaces for less cause." into a completely different perspective. How little a slight does it take for you to decide a workplace is poisonous? So, Patrick, here's how it goes: I won't apologize for pointing out your error, no matter how trivial, because I thought, and still do, that it muddied the waters and risked adding confusion rather than clarity to somebody asking a very basic question. And for all I knew, you may have been genuinely confused yourself, and not just making a silly typo. I will say that I regret including the tracebacks, not because there is anything wrong with doing so, but because they apparently caused you distress and I had no intention to do so. I am sorry that you took offense, it was not intended. At the risk of offending you further, I will suggest that I'm not the only one who needs to apply some introspection here. If your skin is so thin that you react so explosively to such a minor slight, how are you going to react to some of the more vigorous disagreements? -- Steven From timoverbeek10 at gmail.com Thu Apr 1 04:22:01 2010 From: timoverbeek10 at gmail.com (timo verbeek) Date: Thu, 1 Apr 2010 01:22:01 -0700 (PDT) Subject: Getting a Python program to run of off a flash drive? References: Message-ID: On Apr 1, 12:48?am, Abethebabe wrote: > I wanted to know if there was a way I could get a Python program to > run off of my flash drive as soon as the computer (Windows) detected > the device? > > For example I could have a a simple program that would create a text > document on the computers desktop when my flash drive is detected. You could use Autorun.inf if your using Windows but for linux I don't now From lacrima.maxim at gmail.com Thu Apr 1 05:08:57 2010 From: lacrima.maxim at gmail.com (Lacrima) Date: Thu, 1 Apr 2010 02:08:57 -0700 (PDT) Subject: String Formatting Operations for decimals. Message-ID: <5f6e9898-53c5-4a58-aee6-797bed53110e@x3g2000yqd.googlegroups.com> Hello! I need to format a decimal (floating point) number in the following way: 10 results in '10' 10.5 results in '10.5' 10.50 results in '10.5' 10.5678 results in 10.57 How can I achieve this using standard Python string formatting operations? Something like '%.2f' works almost as expected: >>> '%.2f' % 10.5 '10.50' >>> '%.2f' % 10.5678 '10.57' >>> '%.2f' % 10 '10.00' But I always need trailing zeros to be excluded, i.e. 10.5 should result in '10.5' (not '10.50'), and 10 should result in '10' (not '10.00'). So how can I do this? Sorry for my English. Thanks in advance. with regards, Maxim From clp2 at rebertia.com Thu Apr 1 05:14:45 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Thu, 1 Apr 2010 02:14:45 -0700 Subject: String Formatting Operations for decimals. In-Reply-To: <5f6e9898-53c5-4a58-aee6-797bed53110e@x3g2000yqd.googlegroups.com> References: <5f6e9898-53c5-4a58-aee6-797bed53110e@x3g2000yqd.googlegroups.com> Message-ID: On Thu, Apr 1, 2010 at 2:08 AM, Lacrima wrote: > Hello! > > I need to format a decimal (floating point) number in the following > way: > 10 results in '10' > 10.5 results in '10.5' > 10.50 results in '10.5' > 10.5678 results in 10.57 > > How can I achieve this using standard Python string formatting > operations? > Something like '%.2f' works almost as expected: >>>> '%.2f' % 10.5 > '10.50' >>>> '%.2f' % 10.5678 > '10.57' >>>> '%.2f' % 10 > '10.00' > But I always need trailing zeros to be excluded, i.e. 10.5 should > result in '10.5' (not '10.50'), and 10 should result in '10' (not > '10.00'). > So how can I do this? ('%.2f' % 10).rstrip('0').rstrip('.') Cheers, Chris -- http://blog.rebertia.com From contact at xavierho.com Thu Apr 1 05:15:23 2010 From: contact at xavierho.com (Xavier Ho) Date: Thu, 1 Apr 2010 19:15:23 +1000 Subject: String Formatting Operations for decimals. In-Reply-To: <5f6e9898-53c5-4a58-aee6-797bed53110e@x3g2000yqd.googlegroups.com> References: <5f6e9898-53c5-4a58-aee6-797bed53110e@x3g2000yqd.googlegroups.com> Message-ID: Hi Maxim, If it's the trailing zeroes you're concerned about, here's a work-around: >>> ('%.2f' % 10.5678).rstrip('0') '10.57 I'm sure there are better solutions. But this one works for your need, right? Cheers,' Ching-Yun Xavier Ho, Technical Artist Contact Information Mobile: (+61) 04 3335 4748 Skype ID: SpaXe85 Email: contact at xavierho.com Website: http://xavierho.com/ On Thu, Apr 1, 2010 at 7:08 PM, Lacrima wrote: > Hello! > > I need to format a decimal (floating point) number in the following > way: > 10 results in '10' > 10.5 results in '10.5' > 10.50 results in '10.5' > 10.5678 results in 10.57 > > How can I achieve this using standard Python string formatting > operations? > Something like '%.2f' works almost as expected: > >>> '%.2f' % 10.5 > '10.50' > >>> '%.2f' % 10.5678 > '10.57' > >>> '%.2f' % 10 > '10.00' > But I always need trailing zeros to be excluded, i.e. 10.5 should > result in '10.5' (not '10.50'), and 10 should result in '10' (not > '10.00'). > So how can I do this? > Sorry for my English. > Thanks in advance. > > with regards, > Maxim > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From gagsl-py2 at yahoo.com.ar Thu Apr 1 05:17:19 2010 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 01 Apr 2010 06:17:19 -0300 Subject: Generating text from a regular expression References: <829a8515-0c35-449e-abb9-2321092f2598@l25g2000yqd.googlegroups.com> Message-ID: En Wed, 31 Mar 2010 12:23:48 -0300, Paul McGuire escribi?: > On Mar 31, 5:49 am, Nathan Harmston > wrote: >> >> I have a slightly complicated/medium sized regular expression and I >> want to generate all possible words that it can match (to compare >> performance of regex against an acora based matcher). > > The pyparsing wiki Examples page includes this regex inverter: > http://pyparsing.wikispaces.com/file/view/invRegex.py > >> From the module header: > # Supports: > # - {n} and {m,n} repetition, but not unbounded + or * repetition > # - ? optional elements > # - [] character ranges > # - () grouping > # - | alternation I took the liberty of modifying your invRegex.py example, adding support for infinite repeaters. It depends on two other modules: mergeinf.py (from http://code.activestate.com/recipes/577041) provides the infinite merge operation. enumre.py provides the basic functions (merge, prod, repeat, closure) necessary to enumerate the language generated by a given regular expression, even if it contains unbounded repeaters like *,+. The key is to generate shorter strings before longer ones, so in 'a*|b*' it doesn't get stuck generating infinite a's before any b. By example, "(a|bc)*d" corresponds to this code: prod( closure( merge( 'a', prod('b','c'))), 'd') which returns an infinite generator starting with: d ad aad bcd aaad abcd bcad aaaad aabcd abcad bcaad bcbcd aaaaad aaabcd aabcad ... I got the idea from http://userweb.cs.utexas.edu/users/misra/Notes.dir/RegExp.pdf Finally, invRegexInf.py is based on your original regex parser. I only modified the generation part, taking advantage of the above infrastructure; the parser itself remains almost the same. It essentially saves oneself the very tedious work of converting a regular expression into the equivalent sequence of function calls as shown above. (I hope I got it right: I like pyparsing a lot and use it whenever I feel it's appropriate, but not as often as to remember the details...) -- Gabriel Genellina -------------- next part -------------- A non-text attachment was scrubbed... Name: invRegexInf.py Type: application/octet-stream Size: 7691 bytes Desc: not available URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: enumre.py Type: application/octet-stream Size: 10669 bytes Desc: not available URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: mergeinf.py Type: application/octet-stream Size: 4546 bytes Desc: not available URL: From lacrima.maxim at gmail.com Thu Apr 1 05:24:07 2010 From: lacrima.maxim at gmail.com (Maxim Lacrima) Date: Thu, 1 Apr 2010 12:24:07 +0300 Subject: String Formatting Operations for decimals. In-Reply-To: References: <5f6e9898-53c5-4a58-aee6-797bed53110e@x3g2000yqd.googlegroups.com> Message-ID: Hello, Chris! Thanks for your really quick reply! It works! On 1 April 2010 12:14, Chris Rebert wrote: > On Thu, Apr 1, 2010 at 2:08 AM, Lacrima wrote: > > Hello! > > > > I need to format a decimal (floating point) number in the following > > way: > > 10 results in '10' > > 10.5 results in '10.5' > > 10.50 results in '10.5' > > 10.5678 results in 10.57 > > > > How can I achieve this using standard Python string formatting > > operations? > > Something like '%.2f' works almost as expected: > >>>> '%.2f' % 10.5 > > '10.50' > >>>> '%.2f' % 10.5678 > > '10.57' > >>>> '%.2f' % 10 > > '10.00' > > But I always need trailing zeros to be excluded, i.e. 10.5 should > > result in '10.5' (not '10.50'), and 10 should result in '10' (not > > '10.00'). > > So how can I do this? > > ('%.2f' % 10).rstrip('0').rstrip('.') > > Cheers, > Chris > -- > http://blog.rebertia.com > -- with regards, Maxim -------------- next part -------------- An HTML attachment was scrubbed... URL: From eglyph at gmail.com Thu Apr 1 05:38:44 2010 From: eglyph at gmail.com (eglyph at gmail.com) Date: Thu, 1 Apr 2010 02:38:44 -0700 (PDT) Subject: Python + OpenOffice Calc References: <4bb2fe14$0$1120$4fafbaef@reader3.news.tin.it> Message-ID: On Apr 1, 6:53?am, rantingrick wrote: > > 3 fields: quantity - description of the piece bought - price > > So what is your plan...? > ? * Pop up a dialog with three entrys, > ? * have him fill out the three entrys, > ? * then have python insert the data into the spreadsheet? > ...Why bother messing with OO, too much trouble for me? Totally agree with you. No need for a heavy machinery in this case. > Then just save all the data as csv and you > can always load it into a spreadsheet later if the IRS comes knocking, > or you need to print a professional looking spreadsheet ;-). ?Simple, > 100% python solution! Actually, a spreadsheet based solution isn't best fit for such a task. I'd recommend to store the data in sqlite3 (also 100% pure python as the module is in the stdlib). CSV is good for making invoices or something like that. From J.Fine at open.ac.uk Thu Apr 1 05:57:01 2010 From: J.Fine at open.ac.uk (Jonathan Fine) Date: Thu, 01 Apr 2010 10:57:01 +0100 Subject: Q: We have *args and **kwargs. Woud ***allargs be useful? Message-ID: The idioms def f(*args, **kwargs): # Do something. and args = (1, 2, 3) kwargs = dict(a=4, b=5) g(*args, **kwargs) are often useful in Python. I'm finding myself picking up /all/ the arguments and storing them for later use (as part of a testing framework). So for me it would be nice if I could write def f(***allargs): args, kwargs = allargs # Continue as before. However, if we do this then 'args' in '*args' is misleading. So I'll use 'sargs' (for sequence arguments) instead. I can now write, for a suitable class Args args = Args(1, 2, 3, a=4, b=5) g(***args) # Same as before. sargs, kwargs = args g(*sargs, **kwargs) # Same as before. Even better, now that Args is a class we can give it a method 'call' so that args.call(g) is equivalent to g(***args) which removes the need for the *** construct. This reminds me of functools.partial except, of course, we've fixed all the arguments and left the passing of the function for later, whereas in partial we fix the function and some of the arguments. http://docs.python.org/library/functools.html#functools.partial My view are that 1. Conceptually ***allargs is useful, but an Args class would be more useful (not that it need be either-or). 2. If Args were built in , there could be performance benefits. 3. It's clearer to write def(*seqargs, **kwargs): than def(*args, **kwargs): 4. When the Args class is used a lot, one might welcome def(***args): # Do something with args. as a shortcut (and minor speedup) for def(*seqargs, **kwargs): args = Args(*seqargs, **kwargs) # Do something with args. I look forward to your comments on this. -- Jonathan From infotechsys at fairpoint.net Thu Apr 1 06:34:02 2010 From: infotechsys at fairpoint.net (Wayne) Date: Thu, 01 Apr 2010 06:34:02 -0400 Subject: Developement Question? Message-ID: <1270118042.3223.16.camel@wayne-desktop> My town office uses Microsoft operating system. They have a proprietary accounting system that uses excel for their accounting reports. I would like to read these report and reproduce the report so that the report can be seen on the web. I was thinking about using xlrd and xlwt along with some sort of software for building the web pages. I use linux only and do not use Microsoft. Q. Does python have to be installed on there computer to run the script? Q. Am I approaching this the wrong way? If so, what would be a better approach? From eryan.yu at gmail.com Thu Apr 1 06:56:05 2010 From: eryan.yu at gmail.com (Mister Yu) Date: Thu, 1 Apr 2010 03:56:05 -0700 (PDT) Subject: newbie with a encoding question, please help Message-ID: <23c7d677-dd66-4ef1-8032-5f39dc74b18e@z3g2000yqz.googlegroups.com> hi experts, i m new to python, i m writing crawlers to extract data from some chinese websites, and i run into a encoding problem. i have a unicode object, which looks like this u'\xd6\xd0\xce\xc4' which is encoded in "gb2312", but i have no idea of how to convert it back to utf-8 to re-create this one is easy: this will work ============================ >>> su = u"??".encode('gb2312') >>> su u >>> print su.decode('gb2312') ?? -> (same as the original string) ============================ but this doesn't,why =========================== >>> su = u'\xd6\xd0\xce\xc4' >>> su u'\xd6\xd0\xce\xc4' >>> print su.decode('gb2312') Traceback (most recent call last): File "", line 1, in UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-3: ordinal not in range(128) =========================== thank you From jmontoyaz at gmail.com Thu Apr 1 06:58:51 2010 From: jmontoyaz at gmail.com (Javier Montoya) Date: Thu, 1 Apr 2010 03:58:51 -0700 (PDT) Subject: associative array References: Message-ID: On Mar 31, 7:36?pm, Gary Herron wrote: > JavierMontoyawrote: > > Dear all, > > > I'm a newbie in python and would be acknowledge if somebody could shed > > some light on associative arrays. > > More precisely, I would like to create a multi-dimensional associative > > array. I have for example a list of students which are identified > > uniquely by their student IDs. Additionally, for each student I have > > some information: FirstName, LastName, etc. > > > The array would have then the following form: > > [StudentID] => [FirstName][LastName][Telephone]...[ ... ] > > > I would like to be able to access a field directly by using a > > StudentID > > [StudentID][FirstName] > > [StudentID][LastName] > > > How could I manipulate such an array (create the array, add elements, > > access data)? > > > Best wishes > > Create a class for student with attributes for ID, FirstName, LastName, etc. > > ? class Student: > ? ? ? def __init__(self, id, FirstName, ...): > ? ? ? ? ? self.id = id > ? ? ? ? ? self.FirstName = FirstName > ? ? ? ? ? ... > > then whenever you create a student object, use a dictionary to associate > the object with its is > ? AA = {} # An empty dictionary > ? s = Student(...) > ? AA[s.id] = s > ? ... and repeat for many students... > > Then to access a student's object given an id: > ? s = AA[id] > ? print s.id, s.FirstName, s.LastName, ... > > I'd *not* call this a multi-dimension association, but rather just an > association between student objects and their ids. > > Hope that helps, > > Gary Herron > > -- > Gary Herron, PhD. > Department of Computer Science > DigiPen Institute of Technology > (425) 895-4418 Dear all, Thanks for your suggestions, it worked! As Gary suggested, I created a 'student' class and mapped its objects to a dictionary. Is it possible to sort the dictionary by the student's grades in descending order? Best wishes From clp2 at rebertia.com Thu Apr 1 07:10:42 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Thu, 1 Apr 2010 04:10:42 -0700 Subject: associative array In-Reply-To: References: Message-ID: On Thu, Apr 1, 2010 at 3:58 AM, Javier Montoya wrote: > On Mar 31, 7:36?pm, Gary Herron wrote: >> JavierMontoyawrote: >> > Dear all, >> >> > I'm a newbie in python and would be acknowledge if somebody could shed >> > some light on associative arrays. >> > More precisely, I would like to create a multi-dimensional associative >> > array. I have for example a list of students which are identified >> > uniquely by their student IDs. Additionally, for each student I have >> > some information: FirstName, LastName, etc. >> >> > The array would have then the following form: >> > [StudentID] => [FirstName][LastName][Telephone]...[ ... ] >> >> > I would like to be able to access a field directly by using a >> > StudentID >> > [StudentID][FirstName] >> > [StudentID][LastName] >> >> > How could I manipulate such an array (create the array, add elements, >> > access data)? >> >> > Best wishes >> >> Create a class for student with attributes for ID, FirstName, LastName, etc. >> >> ? class Student: >> ? ? ? def __init__(self, id, FirstName, ...): >> ? ? ? ? ? self.id = id >> ? ? ? ? ? self.FirstName = FirstName >> ? ? ? ? ? ... >> >> then whenever you create a student object, use a dictionary to associate >> the object with its is >> ? AA = {} # An empty dictionary >> ? s = Student(...) >> ? AA[s.id] = s >> ? ... and repeat for many students... >> >> Then to access a student's object given an id: >> ? s = AA[id] >> ? print s.id, s.FirstName, s.LastName, ... >> >> I'd *not* call this a multi-dimension association, but rather just an >> association between student objects and their ids. >> >> Hope that helps, >> >> Gary Herron >> >> -- >> Gary Herron, PhD. >> Department of Computer Science >> DigiPen Institute of Technology >> (425) 895-4418 > > Dear all, > > Thanks for your suggestions, it worked! As Gary suggested, I created a > 'student' class and mapped its objects to a dictionary. > Is it possible to sort the dictionary by the student's grades in > descending order? Dictionaries are not ordered collections, so they themselves cannot be sorted. However, if you want a list of students sorted in the manner you stated: class_rank = list(garys_dictionary.values()) class_rank.sort(key=lambda student: student.grade, reverse=True) Cheers, Chris -- http://blog.rebertia.com From __peter__ at web.de Thu Apr 1 07:20:57 2010 From: __peter__ at web.de (Peter Otten) Date: Thu, 01 Apr 2010 13:20:57 +0200 Subject: associative array References: Message-ID: Javier Montoya wrote: > Is it possible to sort the dictionary by the student's grades in > descending order? You cannot sort dictionaries, but you can put dictionary items into a list and then sort that. Assumming that you have a dictionary student_dict that maps student IDs to Student instances and a function get_grade() to find a student's grade you'd do def get_grade(student): return course[student.student_id].grade # or whatever it takes students_by_grade = sorted(student_dict.itervalues(), key=get_grade, reverse=True) for student in students_by_grade: print student.first_name, student.last_name However, problems like the above are normally handled best using a SQL database, so I recommend that you have a look at http://docs.python.org/library/sqlite3.html Peter From clp2 at rebertia.com Thu Apr 1 07:22:01 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Thu, 1 Apr 2010 04:22:01 -0700 Subject: newbie with a encoding question, please help In-Reply-To: <23c7d677-dd66-4ef1-8032-5f39dc74b18e@z3g2000yqz.googlegroups.com> References: <23c7d677-dd66-4ef1-8032-5f39dc74b18e@z3g2000yqz.googlegroups.com> Message-ID: 2010/4/1 Mister Yu : > hi experts, > > i m new to python, i m writing crawlers to extract data from some > chinese websites, and i run into a encoding problem. > > i have a unicode object, which looks like this u'\xd6\xd0\xce\xc4' > which is encoded in "gb2312", No! Instances of type 'unicode' (i.e. strings with a leading 'u') ***aren't encoded at all***. > but i have no idea of how to convert it > back to utf-8 To convert u'\xd6\xd0\xce\xc4' to UTF-8, do u'\xd6\xd0\xce\xc4'.encode('utf-8') > to re-create this one is easy: > > this will work > ============================ >>>> su = u"??".encode('gb2312') >>>> su > u >>>> print su.decode('gb2312') > ?? ? ?-> (same as the original string) > > ============================ > but this doesn't,why > =========================== >>>> su = u'\xd6\xd0\xce\xc4' >>>> su > u'\xd6\xd0\xce\xc4' >>>> print su.decode('gb2312') You can't decode a unicode string, it's already been decoded! One decodes a bytestring to get a unicode string. One **encodes** a unicode string to get a bytestring. So the last line of your example should be: print su.encode('gb2312') Only call .encode() on things of type 'unicode'. Only call .decode() on things of type 'str'. [When using Python 2.x that is. Python 3.x renames the types in question.] Cheers, Chris -- http://blog.rebertia.com From eryan.yu at gmail.com Thu Apr 1 07:38:41 2010 From: eryan.yu at gmail.com (Mister Yu) Date: Thu, 1 Apr 2010 04:38:41 -0700 (PDT) Subject: newbie with a encoding question, please help References: <23c7d677-dd66-4ef1-8032-5f39dc74b18e@z3g2000yqz.googlegroups.com> Message-ID: On Apr 1, 7:22?pm, Chris Rebert wrote: > 2010/4/1 Mister Yu : > > > hi experts, > > > i m new to python, i m writing crawlers to extract data from some > > chinese websites, and i run into a encoding problem. > > > i have a unicode object, which looks like this u'\xd6\xd0\xce\xc4' > > which is encoded in "gb2312", > > No! Instances of type 'unicode' (i.e. strings with a leading 'u') > ***aren't encoded at all***. > > > but i have no idea of how to convert it > > back to utf-8 > > To convert u'\xd6\xd0\xce\xc4' to UTF-8, do u'\xd6\xd0\xce\xc4'.encode('utf-8') > > > > > to re-create this one is easy: > > > this will work > > ============================ > >>>> su = u"??".encode('gb2312') > >>>> su > > u > >>>> print su.decode('gb2312') > > ?? ? ?-> (same as the original string) > > > ============================ > > but this doesn't,why > > =========================== > >>>> su = u'\xd6\xd0\xce\xc4' > >>>> su > > u'\xd6\xd0\xce\xc4' > >>>> print su.decode('gb2312') > > You can't decode a unicode string, it's already been decoded! > > One decodes a bytestring to get a unicode string. > One **encodes** a unicode string to get a bytestring. > > So the last line of your example should be: > print su.encode('gb2312') > > Only call .encode() on things of type 'unicode'. > Only call .decode() on things of type 'str'. > [When using Python 2.x that is. Python 3.x renames the types in question.] > > Cheers, > Chris > --http://blog.rebertia.com hi, thanks for the tips. but i m still not very sure how to convert a unicode object ** u'\xd6\xd0\xce\xc4 ** back to "??" the string it supposed to be? thanks. sorry i m really new to python. From v.harishankar at gmail.com Thu Apr 1 07:57:11 2010 From: v.harishankar at gmail.com (Harishankar) Date: Thu, 1 Apr 2010 11:57:11 +0000 (UTC) Subject: associative array References: Message-ID: On Wed, 31 Mar 2010 09:40:30 -0700, Javier Montoya wrote: > Dear all, > > I'm a newbie in python and would be acknowledge if somebody could shed > some light on associative arrays. > More precisely, I would like to create a multi-dimensional associative > array. I have for example a list of students which are identified > uniquely by their student IDs. Additionally, for each student I have > some information: FirstName, LastName, etc. > > The array would have then the following form: [StudentID] => > [FirstName][LastName][Telephone]...[ ... ] > > I would like to be able to access a field directly by using a StudentID > [StudentID][FirstName] > [StudentID][LastName] > > How could I manipulate such an array (create the array, add elements, > access data)? > > Best wishes I know this is not a direct answer, but in your case I would probably use a database, because it is the easiest and most standardized way to access such types of data. If you don't want something heavyweight, use sqlite with in-memory databases/persistent file. Look at sqlite3 module in python. -- Harishankar (http://harishankar.org http://literaryforums.org) From clp2 at rebertia.com Thu Apr 1 08:13:45 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Thu, 1 Apr 2010 05:13:45 -0700 Subject: newbie with a encoding question, please help In-Reply-To: References: <23c7d677-dd66-4ef1-8032-5f39dc74b18e@z3g2000yqz.googlegroups.com> Message-ID: On Thu, Apr 1, 2010 at 4:38 AM, Mister Yu wrote: > On Apr 1, 7:22?pm, Chris Rebert wrote: >> 2010/4/1 Mister Yu : >> > hi experts, >> >> > i m new to python, i m writing crawlers to extract data from some >> > chinese websites, and i run into a encoding problem. >> >> > i have a unicode object, which looks like this u'\xd6\xd0\xce\xc4' >> > which is encoded in "gb2312", > hi, thanks for the tips. > > but i m still not very sure how to convert a unicode object ?** > u'\xd6\xd0\xce\xc4 ** back to "??" the string it supposed to be? Ah, my apologies! I overlooked something (sorry, it's early in the morning where I am). What you have there is ***really*** screwy. It's the 2 Chinese characters, encoded in gb2312, and then somehow cast *directly* into a 'unicode' string (which ought never to be done). In answer to your original question (after some experimentation): gb2312_bytes = ''.join([chr(ord(c)) for c in u'\xd6\xd0\xce\xc4']) unicode_string = gb2312_bytes.decode('gb2312') utf8_bytes = unicode_string.encode('utf-8') #as you wanted If possible, I'd look at the code that's giving you that funky "string" in the first place and see if it can be fixed to give you either a proper bytestring or proper unicode string rather than the bastardized mess you're currently having to deal with. Apologies again and Cheers, Chris -- http://blog.rebertia.com From stefan_ml at behnel.de Thu Apr 1 08:16:01 2010 From: stefan_ml at behnel.de (Stefan Behnel) Date: Thu, 01 Apr 2010 14:16:01 +0200 Subject: newbie with a encoding question, please help In-Reply-To: References: <23c7d677-dd66-4ef1-8032-5f39dc74b18e@z3g2000yqz.googlegroups.com> Message-ID: Mister Yu, 01.04.2010 13:38: > i m still not very sure how to convert a unicode object ** > u'\xd6\xd0\xce\xc4 ** back to "??" the string it supposed to be? You are confused. '\xd6\xd0\xce\xc4' is an encoded byte string, not a unicode string. The fact that you have it stored in a unicode string implies that something in your code (or in a library) has done an incorrect conversion from bytes to unicode that did not take into account the real character set in use. So you end up with a completely meaningless unicode string. Please show us the code that does the conversion to a unicode string. Stefan From eryan.yu at gmail.com Thu Apr 1 08:26:23 2010 From: eryan.yu at gmail.com (Mister Yu) Date: Thu, 1 Apr 2010 05:26:23 -0700 (PDT) Subject: newbie with a encoding question, please help References: <23c7d677-dd66-4ef1-8032-5f39dc74b18e@z3g2000yqz.googlegroups.com> Message-ID: On Apr 1, 8:13?pm, Chris Rebert wrote: > On Thu, Apr 1, 2010 at 4:38 AM, Mister Yu wrote: > > On Apr 1, 7:22?pm, Chris Rebert wrote: > >> 2010/4/1 Mister Yu : > >> > hi experts, > > >> > i m new to python, i m writing crawlers to extract data from some > >> > chinese websites, and i run into a encoding problem. > > >> > i have a unicode object, which looks like this u'\xd6\xd0\xce\xc4' > >> > which is encoded in "gb2312", > > > hi, thanks for the tips. > > > but i m still not very sure how to convert a unicode object ?** > > u'\xd6\xd0\xce\xc4 ** back to "??" the string it supposed to be? > > Ah, my apologies! I overlooked something (sorry, it's early in the > morning where I am). > What you have there is ***really*** screwy. It's the 2 Chinese > characters, encoded in gb2312, and then somehow cast *directly* into a > 'unicode' string (which ought never to be done). > > In answer to your original question (after some experimentation): > gb2312_bytes = ''.join([chr(ord(c)) for c in u'\xd6\xd0\xce\xc4']) > unicode_string = gb2312_bytes.decode('gb2312') > utf8_bytes = unicode_string.encode('utf-8') #as you wanted > > If possible, I'd look at the code that's giving you that funky > "string" in the first place and see if it can be fixed to give you > either a proper bytestring or proper unicode string rather than the > bastardized mess you're currently having to deal with. > > Apologies again and Cheers, > Chris > --http://blog.rebertia.com Hi Chris, thanks for the great tips! it works like a charm. i m using the Scrapy project(http://doc.scrapy.org/intro/ tutorial.html) to write my crawler, when it extract data with xpath, it puts the chinese characters directly into the unicode object. thanks again chris, and have a good april fool day. Cheers, Yu From python at mrabarnett.plus.com Thu Apr 1 08:54:49 2010 From: python at mrabarnett.plus.com (MRAB) Date: Thu, 01 Apr 2010 13:54:49 +0100 Subject: decorators only when __debug__ == True In-Reply-To: References: <7778821c-84f3-4829-8e05-85134c5d6c5b@y17g2000yqd.googlegroups.com> <4bb3d27f$0$8827$c3e8da3@news.astraweb.com> Message-ID: <4BB49799.1040100@mrabarnett.plus.com> Steven D'Aprano wrote: > On Thu, 01 Apr 2010 00:27:51 +0100, MRAB wrote: > >>>> A decorator shouldn't call the function it's decorating. >>> *raises eyebrow* >>> >>> Surely, in the general case, a decorator SHOULD call the function it is >>> decorating? I'm sure you know that, but your wording is funny and could >>> confuse the OP. >>> >> What I mean is that the function that's doing the decorating shouldn't >> call the function; it's the locally-defined wrapper function that calls >> the decorated function. > > Ah, gotcha, that makes sense. Now I understand the distinction you were > making. Thank you for the clarification. > I had the following idea: define the terms 'decorator', 'decoration' and 'decoratee'. The decorator applies the decoration to the decoratee. The decoratee is the function defined locally in the decorator. From python at mrabarnett.plus.com Thu Apr 1 08:58:36 2010 From: python at mrabarnett.plus.com (MRAB) Date: Thu, 01 Apr 2010 13:58:36 +0100 Subject: Developement Question? In-Reply-To: <1270118042.3223.16.camel@wayne-desktop> References: <1270118042.3223.16.camel@wayne-desktop> Message-ID: <4BB4987C.5080209@mrabarnett.plus.com> Wayne wrote: > My town office uses Microsoft operating system. They have a proprietary > accounting system that uses excel for their accounting reports. > I would like to read these report and reproduce the report so that > the report can be seen on the web. I was thinking about using xlrd and > xlwt along with some sort of software for building the web pages. I > use linux only and do not use Microsoft. > Q. Does python have to be installed on there computer to run the script? > If you can copy the spreadsheet files to your machine then you can run the script on your machine. > Q. Am I approaching this the wrong way? If so, what would be a better > approach? > From steve at holdenweb.com Thu Apr 1 09:16:29 2010 From: steve at holdenweb.com (Steve Holden) Date: Thu, 01 Apr 2010 09:16:29 -0400 Subject: decorators only when __debug__ == True In-Reply-To: <4BB49799.1040100@mrabarnett.plus.com> References: <7778821c-84f3-4829-8e05-85134c5d6c5b@y17g2000yqd.googlegroups.com> <4bb3d27f$0$8827$c3e8da3@news.astraweb.com> <4BB49799.1040100@mrabarnett.plus.com> Message-ID: MRAB wrote: > Steven D'Aprano wrote: >> On Thu, 01 Apr 2010 00:27:51 +0100, MRAB wrote: >> >>>>> A decorator shouldn't call the function it's decorating. >>>> *raises eyebrow* >>>> >>>> Surely, in the general case, a decorator SHOULD call the function it is >>>> decorating? I'm sure you know that, but your wording is funny and could >>>> confuse the OP. >>>> >>> What I mean is that the function that's doing the decorating shouldn't >>> call the function; it's the locally-defined wrapper function that calls >>> the decorated function. >> >> Ah, gotcha, that makes sense. Now I understand the distinction you >> were making. Thank you for the clarification. >> > I had the following idea: define the terms 'decorator', 'decoration' and > 'decoratee'. The decorator applies the decoration to the decoratee. The > decoratee is the function defined locally in the decorator. It would make more sense (to me, at least) if the decoratee were the function passed as an argument to the decorator. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 See PyCon Talks from Atlanta 2010 http://pycon.blip.tv/ Holden Web LLC http://www.holdenweb.com/ UPCOMING EVENTS: http://holdenweb.eventbrite.com/ From stefan_ml at behnel.de Thu Apr 1 09:31:08 2010 From: stefan_ml at behnel.de (Stefan Behnel) Date: Thu, 01 Apr 2010 15:31:08 +0200 Subject: newbie with a encoding question, please help In-Reply-To: References: <23c7d677-dd66-4ef1-8032-5f39dc74b18e@z3g2000yqz.googlegroups.com> Message-ID: Mister Yu, 01.04.2010 14:26: > On Apr 1, 8:13 pm, Chris Rebert wrote: >> gb2312_bytes = ''.join([chr(ord(c)) for c in u'\xd6\xd0\xce\xc4']) >> unicode_string = gb2312_bytes.decode('gb2312') >> utf8_bytes = unicode_string.encode('utf-8') #as you wanted Simplifying this hack a bit: gb2312_bytes = u'\xd6\xd0\xce\xc4'.encode('ISO-8859-1') unicode_string = gb2312_bytes.decode('gb2312') utf8_bytes = unicode_string.encode('utf-8') Although I have to wonder why you want a UTF-8 encoded byte string as output instead of Unicode. >> If possible, I'd look at the code that's giving you that funky >> "string" in the first place and see if it can be fixed to give you >> either a proper bytestring or proper unicode string rather than the >> bastardized mess you're currently having to deal with. > > thanks for the great tips! it works like a charm. I hope you're aware that it's a big ugly hack, though. You should really try to fix your input instead. > i m using the Scrapy project(http://doc.scrapy.org/intro/ > tutorial.html) to write my crawler, when it extract data with xpath, > it puts the chinese characters directly into the unicode object. My guess is that the HTML page you are parsing is broken and doesn't specify its encoding. In that case, all that scrapy can do is guess, and it seems to have guessed incorrectly. You should check if there is a way to tell scrapy about the expected page encoding, so that it can return correctly decoded unicode strings directly, instead of resorting to dirty hacks that may or may not work depending on the page you are parsing. Stefan From ethan at stoneleaf.us Thu Apr 1 09:46:33 2010 From: ethan at stoneleaf.us (Ethan Furman) Date: Thu, 01 Apr 2010 06:46:33 -0700 Subject: Python 3.1, object, and setattr() Message-ID: <4BB4A3B9.8010709@stoneleaf.us> Greetings! Perhaps I woke up too early this morning, but this behaviour has me baffled: Python 3.1.1 (r311:74483, Aug 17 2009, 17:02:12) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. --> test = object() --> setattr(test, 'example', 123) Traceback (most recent call last): File "", line 1, in AttributeError: 'object' object has no attribute 'example' Shouldn't setattr() be creating the 'example' attribute? Any tips greatly appreciated! ~Ethan~ From pmaupin at gmail.com Thu Apr 1 10:00:03 2010 From: pmaupin at gmail.com (Patrick Maupin) Date: Thu, 1 Apr 2010 07:00:03 -0700 (PDT) Subject: sorting ascending/descending with operator.attrgetter References: <96712ef1-5c10-455b-904c-c2436736c9d2@35g2000yqm.googlegroups.com> <4bb3d346$0$8827$c3e8da3@news.astraweb.com> Message-ID: On Apr 1, 1:54?am, Steven D'Aprano wrote: > At the risk of offending you further, I will suggest that I'm not the > only one who needs to apply some introspection here. If your skin is so > thin that you react so explosively to such a minor slight, how are you > going to react to some of the more vigorous disagreements? I think, if you go back and read other threads, you will find that a) I react fine to even very vigorous technical disagreements, and b) my reaction to you in particular (which, yes, introspection does show that I need to not react right away) is because of an induced sensitivity. Perhaps I'll see my allergist. Regards, Pat From showell30 at yahoo.com Thu Apr 1 10:07:53 2010 From: showell30 at yahoo.com (Steve Howell) Date: Thu, 1 Apr 2010 07:07:53 -0700 (PDT) Subject: decorators only when __debug__ == True References: <7778821c-84f3-4829-8e05-85134c5d6c5b@y17g2000yqd.googlegroups.com> <4bb3d27f$0$8827$c3e8da3@news.astraweb.com> <4BB49799.1040100@mrabarnett.plus.com> Message-ID: <8b2f6378-fe6f-4f9e-8798-45ec613c67f5@n34g2000yqb.googlegroups.com> On Apr 1, 6:16?am, Steve Holden wrote: > MRAB wrote: > > > I had the following idea: define the terms 'decorator', 'decoration' and > > 'decoratee'. The decorator applies the decoration to the decoratee. The > > decoratee is the function defined locally in the decorator. > > It would make more sense (to me, at least) if the decoratee were the > function passed as an argument to the decorator. > Me too. I do like the idea of coming up with a consistent terminology. From showell30 at yahoo.com Thu Apr 1 10:16:26 2010 From: showell30 at yahoo.com (Steve Howell) Date: Thu, 1 Apr 2010 07:16:26 -0700 (PDT) Subject: Python 3.1, object, and setattr() References: Message-ID: <964910ec-a2a7-44cc-b8f3-5d4de68b5411@j21g2000yqh.googlegroups.com> On Apr 1, 6:46?am, Ethan Furman wrote: > Greetings! > > Perhaps I woke up too early this morning, but this behaviour has me baffled: > > Python 3.1.1 (r311:74483, Aug 17 2009, 17:02:12) [MSC v.1500 32 bit > (Intel)] on win32 > Type "help", "copyright", "credits" or "license" for more information. > > --> test = object() > > --> setattr(test, 'example', 123) > Traceback (most recent call last): > ? ?File "", line 1, in > AttributeError: 'object' object has no attribute 'example' > > Shouldn't setattr() be creating the 'example' attribute? ?Any tips > greatly appreciated! > On 2.6.2 the error seems to be limited to instances of object. If you subclass object, you are fine. I do not know why that is so; I'm just verifying that the behavior you see is not limited to 3.1.1. Python 2.6.2 (release26-maint, Apr 19 2009, 01:56:41) [GCC 4.3.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> class Foo(object): pass ... >>> test = Foo() >>> setattr(test, 'example', 123) >>> test.example 123 >>> test = object() >>> setattr(test, 'example', 123) Traceback (most recent call last): File "", line 1, in AttributeError: 'object' object has no attribute 'example' It's probably good to subclass object anyway, with something like: class Record(object): pass But I do not know your use case. From steve at holdenweb.com Thu Apr 1 10:21:31 2010 From: steve at holdenweb.com (Steve Holden) Date: Thu, 01 Apr 2010 10:21:31 -0400 Subject: Python 3.1, object, and setattr() In-Reply-To: <4BB4A3B9.8010709@stoneleaf.us> References: <4BB4A3B9.8010709@stoneleaf.us> Message-ID: Ethan Furman wrote: > Greetings! > > Perhaps I woke up too early this morning, but this behaviour has me > baffled: > > Python 3.1.1 (r311:74483, Aug 17 2009, 17:02:12) [MSC v.1500 32 bit > (Intel)] on win32 > Type "help", "copyright", "credits" or "license" for more information. > > --> test = object() > > --> setattr(test, 'example', 123) > Traceback (most recent call last): > File "", line 1, in > AttributeError: 'object' object has no attribute 'example' > > Shouldn't setattr() be creating the 'example' attribute? Any tips > greatly appreciated! > It's not just object, and it's not just the setattr() function. It's not even just Python 3.1 for that matter! Later Python 2 implementations have the same issue. >>> x = 1 >>> setattr(x, 'example', 123) Traceback (most recent call last): File "", line 1, in AttributeError: 'int' object has no attribute 'example' >>> x.example = 123 Traceback (most recent call last): File "", line 1, in AttributeError: 'int' object has no attribute 'example' >>> There are limits to what you can do with the built-in types. No matter how hard Python tries to make them look the same, ultimately the built-in types are implemented differently from the types you create yourself. For efficiency reasons the attributes of the built-ins are stored in a different way (that's more accessible to the C implementation) than those of the declared types. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 See PyCon Talks from Atlanta 2010 http://pycon.blip.tv/ Holden Web LLC http://www.holdenweb.com/ UPCOMING EVENTS: http://holdenweb.eventbrite.com/ From pmaupin at gmail.com Thu Apr 1 10:23:17 2010 From: pmaupin at gmail.com (Patrick Maupin) Date: Thu, 1 Apr 2010 07:23:17 -0700 (PDT) Subject: sorting ascending/descending with operator.attrgetter References: <96712ef1-5c10-455b-904c-c2436736c9d2@35g2000yqm.googlegroups.com> <4bb3d346$0$8827$c3e8da3@news.astraweb.com> Message-ID: On Apr 1, 12:50?am, Steve Holden wrote: > > I can well imagine that everybody who has to work with you thoroughly > > ?enjoys proving you wrong as often as possible. > > I am glad I wasn't drinking when I read this. Liquid in one's nose is so > uncomfortable. Well, in that case, I'm glad you enjoyed it. It's hard to know when to put a disclaimer on these things. Others might not find the same sorts of things funny, and the very act of putting a disclaimer often promises more than it delivers, so I think it's pretty much just "caveat reader." > I guess we have to value the good that's in Steven (few would deny that > he *is* technically very competent) and try and ignore his more annoying > side. Well, I suppose there are two coping strategies. Ignoring him (yes, I need to do that more), and also, reading more carefully before posting. The latter is always a good thing, but on the other hand it takes more mental effort. Yes, it's better for posterity, but someone reading the thread later and seeing what is written in context will probably figure out what is meant, even if there are a few mistakes. The extra effort shifts the balance from "will this help the OP?" to "if this email were read completely devoid of external context, how many ways are there to mis-interpret it, and how much time am I willing to spend reducing that number, when it's impossible to get it to zero, anyway?" > I have toyed many times with the idea of giving a presentation at PyCon > called something like "Humanity 101". It would include such advice as > "When I say 'use soap' I am not talking about the Simple Object Access > Protocol" and "Being wrong is usually survivable; offending a homicidal > maniac often isn't". > > Perhaps I should just add it to the Holden Web course schedule? Well, I haven't killed anybody yet; OTOH a few events from my childhood taught me that there are really only two kinds of people: those who could kill under the right circumstances, and those who haven't figured it out yet. So, yes, that might be a good idea ;-) Regards, Pat From steve at holdenweb.com Thu Apr 1 10:25:08 2010 From: steve at holdenweb.com (Steve Holden) Date: Thu, 01 Apr 2010 10:25:08 -0400 Subject: Python 3.1, object, and setattr() In-Reply-To: <4BB4A3B9.8010709@stoneleaf.us> References: <4BB4A3B9.8010709@stoneleaf.us> Message-ID: Ethan Furman wrote: > Greetings! > > Perhaps I woke up too early this morning, but this behaviour has me > baffled: > > Python 3.1.1 (r311:74483, Aug 17 2009, 17:02:12) [MSC v.1500 32 bit > (Intel)] on win32 > Type "help", "copyright", "credits" or "license" for more information. > > --> test = object() > > --> setattr(test, 'example', 123) > Traceback (most recent call last): > File "", line 1, in > AttributeError: 'object' object has no attribute 'example' > > Shouldn't setattr() be creating the 'example' attribute? Any tips > greatly appreciated! > By the way, the "solution" is to create a subclass of object (which in Python 3 simply requires you to declare a class! In Python 2 you'd have to explicitly subclass object, or (equivalently) set your class's metaclass to type with __metaclass__ = type regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 See PyCon Talks from Atlanta 2010 http://pycon.blip.tv/ Holden Web LLC http://www.holdenweb.com/ UPCOMING EVENTS: http://holdenweb.eventbrite.com/ From fordhaivat at gmail.com Thu Apr 1 10:34:51 2010 From: fordhaivat at gmail.com (Someone Something) Date: Thu, 1 Apr 2010 10:34:51 -0400 Subject: CGI templating with python In-Reply-To: References: Message-ID: Cheetah would work, but it would be a major pain to debug (I hate those 500 Server Error pages) something django (as mentioned above) or turbogears (with Kid) would get you rolling quickly. On Wed, Mar 31, 2010 at 8:38 PM, KB wrote: > Hi there, > > Years ago I wrote a LAMP app using python. I find I need a simple web > data entry tool to store records (stock research) and when I enter a > stock ticker, to pull up all the past research I have done. I am > imagining fields like ticker, date, pulldown menus for various > options, long text for comments etc.. > > It's a very light weight application, so I was wondering if using > something like Cheetah is the best way to do this? > > Or should I research Zope further or are there any other suggestions? > > Environment: > - Python 2.5 (w/ MySQLdb) > - MySQL 5.1 > - Windows Vista > > Many thanks in advance! > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From eryan.yu at gmail.com Thu Apr 1 10:53:31 2010 From: eryan.yu at gmail.com (Mister Yu) Date: Thu, 1 Apr 2010 07:53:31 -0700 (PDT) Subject: newbie with a encoding question, please help References: <23c7d677-dd66-4ef1-8032-5f39dc74b18e@z3g2000yqz.googlegroups.com> Message-ID: On Apr 1, 9:31 pm, Stefan Behnel wrote: > Mister Yu, 01.04.2010 14:26: > > > On Apr 1, 8:13 pm, Chris Rebert wrote: > >> gb2312_bytes = ''.join([chr(ord(c)) for c in u'\xd6\xd0\xce\xc4']) > >> unicode_string = gb2312_bytes.decode('gb2312') > >> utf8_bytes = unicode_string.encode('utf-8') #as you wanted > > Simplifying this hack a bit: > > gb2312_bytes = u'\xd6\xd0\xce\xc4'.encode('ISO-8859-1') > unicode_string = gb2312_bytes.decode('gb2312') > utf8_bytes = unicode_string.encode('utf-8') > > Although I have to wonder why you want a UTF-8 encoded byte string as > output instead of Unicode. > > >> If possible, I'd look at the code that's giving you that funky > >> "string" in the first place and see if it can be fixed to give you > >> either a proper bytestring or proper unicode string rather than the > >> bastardized mess you're currently having to deal with. > > > thanks for the great tips! it works like a charm. > > I hope you're aware that it's a big ugly hack, though. You should really > try to fix your input instead. > > > i m using the Scrapy project(http://doc.scrapy.org/intro/ > > tutorial.html) to write my crawler, when it extract data with xpath, > > it puts the chinese characters directly into the unicode object. > > My guess is that the HTML page you are parsing is broken and doesn't > specify its encoding. In that case, all that scrapy can do is guess, and it > seems to have guessed incorrectly. > > You should check if there is a way to tell scrapy about the expected page > encoding, so that it can return correctly decoded unicode strings directly, > instead of resorting to dirty hacks that may or may not work depending on > the page you are parsing. > > Stefan Hi Stefan, i don't think the page is broken or somehow, you can take a look at the page http://www.7176.com/Sections/Genre/Comedy , it's kinda like a chinese IMDB rip off from what i can see from the source code of the page header, it contains the coding info: ??? ?? ????? ?1? maybe i should take a look at the source code of Scrapy, but i m just not more than a week's newbie of python. not sure if i can understand the source. earlier Chris's walk around is looking pretty well until it meets some string like this: >>> su = u'???? 12345 ????' >>> su u'\u4e00\u4e8c\u4e09\u56db 12345 \u4e00\u4e8c\u4e09\u56db' >>> gb2312_bytes = ''.join([chr(ord(c)) for c in u'\u4e00\u4e8c\u4e09\u56db 12345 \u4e00\u4e8c\u4e09\u56db']) Traceback (most recent call last): File "", line 1, in ValueError: chr() arg not in range(256) the digis doesn't get encoded so it messes up the code. any ideas? once again, thanks everybody's help!!!! From showell30 at yahoo.com Thu Apr 1 10:59:41 2010 From: showell30 at yahoo.com (Steve Howell) Date: Thu, 1 Apr 2010 07:59:41 -0700 (PDT) Subject: sort array, apply rearrangement to second References: <1jg6j1v.oxpx651vbq67mN%see@sig.for.address> <8d8415a5-ba77-4dc3-b870-f159886e76b5@i25g2000yqm.googlegroups.com> Message-ID: On Mar 31, 1:09?pm, Raymond Hettinger wrote: > On Mar 30, 4:25?pm, s... at sig.for.address (Victor Eijkhout) wrote: > > > I have two arrays, made with numpy. The first one has values that I want > > to use as sorting keys; the second one needs to be sorted by those keys. > > Obviously I could turn them into a dictionary ?of pairs and sort by the > > first member, but I think that's not very efficient, at least in space, > > and this needs to be done as efficiently as possible. > > Alf's recommendation is clean and correct. ?Just make a list of > tuples. > > FWIW, here's a little hack that does the work for you: > > >>> values = ['A', 'B', 'C', 'D', 'E'] > >>> keys = [50, 20, 40, 10, 30] > >>> keyiter = iter(keys) > >>> sorted(values, key=lambda k: next(keyiter)) > > ['D', 'B', 'E', 'C', 'A'] > Another option: [values[i] for i in sorted(range(len(keys)), key=lambda i: keys[i])] Sort the indexes according to keys values, then use indexes to get the values. It might read more clearly when broken out into two lines: >>> sorted_indexes = sorted(range(len(keys)), key = lambda i: keys[i]) >>> sorted_indexes [3, 1, 4, 2, 0] >>> [values[i] for i in sorted_indexes] ['D', 'B', 'E', 'C', 'A'] The advantage of Raymond's solution is that he only creates one new Python list, whereas my solutions create an intermediate Python list of integers. I don't think my solution really is that space-wasteful, though, since by the time the second list gets created, any internal intermediate lists from CPython's sorted() implementation will probably have been cleaned up. From natdabolt at yahoo.com Thu Apr 1 11:08:45 2010 From: natdabolt at yahoo.com (NADHIRAH) Date: Thu, 1 Apr 2010 08:08:45 -0700 Subject: simple-way-to-recover-your-missing-laptop References: <48469e2f$1_2@news.tm.net.my> Message-ID: <4bb3e3f4_2@news.tm.net.my> "fizzi" wrote in message news:48469e2f$1_2 at news.tm.net.my... > Worst thing could happen to your laptop is its been stolen, there is an > easy way to recover back your missing property. LocatePC is a software > that sends you a secret email message from your computer containing vital > information that can help you and law enforcement track a stolen computer, > and eventually return it to you. > > the rest of the article > http://www.my10sen.com/2008/06/04/simple-way-to-recover-your-missing-laptop/ From keith at nekotaku.com Thu Apr 1 11:19:51 2010 From: keith at nekotaku.com (KB) Date: Thu, 1 Apr 2010 08:19:51 -0700 (PDT) Subject: CGI templating with python References: Message-ID: > Django will probably get you where you want to go the fastest: > > ? ?http://www.djangoproject.com/ > > In particular, its admin interface will probably automatically generate a usable > UI for you without your having to write many templates at all. Robert, Thank you very very much. I had a brief peruse of django last night and it does indeed look like what I am after! Will take me some time :) to delve into it deeper but I wanted to thank you! From keith at nekotaku.com Thu Apr 1 11:23:24 2010 From: keith at nekotaku.com (KB) Date: Thu, 1 Apr 2010 08:23:24 -0700 (PDT) Subject: Developement Question? References: Message-ID: <9fbc222c-4812-45ba-9d16-6ba63bfd0eaf@i25g2000yqm.googlegroups.com> On Apr 1, 3:34?am, Wayne wrote: > My town office uses Microsoft operating system. They have a proprietary > accounting system that uses excel for their accounting reports. > I would like to read these report and reproduce the report so that > the report can be seen on the web. I was thinking about using xlrd and > xlwt along with some sort of software for building the web pages. I > use linux only and do not use Microsoft. > Q. Does python have to be installed on there computer to run the script? > > Q. Am I approaching this the wrong way? If so, what would be a better > approach? Wayne, check out google group python-excel. They are very helpful there, and I believe there are threads on how to compile what you are looking for into a .exe for just such a situation (Disclaimer: I am far from an expert, so I may have misunderstood from the python-excel thread if python is/isn't required on the target machine once the .exe is built, but try that group - John Machin is very responsive) From patentsvnc at gmail.com Thu Apr 1 11:27:53 2010 From: patentsvnc at gmail.com (Den) Date: Thu, 1 Apr 2010 08:27:53 -0700 (PDT) Subject: (a==b) ? 'Yes' : 'No' References: <4bb22b39$0$1638$742ec2ed@news.sonic.net> Message-ID: <861e25b4-96b1-4a12-82d8-9a93cbc3e8da@8g2000yqz.googlegroups.com> On Mar 30, 10:56?am, Steve Holden wrote: > John Nagle wrote: > > Chris Rebert wrote: > >> On Tue, Mar 30, 2010 at 8:40 AM, gentlestone > >> wrote: > >>> Hi, how can I write the popular C/JAVA syntax in Python? > > >>> Java example: > >>> ? ?return (a==b) ? 'Yes' : 'No' > > >>> My first idea is: > >>> ? ?return ('No','Yes')[bool(a==b)] > > >>> Is there a more elegant/common python expression for this? > > >> Yes, Python has ternary operator-like syntax: > >> return ('Yes' if a==b else 'No') > > >> Note that this requires a recent version of Python. > > > ? ? Who let the dogs in? ?That's awful syntax. > > Yes, that's deliberately awful syntax. Guido designed it that way to > ensure that people didn't aver-use it, thereby reducing the readability > of Python applications. Speaking purely personally I hardly ever use it, > but don't dislike it. > > regards > ?Steve > -- > Steve Holden ? ? ? ? ? +1 571 484 6266 ? +1 800 494 3119 > See PyCon Talks from Atlanta 2010 ?http://pycon.blip.tv/ > Holden Web LLC ? ? ? ? ? ? ? ?http://www.holdenweb.com/ > UPCOMING EVENTS: ? ? ? ?http://holdenweb.eventbrite.com/ I've been following this thread for a few days now. My thoughts are that, in view of a long known widely used syntax for this operator, python's syntax seems like change for change sake. If current programing paradigm provides that particular trinary operator, why should python's be different from the previously well known one. For instance, no reasonable language designer would, now, use post-fix (I know about Forth) or allow only +=, -=, /=, etc. assignments ONLY. (Just as no reasonable car designer would put the accelerator pedal on the left.) There are conventions which should span products. Yes python has the trinary operator and it's not going to change, but this seems like a bit of petulance on the part of the designer. Den From joncle at googlemail.com Thu Apr 1 11:38:40 2010 From: joncle at googlemail.com (Jon Clements) Date: Thu, 1 Apr 2010 08:38:40 -0700 (PDT) Subject: Q: We have *args and **kwargs. Woud ***allargs be useful? References: Message-ID: <2ee6ab09-bcf3-41a7-b1c6-fc23f65eb1ab@10g2000yqq.googlegroups.com> On 1 Apr, 10:57, Jonathan Fine wrote: > The idioms > ? ? ?def f(*args, **kwargs): > ? ? ? ? ?# Do something. > and > ? ? ?args = (1, 2, 3) > ? ? ?kwargs = dict(a=4, b=5) > ? ? ?g(*args, **kwargs) > are often useful in Python. > > I'm finding myself picking up /all/ the arguments and storing them for > later use (as part of a testing framework). ?So for me it would be nice > if I could write > ? ? ?def f(***allargs): > ? ? ? ? ? args, kwargs = allargs > ? ? ? ? ? # Continue as before. > > However, if we do this then 'args' in '*args' is misleading. ?So I'll > use 'sargs' (for sequence arguments) instead. > > I can now write, for a suitable class Args > ? ? ?args = Args(1, 2, 3, a=4, b=5) > ? ? ?g(***args) ? # Same as before. > ? ? ?sargs, kwargs = args > ? ? ?g(*sargs, **kwargs) ?# Same as before. > > Even better, now that Args is a class we can give it a method 'call' so that > ? ? ?args.call(g) > is equivalent to > ? ? ?g(***args) > which removes the need for the *** construct. > > This reminds me of functools.partial except, of course, we've fixed all > the arguments and left the passing of the function for later, whereas in > partial we fix the function and some of the arguments. > ? ? ?http://docs.python.org/library/functools.html#functools.partial > > My view are that > 1. ?Conceptually ***allargs is useful, but an Args class would be more > useful (not that it need be either-or). > > 2. ?If Args were built in , there could be performance benefits. > > 3. ?It's clearer to write > ? ? ? ? ?def(*seqargs, **kwargs): > than > ? ? ? ? ?def(*args, **kwargs): > > 4. ?When the Args class is used a lot, one might welcome > ? ? ? ? ?def(***args): > ? ? ? ? ? ? ?# Do something with args. > as a shortcut (and minor speedup) for > ? ? ? ? ?def(*seqargs, **kwargs): > ? ? ? ? ? ? ?args = Args(*seqargs, **kwargs) > ? ? ? ? ? ? ?# Do something with args. > > I look forward to your comments on this. > > -- > Jonathan I'm not sure this'll catch on, it'll be interesting to see other comments. However, I believe you can get the behaviour you desire something like: import inspect class AllArgs(object): def __init__(self, func): self._func = func self._spec = inspect.getargspec(func) self._nposargs = len(self._spec.args) def __call__(self, *args, **kwdargs): self._func.func_globals['Args'] = (args[self._nposargs:], kwdargs) return self._func(*args[:self._nposargs]) @AllArgs def test(): print Args @AllArgs def test2(a, b): print a, b, Args test(1, 2, 3, 4, 5, a=3, b=5) test2(1, 2, 3, 4, 5, c=7) Done quickly, probably buggy, but does provide 'Args', but without further work swallows any *'s and **'s and might ignore defaults (hideously untested) hth Jon. From novacompute at gmail.com Thu Apr 1 12:35:04 2010 From: novacompute at gmail.com (wukong) Date: Thu, 1 Apr 2010 09:35:04 -0700 (PDT) Subject: subprocess only good for win32? References: <353133a8-ff39-4b36-b96d-4836cea621bf@j41g2000vbe.googlegroups.com> <4BB3D0F6.2010906@v.loewis.de> Message-ID: On Mar 31, 3:47?pm, "Martin v. Loewis" wrote: > > WindowsError: [Error 14001] The application has failed to start > > because its side-by-side configuration is incorrect. Please see the > > application event log for more detail > > This is a configuration error on your system. The application you are > trying to start is incorrectly installed - it's not only that Python > can't start it, but nobody can. > > Regards, > Martin but python runs happy otherwise, only this call to subprocess resulted in an err. does anyone know for sure subprocess runs on win64? or any others like, popen does? thanks wk From novacompute at gmail.com Thu Apr 1 12:36:20 2010 From: novacompute at gmail.com (wukong) Date: Thu, 1 Apr 2010 09:36:20 -0700 (PDT) Subject: subprocess only good for win32? References: <353133a8-ff39-4b36-b96d-4836cea621bf@j41g2000vbe.googlegroups.com> <4BB3D0F6.2010906@v.loewis.de> Message-ID: <07893ee5-51a1-4c62-9861-7d75192af716@x12g2000yqx.googlegroups.com> On Mar 31, 3:47?pm, "Martin v. Loewis" wrote: > > WindowsError: [Error 14001] The application has failed to start > > because its side-by-side configuration is incorrect. Please see the > > application event log for more detail > > This is a configuration error on your system. The application you are > trying to start is incorrectly installed - it's not only that Python > can't start it, but nobody can. > > Regards, > Martin nad also as i mentioned previously, it runs great on win32. From J.Fine at open.ac.uk Thu Apr 1 12:44:02 2010 From: J.Fine at open.ac.uk (Jonathan Fine) Date: Thu, 01 Apr 2010 17:44:02 +0100 Subject: Q: We have *args and **kwargs. Woud ***allargs be useful? In-Reply-To: <2ee6ab09-bcf3-41a7-b1c6-fc23f65eb1ab@10g2000yqq.googlegroups.com> References: <2ee6ab09-bcf3-41a7-b1c6-fc23f65eb1ab@10g2000yqq.googlegroups.com> Message-ID: Jon Clements wrote: > I'm not sure this'll catch on, it'll be interesting to see other > comments. > However, I believe you can get the behaviour you desire something > like: > > import inspect > > class AllArgs(object): > def __init__(self, func): > self._func = func > self._spec = inspect.getargspec(func) > self._nposargs = len(self._spec.args) > def __call__(self, *args, **kwdargs): > self._func.func_globals['Args'] = (args[self._nposargs:], > kwdargs) > return self._func(*args[:self._nposargs]) > > @AllArgs > def test(): > print Args > > @AllArgs > def test2(a, b): > print a, b, Args > > test(1, 2, 3, 4, 5, a=3, b=5) > test2(1, 2, 3, 4, 5, c=7) > > Done quickly, probably buggy, but does provide 'Args', but without > further work > swallows any *'s and **'s and might ignore defaults (hideously > untested) Thank you for your interest, Jon. According to http://docs.python.org/library/inspect.html we have that func_globals is the global namespace in which this function was defined. Hence we have >>> def f(): pass ... >>> f.func_globals is globals() True >>> f.func_globals ['x'] = 3 >>> x 3 >>> I don't yet understand what your code is intended to do, but I'm fairly sure you're not wishing to 'monkey-patch' a global namespace of a module. -- Jonathan From steve at holdenweb.com Thu Apr 1 12:44:35 2010 From: steve at holdenweb.com (Steve Holden) Date: Thu, 01 Apr 2010 12:44:35 -0400 Subject: (a==b) ? 'Yes' : 'No' In-Reply-To: <861e25b4-96b1-4a12-82d8-9a93cbc3e8da@8g2000yqz.googlegroups.com> References: <4bb22b39$0$1638$742ec2ed@news.sonic.net> <861e25b4-96b1-4a12-82d8-9a93cbc3e8da@8g2000yqz.googlegroups.com> Message-ID: Den wrote: [...] > I've been following this thread for a few days now. My thoughts are > that, in view of a long known widely used syntax for this operator, > python's syntax seems like change for change sake. If current > programing paradigm provides that particular trinary operator, why > should python's be different from the previously well known one. > Because the "long known widely used syntax" has been responsible for some of the most incomprehensible and buggy code in the known universe. \ > For instance, no reasonable language designer would, now, use post-fix > (I know about Forth) or allow only +=, -=, /=, etc. assignments ONLY. > (Just as no reasonable car designer would put the accelerator pedal on > the left.) There are conventions which should span products. Yes > python has the trinary operator and it's not going to change, but this > seems like a bit of petulance on the part of the designer. > That argument could easily be extended to suggesting that there should be no new languages at all. Guido made the specific choice of this syntax precisely to try and ensure that the ternary (not trinary) operator wasn't abused the way it has been in C (and later C#). He is a language designer with a fine sense of readability, and I personally respect his decision. This StackOverflow thread http://stackoverflow.com/questions/1763543/ternary-operator-associativity-in-c-can-i-rely-on-it is just one example of the time that gets wasted. But then I suppose that this thread just exemplifies that people will find something else to waste their time on if you don't encourage them to abuse the ternary operator. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 See PyCon Talks from Atlanta 2010 http://pycon.blip.tv/ Holden Web LLC http://www.holdenweb.com/ UPCOMING EVENTS: http://holdenweb.eventbrite.com/ From steve at holdenweb.com Thu Apr 1 12:58:49 2010 From: steve at holdenweb.com (Steve Holden) Date: Thu, 01 Apr 2010 12:58:49 -0400 Subject: subprocess only good for win32? In-Reply-To: References: <353133a8-ff39-4b36-b96d-4836cea621bf@j41g2000vbe.googlegroups.com> <4BB3D0F6.2010906@v.loewis.de> Message-ID: wukong wrote: > On Mar 31, 3:47 pm, "Martin v. Loewis" wrote: >>> WindowsError: [Error 14001] The application has failed to start >>> because its side-by-side configuration is incorrect. Please see the >>> application event log for more detail >> This is a configuration error on your system. The application you are >> trying to start is incorrectly installed - it's not only that Python >> can't start it, but nobody can. >> >> Regards, >> Martin > > but python runs happy otherwise, only this call to subprocess resulted > in an err. does anyone know for sure subprocess runs on win64? or > any others like, popen does? > thanks > wk Subprocess runs another program. It's the program you are running that's giving the error, Python is merely reporting it. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 See PyCon Talks from Atlanta 2010 http://pycon.blip.tv/ Holden Web LLC http://www.holdenweb.com/ UPCOMING EVENTS: http://holdenweb.eventbrite.com/ From python at mrabarnett.plus.com Thu Apr 1 13:01:36 2010 From: python at mrabarnett.plus.com (MRAB) Date: Thu, 01 Apr 2010 18:01:36 +0100 Subject: decorators only when __debug__ == True In-Reply-To: References: <7778821c-84f3-4829-8e05-85134c5d6c5b@y17g2000yqd.googlegroups.com> <4bb3d27f$0$8827$c3e8da3@news.astraweb.com> <4BB49799.1040100@mrabarnett.plus.com> Message-ID: <4BB4D170.7070208@mrabarnett.plus.com> Steve Holden wrote: > MRAB wrote: >> Steven D'Aprano wrote: >>> On Thu, 01 Apr 2010 00:27:51 +0100, MRAB wrote: >>> >>>>>> A decorator shouldn't call the function it's decorating. >>>>> *raises eyebrow* >>>>> >>>>> Surely, in the general case, a decorator SHOULD call the function it is >>>>> decorating? I'm sure you know that, but your wording is funny and could >>>>> confuse the OP. >>>>> >>>> What I mean is that the function that's doing the decorating shouldn't >>>> call the function; it's the locally-defined wrapper function that calls >>>> the decorated function. >>> Ah, gotcha, that makes sense. Now I understand the distinction you >>> were making. Thank you for the clarification. >>> >> I had the following idea: define the terms 'decorator', 'decoration' and >> 'decoratee'. The decorator applies the decoration to the decoratee. The >> decoratee is the function defined locally in the decorator. > > It would make more sense (to me, at least) if the decoratee were the > function passed as an argument to the decorator. > Oops, you're right! What I meant was that the _decoration_ is the function defined locally in the decorator. From enleverLesX_XXmcX at XmclavXeauX.com.invalid Thu Apr 1 13:11:32 2010 From: enleverLesX_XXmcX at XmclavXeauX.com.invalid (Michel Claveau - MVP) Date: Thu, 01 Apr 2010 19:11:32 +0200 Subject: subprocess only good for win32? References: Message-ID: <4bb4d3ca$0$3686$ba4acef3@reader.news.orange.fr> Hi! > side-by-side configuration is incorrect Others have given you an explanation. A possibility: you use a DLL directly, without having installed. That is OK with some DLL, and no OK with others DLL. @-salutations -- Michel Claveau From saimapk81 at gmail.com Thu Apr 1 13:12:21 2010 From: saimapk81 at gmail.com (saima81) Date: Thu, 1 Apr 2010 10:12:21 -0700 (PDT) Subject: "jobs in canada" "jobs in canada for pakistanis" "jobs in canada for foreigners" "jobs in canada hotels" "jobs in canada for accountants" "canada jobs" "canada job bank" on http://jobsincanada-net.blogspot.com/ Message-ID: <23b34796-a178-4e5d-a520-5d24a5da83bb@z7g2000yqb.googlegroups.com> "jobs in canada" "jobs in canada for pakistanis" "jobs in canada for foreigners" "jobs in canada hotels" "jobs in canada for accountants" "canada jobs" "canada job bank" on http://jobsincanada-net.blogspot.com/ "jobs in canada" "jobs in canada for pakistanis" "jobs in canada for foreigners" "jobs in canada hotels" "jobs in canada for accountants" "canada jobs" "canada job bank" on http://jobsincanada-net.blogspot.com/ "jobs in canada" "jobs in canada for pakistanis" "jobs in canada for foreigners" "jobs in canada hotels" "jobs in canada for accountants" "canada jobs" "canada job bank" on http://jobsincanada-net.blogspot.com/ "jobs in canada" "jobs in canada for pakistanis" "jobs in canada for foreigners" "jobs in canada hotels" "jobs in canada for accountants" "canada jobs" "canada job bank" on http://jobsincanada-net.blogspot.com/ "jobs in canada" "jobs in canada for pakistanis" "jobs in canada for foreigners" "jobs in canada hotels" "jobs in canada for accountants" "canada jobs" "canada job bank" on http://jobsincanada-net.blogspot.com/ "jobs in canada" "jobs in canada for pakistanis" "jobs in canada for foreigners" "jobs in canada hotels" "jobs in canada for accountants" "canada jobs" "canada job bank" on http://jobsincanada-net.blogspot.com/ "jobs in canada" "jobs in canada for pakistanis" "jobs in canada for foreigners" "jobs in canada hotels" "jobs in canada for accountants" "canada jobs" "canada job bank" on http://jobsincanada-net.blogspot.com/ "jobs in canada" "jobs in canada for pakistanis" "jobs in canada for foreigners" "jobs in canada hotels" "jobs in canada for accountants" "canada jobs" "canada job bank" on http://jobsincanada-net.blogspot.com/ "jobs in canada" "jobs in canada for pakistanis" "jobs in canada for foreigners" "jobs in canada hotels" "jobs in canada for accountants" "canada jobs" "canada job bank" on http://jobsincanada-net.blogspot.com/ "jobs in canada" "jobs in canada for pakistanis" "jobs in canada for foreigners" "jobs in canada hotels" "jobs in canada for accountants" "canada jobs" "canada job bank" on http://jobsincanada-net.blogspot.com/ "jobs in canada" "jobs in canada for pakistanis" "jobs in canada for foreigners" "jobs in canada hotels" "jobs in canada for accountants" "canada jobs" "canada job bank" on http://jobsincanada-net.blogspot.com/ "jobs in canada" "jobs in canada for pakistanis" "jobs in canada for foreigners" "jobs in canada hotels" "jobs in canada for accountants" "canada jobs" "canada job bank" on http://jobsincanada-net.blogspot.com/ "jobs in canada" "jobs in canada for pakistanis" "jobs in canada for foreigners" "jobs in canada hotels" "jobs in canada for accountants" "canada jobs" "canada job bank" on http://jobsincanada-net.blogspot.com/ "jobs in canada" "jobs in canada for pakistanis" "jobs in canada for foreigners" "jobs in canada hotels" "jobs in canada for accountants" "canada jobs" "canada job bank" on http://jobsincanada-net.blogspot.com/ "jobs in canada" "jobs in canada for pakistanis" "jobs in canada for foreigners" "jobs in canada hotels" "jobs in canada for accountants" "canada jobs" "canada job bank" on http://jobsincanada-net.blogspot.com/ "jobs in canada" "jobs in canada for pakistanis" "jobs in canada for foreigners" "jobs in canada hotels" "jobs in canada for accountants" "canada jobs" "canada job bank" on http://jobsincanada-net.blogspot.com/ "jobs in canada" "jobs in canada for pakistanis" "jobs in canada for foreigners" "jobs in canada hotels" "jobs in canada for accountants" "canada jobs" "canada job bank" on http://jobsincanada-net.blogspot.com/ "jobs in canada" "jobs in canada for pakistanis" "jobs in canada for foreigners" "jobs in canada hotels" "jobs in canada for accountants" "canada jobs" "canada job bank" on http://jobsincanada-net.blogspot.com/ "jobs in canada" "jobs in canada for pakistanis" "jobs in canada for foreigners" "jobs in canada hotels" "jobs in canada for accountants" "canada jobs" "canada job bank" on http://jobsincanada-net.blogspot.com/ "jobs in canada" "jobs in canada for pakistanis" "jobs in canada for foreigners" "jobs in canada hotels" "jobs in canada for accountants" "canada jobs" "canada job bank" on http://jobsincanada-net.blogspot.com/ "jobs in canada" "jobs in canada for pakistanis" "jobs in canada for foreigners" "jobs in canada hotels" "jobs in canada for accountants" "canada jobs" "canada job bank" on http://jobsincanada-net.blogspot.com/ "jobs in canada" "jobs in canada for pakistanis" "jobs in canada for foreigners" "jobs in canada hotels" "jobs in canada for accountants" "canada jobs" "canada job bank" on http://jobsincanada-net.blogspot.com/ v From gatoygata2 at gmail.com Thu Apr 1 13:12:38 2010 From: gatoygata2 at gmail.com (Joaquin Abian) Date: Thu, 1 Apr 2010 10:12:38 -0700 (PDT) Subject: no module named exceptions? Message-ID: <4dabb1e4-4735-4e85-a61e-1c4cf1ccbea3@r1g2000yqj.googlegroups.com> In python 3.1, >>> import exceptions Traceback (most recent call last): File "", line 1, in import exceptions ImportError: No module named exceptions in 2.6 no exception is raised It should be the same in 3.1, isnt it? Joaquin From anand.shashwat at gmail.com Thu Apr 1 13:29:50 2010 From: anand.shashwat at gmail.com (Shashwat Anand) Date: Thu, 1 Apr 2010 22:59:50 +0530 Subject: no module named exceptions? In-Reply-To: <4dabb1e4-4735-4e85-a61e-1c4cf1ccbea3@r1g2000yqj.googlegroups.com> References: <4dabb1e4-4735-4e85-a61e-1c4cf1ccbea3@r1g2000yqj.googlegroups.com> Message-ID: There i no module named 'exceptions' in python 2.6 as well as python 3.1 What are you expecting ? On Thu, Apr 1, 2010 at 10:42 PM, Joaquin Abian wrote: > In python 3.1, > > >>> import exceptions > Traceback (most recent call last): > File "", line 1, in > import exceptions > ImportError: No module named exceptions > > in 2.6 no exception is raised > It should be the same in 3.1, isnt it? > > Joaquin > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From tgrav at mac.com Thu Apr 1 13:37:01 2010 From: tgrav at mac.com (Tommy Grav) Date: Thu, 01 Apr 2010 13:37:01 -0400 Subject: no module named exceptions? In-Reply-To: References: <4dabb1e4-4735-4e85-a61e-1c4cf1ccbea3@r1g2000yqj.googlegroups.com> Message-ID: This is what he is expecting. Importing exceptions works fine in 2.6.4, not so in python 3.1. Python 2.6.4 (r264:75706, Nov 3 2009, 18:12:54) [GCC 4.2.1 (Apple Inc. build 5646) (dot 1)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import exceptions >>> Tommy On Apr 1, 2010, at 1:29 PM, Shashwat Anand wrote: > There i no module named 'exceptions' in python 2.6 as well as python 3.1 What are you expecting ? > > On Thu, Apr 1, 2010 at 10:42 PM, Joaquin Abian wrote: > In python 3.1, > > >>> import exceptions > Traceback (most recent call last): > File "", line 1, in > import exceptions > ImportError: No module named exceptions > > in 2.6 no exception is raised > It should be the same in 3.1, isnt it? > > Joaquin > -- > http://mail.python.org/mailman/listinfo/python-list > > -- > http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- An HTML attachment was scrubbed... URL: From tjreedy at udel.edu Thu Apr 1 13:44:02 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 01 Apr 2010 13:44:02 -0400 Subject: Python 3.1, object, and setattr() In-Reply-To: <964910ec-a2a7-44cc-b8f3-5d4de68b5411@j21g2000yqh.googlegroups.com> References: <964910ec-a2a7-44cc-b8f3-5d4de68b5411@j21g2000yqh.googlegroups.com> Message-ID: On 4/1/2010 10:16 AM, Steve Howell wrote: > On Apr 1, 6:46 am, Ethan Furman wrote: > > On 2.6.2 the error seems to be limited to instances of object. If you > subclass object, you are fine. I do not know why that is so; As the other Steve said, object is a built-in class; user-defined subclasses of object are user-defined classes. (And all other built-in classes are built-in subclasses of object, at least in 3.x.) Python objects can have either a fixed or variable set of attributes. By default, instances of user classes have an attribute dictionary (__dict__) for a variable set of attributes. >>> a = A() >>> a.a = 3 >>> a.a 3 >>> a.__dict__ {'a': 3} The exception is when '__slots__ = xxx' is part of the class definition. It instances then have a fixed set of attributes. >>> class C(): __slots__ = () >>> c = C() >>> c.a = 1 Traceback (most recent call last): File "", line 1, in c.a = 1 AttributeError: 'C' object has no attribute 'a' The error message means that 'a' is not in the fixed set of instance attributes (as defined by __slots__) for class C. In general, instances of built-in classes do not have such attribute dictionaries and one their attribute set is fixed (and often empty). It is as if built-in classes have '__slots__ = xxx' as part of their definition. In particular, object and others act like they have '__slots__ = ()', which means they have no instance attributes. There are two exceptions among built-in classes that I know of: type and 'function', (whose instances are user-defined functions). >>> def f(): pass >>> f.__dict__ {} # standard dict just as with user class instances Instances of type are more complicated: >>> C.__dict__ >>> C.z = 3 >>> C.z 3 so the dict_proxy for user classes is writable but >>> int.__dict__ >>> int.z = 3 Traceback (most recent call last): File "", line 1, in int.z = 3 TypeError: can't set attributes of built-in/extension type 'int' wheres for builtins, it is not. Terry Jan Reedy From hetchkay at gmail.com Thu Apr 1 14:35:14 2010 From: hetchkay at gmail.com (hetchkay) Date: Thu, 1 Apr 2010 11:35:14 -0700 (PDT) Subject: question on namedtuple Message-ID: <725a6040-cc29-48da-8423-f3addc52785d@k19g2000yqn.googlegroups.com> Hi, For purposes I don't want to go into here, I have the following code: def handleObj(obj): if isinstance(obj, MyType): return obj.handle() elif isinstance(obj, (list, tuple, set)): return obj.__class__(map (handleObj, obj)) elif isinstance(obj, dict): return obj.__class__((handleObj(k), handleObj(v)) for k, v in obj.items()) else: return obj This works fine except if obj is a namedtuple. A namedtuple object has different constructor signature from tuple: >>> tuple([1,2]) (1,2) >>> collections.namedtuple("sample", "a, b")([1, 2]) Traceback (most recent call last): File "CommandConsole", line 1, in TypeError: __new__() takes exactly 3 arguments (2 given) >>> collections.namedtuple("sample", "a, b")(1, 2) sample(a=1, b=2) Is there any easy way of knowing that the obj is a namedtuple and not a plain tuple [so that I could use obj.__class__(*map(handleObj, obj)) instead of obj.__class__(map(handleObj, obj)) ]. Thanks in advance for your help. Krishnan From anirbans at cs.ubc.ca Thu Apr 1 14:56:04 2010 From: anirbans at cs.ubc.ca (Ani) Date: Thu, 1 Apr 2010 11:56:04 -0700 (PDT) Subject: folks, what's wrong with this? Message-ID: Hi All: I am just a beginner in python. Can anyone please tell me what is wrong with this piece of code? import copy class BaseDummyObject(object): def __init__(self): pass def __getattr__(self, item): try: return self.__dict__.__getitem__(item) except KeyError: print "Attribute Error: attr %s of class %s non-existent!" %(item, self.__class__.__name__) class DummyObject(BaseDummyObject): pass def main(): bar = 3 obj = DummyObject() obj.foo = bar obj.me = obj newobj = copy.deepcopy(obj) if __name__ == "__main__": main() So when I do this, I get: Attribute Error: attr __deepcopy__ of class DummyObject non-existent! Attribute Error: attr __getnewargs__ of class DummyObject non- existent! Traceback (most recent call last): File "C:\Workspace\QA3.0\Python_Lib\Mobidia\RemoteManager \test_code.py", line 39, in main() File "C:\Workspace\QA3.0\Python_Lib\Mobidia\RemoteManager \test_code.py", line 30, in main newobj = copy.deepcopy(obj) File "C:\Python26\lib\copy.py", line 181, in deepcopy rv = reductor(2) TypeError: 'NoneType' object is not callable Any help will be really appreciated. From robert.kern at gmail.com Thu Apr 1 15:10:51 2010 From: robert.kern at gmail.com (Robert Kern) Date: Thu, 01 Apr 2010 14:10:51 -0500 Subject: folks, what's wrong with this? In-Reply-To: References: Message-ID: On 2010-04-01 13:56 PM, Ani wrote: > Hi All: > > I am just a beginner in python. Can anyone please tell me what is > wrong with this piece of code? > > import copy > class BaseDummyObject(object): > > def __init__(self): > pass > > def __getattr__(self, item): > try: > return self.__dict__.__getitem__(item) > except KeyError: > print "Attribute Error: attr %s of class %s non-existent!" > %(item, > > self.__class__.__name__) You need to raise an AttributeError here. Otherwise, it implicitly returns None for all attributes not in the __dict__ and thus confusing the copy.deepcopy() code. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From ethan at stoneleaf.us Thu Apr 1 15:14:35 2010 From: ethan at stoneleaf.us (Ethan Furman) Date: Thu, 01 Apr 2010 12:14:35 -0700 Subject: Python 3.1, object, and setattr() In-Reply-To: <4BB4A3B9.8010709@stoneleaf.us> References: <4BB4A3B9.8010709@stoneleaf.us> Message-ID: <4BB4F09B.8070203@stoneleaf.us> Many thanks for the replies, and especially for the very detailed explanation. Makes much more sense now. ~Ethan~ From clp2 at rebertia.com Thu Apr 1 15:45:31 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Thu, 1 Apr 2010 12:45:31 -0700 Subject: no module named exceptions? In-Reply-To: References: <4dabb1e4-4735-4e85-a61e-1c4cf1ccbea3@r1g2000yqj.googlegroups.com> Message-ID: > On Thu, Apr 1, 2010 at 10:42 PM, Joaquin Abian wrote: >> In python 3.1, >> >> >>> import exceptions >> Traceback (most recent call last): >> File "", line 1, in >> import exceptions >> ImportError: No module named exceptions >> >> in 2.6 no exception is raised >> It should be the same in 3.1, isnt it? On Thu, Apr 1, 2010 at 10:37 AM, Tommy Grav wrote: > This is what he is expecting. Importing exceptions works fine in 2.6.4, not > so > in python 3.1. > Python 2.6.4 (r264:75706, Nov ?3 2009, 18:12:54) > [GCC 4.2.1 (Apple Inc. build 5646) (dot 1)] on darwin > Type "help", "copyright", "credits" or "license" for more information. >>>> import exceptions >>>> It appears to have been removed between Python 3.1.2 (http://docs.python.org/py3k/modindex.html#cap-E) and Python 3.2a0 (http://docs.python.org/dev/py3k/modindex.html#cap-E). Exactly why, I don't know. I wasn't able to locate anything about it in a quick scan of the Python 3000 PEPs. Cheers, Chris -- http://blog.rebertia.com From open2day82 at gmail.com Thu Apr 1 16:03:33 2010 From: open2day82 at gmail.com (emely) Date: Thu, 1 Apr 2010 13:03:33 -0700 (PDT) Subject: Free >> Programs > books profit > affiliate Message-ID: <26508148-46aa-4d31-ae5b-bf9ad1c8caa1@q23g2000yqd.googlegroups.com> Free >> Programs > books profit > affiliate Free >> Programs of rare books profit education Forex & affiliate banned from display Emergency Room inclusive of all the few programs http://echance.info/download/133 Books cylinder profit http://echance.info/download/134 Cylinder Forex Education Video http://echance.info/download/131 Cylinder education affiliate Video http://echance.info/download/79 Download the movie is banned from displ http://echance.info/download/135 GAMES FREE http://echance.info/games Free Proxy http://open2day.t35.com http://sif4ever.t35.com From open2day82 at gmail.com Thu Apr 1 16:04:10 2010 From: open2day82 at gmail.com (emely) Date: Thu, 1 Apr 2010 13:04:10 -0700 (PDT) Subject: Free >> Programs of rare books profit education Forex & affiliate banned from display Message-ID: Free >> Programs > books profit > affiliate Emergency Room inclusive of all the few programs http://echance.info/download/133 Books cylinder profit http://echance.info/download/134 Cylinder Forex Education Video http://echance.info/download/131 Cylinder education affiliate Video http://echance.info/download/79 Download the movie is banned from displ http://echance.info/download/135 GAMES FREE http://echance.info/games Free Proxy http://open2day.t35.com http://sif4ever.t35.com From clp2 at rebertia.com Thu Apr 1 16:04:25 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Thu, 1 Apr 2010 13:04:25 -0700 Subject: question on namedtuple In-Reply-To: <725a6040-cc29-48da-8423-f3addc52785d@k19g2000yqn.googlegroups.com> References: <725a6040-cc29-48da-8423-f3addc52785d@k19g2000yqn.googlegroups.com> Message-ID: On Thu, Apr 1, 2010 at 11:35 AM, hetchkay wrote: > Hi, > For purposes I don't want to go into here, I have the following code: > def handleObj(obj): > ?if isinstance(obj, MyType): > ? ? return obj.handle() > ?elif isinstance(obj, (list, tuple, set)): > ? ? return obj.__class__(map (handleObj, obj)) > ?elif isinstance(obj, dict): > ? ? return obj.__class__((handleObj(k), handleObj(v)) for k, v in > obj.items()) > ?else: > ? ? return obj > > This works fine except if obj is a namedtuple. A namedtuple object has > different constructor signature from tuple: >>>> tuple([1,2]) > (1,2) >>>> collections.namedtuple("sample", "a, b")([1, 2]) > Traceback (most recent call last): > ?File "CommandConsole", line 1, in > TypeError: __new__() takes exactly 3 arguments (2 given) >>>> collections.namedtuple("sample", "a, b")(1, 2) > sample(a=1, b=2) > > Is there any easy way of knowing that the obj is a namedtuple and not > a plain tuple [so that I could use obj.__class__(*map(handleObj, obj)) > instead of obj.__class__(map(handleObj, obj)) ]. It's very slightly brittle, but a good heuristic is probably: if isinstance(obj, tuple) and all(hasattr(obj, attr_name) for \ attr_name in ('_make','_fields','_replace','_asdict')): return obj.__class__(*map(handleObj, obj)) I couldn't find/think of a more direct/reliable method. Though perhaps there's some more obscure but accurate method. Cheers, Chris -- http://blog.rebertia.com From gherron at digipen.edu Thu Apr 1 16:10:34 2010 From: gherron at digipen.edu (Gary Herron) Date: Thu, 01 Apr 2010 13:10:34 -0700 Subject: no module named exceptions? In-Reply-To: <4dabb1e4-4735-4e85-a61e-1c4cf1ccbea3@r1g2000yqj.googlegroups.com> References: <4dabb1e4-4735-4e85-a61e-1c4cf1ccbea3@r1g2000yqj.googlegroups.com> Message-ID: <4BB4FDBA.1050802@digipen.edu> Joaquin Abian wrote: > In python 3.1, > > >>>> import exceptions >>>> > Traceback (most recent call last): > File "", line 1, in > import exceptions > ImportError: No module named exceptions > > in 2.6 no exception is raised > It should be the same in 3.1, isnt it? > > Joaquin > In 2.x, the exceptions module was imported automatically, so there was never a need to explicitly import it. For example: Python 2.6.4 (r264:75706, Dec 7 2009, 18:45:15) [GCC 4.4.1] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> print ImportError In Python 3.x, it appears the same effect is achieved by putting the Exceptions in the builtin module For example: Python 3.1.1+ (r311:74480, Nov 2 2009, 14:49:22) [GCC 4.4.1] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> print(ImportError) And another example: >>> import builtins >>> print(builtins.ImportError) -- Gary Herron, PhD. Department of Computer Science DigiPen Institute of Technology (425) 895-4418 From nad at acm.org Thu Apr 1 16:16:06 2010 From: nad at acm.org (Ned Deily) Date: Thu, 01 Apr 2010 13:16:06 -0700 Subject: no module named exceptions? References: <4dabb1e4-4735-4e85-a61e-1c4cf1ccbea3@r1g2000yqj.googlegroups.com> Message-ID: In article , Chris Rebert wrote: > > On Thu, Apr 1, 2010 at 10:42 PM, Joaquin Abian wrote: > >> In python 3.1, > >> > >> >>> import exceptions > >> Traceback (most recent call last): > >> File "", line 1, in > >> import exceptions > >> ImportError: No module named exceptions > >> > >> in 2.6 no exception is raised > >> It should be the same in 3.1, isnt it? > > On Thu, Apr 1, 2010 at 10:37 AM, Tommy Grav wrote: > > This is what he is expecting. Importing exceptions works fine in 2.6.4, not > > so > > in python 3.1. > > Python 2.6.4 (r264:75706, Nov ?3 2009, 18:12:54) > > [GCC 4.2.1 (Apple Inc. build 5646) (dot 1)] on darwin > > Type "help", "copyright", "credits" or "license" for more information. > >>>> import exceptions > >>>> > > It appears to have been removed between Python 3.1.2 > (http://docs.python.org/py3k/modindex.html#cap-E) and Python 3.2a0 > (http://docs.python.org/dev/py3k/modindex.html#cap-E). Exactly why, I > don't know. I wasn't able to locate anything about it in a quick scan > of the Python 3000 PEPs. The exceptions module doesn't exist in Python 3 but the documentation had not been cleaned up until recently: http://bugs.python.org/issue7590 -- Ned Deily, nad at acm.org From open2day82 at gmail.com Thu Apr 1 16:26:57 2010 From: open2day82 at gmail.com (emely) Date: Thu, 1 Apr 2010 13:26:57 -0700 (PDT) Subject: free proxy & fast Message-ID: <84a4c22a-b2b4-48a3-8a9b-db91d659af2a@k19g2000yqn.googlegroups.com> http://open2day.t35.com http://sif4ever.t35.com From __peter__ at web.de Thu Apr 1 16:36:09 2010 From: __peter__ at web.de (Peter Otten) Date: Thu, 01 Apr 2010 22:36:09 +0200 Subject: question on namedtuple References: <725a6040-cc29-48da-8423-f3addc52785d@k19g2000yqn.googlegroups.com> Message-ID: hetchkay wrote: > For purposes I don't want to go into here, I have the following code: > def handleObj(obj): > if isinstance(obj, MyType): > return obj.handle() > elif isinstance(obj, (list, tuple, set)): > return obj.__class__(map (handleObj, obj)) > elif isinstance(obj, dict): > return obj.__class__((handleObj(k), handleObj(v)) for k, v in > obj.items()) > else: > return obj > > This works fine except if obj is a namedtuple. A namedtuple object has > different constructor signature from tuple: >>>> tuple([1,2]) > (1,2) >>>> collections.namedtuple("sample", "a, b")([1, 2]) > Traceback (most recent call last): > File "CommandConsole", line 1, in > TypeError: __new__() takes exactly 3 arguments (2 given) >>>> collections.namedtuple("sample", "a, b")(1, 2) > sample(a=1, b=2) > > Is there any easy way of knowing that the obj is a namedtuple and not > a plain tuple [so that I could use obj.__class__(*map(handleObj, obj)) > instead of obj.__class__(map(handleObj, obj)) ]. I don't think there is a safe way to do this short of a comprehensive list of namedtuple classes. In practice it may be sufficient to check the duck type of the tuple subclass, e. g.: elif isinstance(obj, (list, set)): return obj.__class__(map(handleObj, obj)) elif isinstance(obj, tuple): try: make = obj._make except AttributeError: make = obj.__class__ return make(handleObj(item) for item in obj) Peter From utente at esempio.net Thu Apr 1 16:44:51 2010 From: utente at esempio.net (superpollo) Date: Thu, 01 Apr 2010 22:44:51 +0200 Subject: off topic but please forgive me me and answer Message-ID: <4bb505c5$0$1133$4fafbaef@reader3.news.tin.it> how much is one half times one half? From rantingrick at gmail.com Thu Apr 1 16:51:33 2010 From: rantingrick at gmail.com (rantingrick) Date: Thu, 1 Apr 2010 13:51:33 -0700 (PDT) Subject: Python + OpenOffice Calc References: <4bb2fe14$0$1120$4fafbaef@reader3.news.tin.it> Message-ID: <3afe372c-a315-4ea0-bf11-137d9a45df25@i25g2000yqm.googlegroups.com> On Apr 1, 4:38?am, "egl... at gmail.com" wrote: > Actually, a spreadsheet based solution isn't best fit for such a task. > I'd recommend to store the data in sqlite3 (also 100% pure python as > the module is in the stdlib). CSV is good for making invoices or > something like that. +1 From piet at vanoostrum.org Thu Apr 1 16:55:46 2010 From: piet at vanoostrum.org (Piet van Oostrum) Date: Thu, 01 Apr 2010 22:55:46 +0200 Subject: subprocess only good for win32? References: <353133a8-ff39-4b36-b96d-4836cea621bf@j41g2000vbe.googlegroups.com> Message-ID: >>>>> wukong (w) wrote: >w> also subprocess.py clearly says >w> """ >w> import sys >w> mswindows = (sys.platform == "win32") >w> """ It may sound strange, but even in 64-bit Python on Win64, sys.plattform=="win32". You can check that subprocess is working, e.g. with subprocess.call('dir', shell=True) -- Piet van Oostrum WWW: http://pietvanoostrum.com/ PGP key: [8DAE142BE17999C4] Nu Fair Trade woonwaar op http://www.zylja.com From python.list at tim.thechases.com Thu Apr 1 17:42:57 2010 From: python.list at tim.thechases.com (Tim Chase) Date: Thu, 01 Apr 2010 16:42:57 -0500 Subject: off topic but please forgive me me and answer In-Reply-To: <4bb505c5$0$1133$4fafbaef@reader3.news.tin.it> References: <4bb505c5$0$1133$4fafbaef@reader3.news.tin.it> Message-ID: <4BB51361.4050904@tim.thechases.com> superpollo wrote: > how much is one half times one half? Uh, did you try it at the python prompt? If not, here's the answer: 0.1b * 0.1b = 0.01b Now all you need is to find the recent thread that converts binary floats to decimal floats ;-) -tkc From anirbans at cs.ubc.ca Thu Apr 1 17:52:23 2010 From: anirbans at cs.ubc.ca (Ani) Date: Thu, 1 Apr 2010 14:52:23 -0700 (PDT) Subject: folks, what's wrong with this? References: Message-ID: <9338f2ea-eadc-45cb-be64-c5f5baca9b3c@q23g2000yqd.googlegroups.com> On Apr 1, 12:10?pm, Robert Kern wrote: > On 2010-04-01 13:56 PM, Ani wrote: > > > > > Hi All: > > > I am just a beginner in python. Can anyone please tell me what is > > wrong with this piece of code? > > > import copy > > class BaseDummyObject(object): > > > ? ? ?def __init__(self): > > ? ? ? ? ?pass > > > ? ? ?def __getattr__(self, item): > > ? ? ? ? ?try: > > ? ? ? ? ? ? ?return self.__dict__.__getitem__(item) > > ? ? ? ? ?except KeyError: > > ? ? ? ? ? ? ?print "Attribute Error: attr %s of class %s non-existent!" > > %(item, > > > self.__class__.__name__) > > You need to raise an AttributeError here. Otherwise, it implicitly returns None > for all attributes not in the __dict__ and thus confusing the copy.deepcopy() code. > Thanks Robert. So I raised the exception and now everything looks good. So what's happening here? When a certain attribute is not available in the __dict__ and an exception is raised, who's catching it? Ani From robert.kern at gmail.com Thu Apr 1 18:18:39 2010 From: robert.kern at gmail.com (Robert Kern) Date: Thu, 01 Apr 2010 17:18:39 -0500 Subject: folks, what's wrong with this? In-Reply-To: <9338f2ea-eadc-45cb-be64-c5f5baca9b3c@q23g2000yqd.googlegroups.com> References: <9338f2ea-eadc-45cb-be64-c5f5baca9b3c@q23g2000yqd.googlegroups.com> Message-ID: On 2010-04-01 16:52 PM, Ani wrote: > On Apr 1, 12:10 pm, Robert Kern wrote: >> On 2010-04-01 13:56 PM, Ani wrote: >> >> >> >>> Hi All: >> >>> I am just a beginner in python. Can anyone please tell me what is >>> wrong with this piece of code? >> >>> import copy >>> class BaseDummyObject(object): >> >>> def __init__(self): >>> pass >> >>> def __getattr__(self, item): >>> try: >>> return self.__dict__.__getitem__(item) >>> except KeyError: >>> print "Attribute Error: attr %s of class %s non-existent!" >>> %(item, >> >>> self.__class__.__name__) >> >> You need to raise an AttributeError here. Otherwise, it implicitly returns None >> for all attributes not in the __dict__ and thus confusing the copy.deepcopy() code. >> > > Thanks Robert. So I raised the exception and now everything looks > good. So what's happening here? When a certain attribute is not > available in the __dict__ and an exception is raised, who's catching > it? copy.deepcopy(), in this case, or one of the functions it calls. You can use traceback.print_stack() to see who is attempting to get the attribute. It is checking for certain methods on the object which control how the object gets seralized. copy.deepcopy() uses the same mechanism as pickle to serialize and reconstruct the object in memory. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From no.email at please.post Thu Apr 1 18:34:31 2010 From: no.email at please.post (kj) Date: Thu, 1 Apr 2010 22:34:31 +0000 (UTC) Subject: C-style static variables in Python? Message-ID: When coding C I have often found static local variables useful for doing once-only run-time initializations. For example: int foo(int x, int y, int z) { static int first_time = TRUE; static Mongo *mongo; if (first_time) { mongo = heavy_lifting_at_runtime(); first_time = FALSE; } return frobnicate(mongo, x, y, z); } In this case, the static variable mongo is initialized only once (at most). What I like most about this is that it obviates the need for a global variable to hold the persistent value (I avoid globals like the plague, especially in Python). It also nicely encapsulates the logic that determines whether initialization is required. The best way I've found to achieve a similar effect in (procedural) Python defines the function as a closure. For example, here's a function that keeps track of (and prints out) how many times it has been called: >>> def make_spam(): ... counter = [0] ... def _(): ... counter[0] += 1 ... print counter[0] ... return _ ... >>> spam = make_spam() >>> spam() 1 >>> spam() 2 >>> spam() 3 (Too bad that one can't stick the whole def inside parentheses and call the function right there, like one can do with JavaScript.) Another approach would be to stuff the static values in the function's __dict__. This is less satisfactory than the closure approach because the "pseudo-static" variable is accessible from outside the function, but the code is arguably a little more straightforward, and one does not end up with the now useless one-time closure-generating function kicking around. Here's another version of the function above: >>> def spam(): ... d = spam.__dict__ ... if not 's' in spam.__dict__: ... spam.s = 1 ... print spam.s ... spam.s += 1 ... >>> spam() 1 >>> spam() 2 >>> spam() 3 Besides the external accessibility issue, I don't like explictly coding the name of the function within the function. Is there any way to have the function access its own __dict__ without having to explicitly code its name in its body? E.g., is there some generic special variable that, within a function, refers to the function object itself? I'm sure that there are many other ways to skin this cat, especially if one starts definining fancy callable classes and whatnot. But is there a better *simple* way to achieve C-style static locals in Python that does not require a lot of extra machinery? TIA! ~K From clp2 at rebertia.com Thu Apr 1 18:51:16 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Thu, 1 Apr 2010 15:51:16 -0700 Subject: C-style static variables in Python? In-Reply-To: References: Message-ID: On Thu, Apr 1, 2010 at 3:34 PM, kj wrote: > When coding C I have often found static local variables useful for > doing once-only run-time initializations. > Another approach would be to stuff the static values in the function's > __dict__. ?This is less satisfactory than the closure approach > because the "pseudo-static" variable is accessible from outside > the function, but the code is arguably a little more straightforward, > and one does not end up with the now useless one-time closure-generating > function kicking around. ?Here's another version of the function > above: > >>>> def spam(): > ... ? ? d = spam.__dict__ > ... ? ? if not 's' in spam.__dict__: > ... ? ? ? ? spam.s = 1 > ... ? ? print spam.s > ... ? ? spam.s += 1 > ... >>>> spam() > 1 >>>> spam() > 2 >>>> spam() > 3 > > Besides the external accessibility issue, I don't like explictly > coding the name of the function within the function. ?Is there any > way to have the function access its own __dict__ without having to > explicitly code its name in its body? ?E.g., is there some generic > special variable that, within a function, refers to the function > object itself? Nope. It's been proposed in that past (http://www.python.org/dev/peps/pep-3130/), but that proposal was rejected. > I'm sure that there are many other ways to skin this cat, especially > if one starts definining fancy callable classes and whatnot. ?But > is there a better *simple* way to achieve C-style static locals in > Python that does not require a lot of extra machinery? You can abuse the default argument value mechanism: def spam(s_cell=[1]): s = s_cell[0] print s s_cell[0] += 1 It's a bit less ugly when the value itself is mutable, which isn't the case here with the integer. Personally, I hate such abuse with a passion; I think a global variable is clearest. Cheers, Chris -- http://blog.rebertia.com From fabio at aptana.com Thu Apr 1 19:10:00 2010 From: fabio at aptana.com (Fabio Zadrozny) Date: Thu, 1 Apr 2010 20:10:00 -0300 Subject: Pydev 1.5.6 Released (Django Integration) Message-ID: Hi All, Pydev 1.5.6 has been released Details on Pydev: http://pydev.org Details on its development: http://pydev.blogspot.com Release Highlights: ------------------------------- * Django integration: * New Django project can be created through wizards * Can set an existing project as a Django project (right-click project > pydev > set as django project) * Can remove Django project config (right-click project > django > remove django project config) * Custom actions can be passed to the configured manage.py through ctrl+2+dj django_action -- if no action is passed, will open dialog to choose from a list of previously used commands. * Predefined/custom actions can be used through right-clicking the project > django > select custom action * manage.py location and settings module configured * Django shell (with code-completion, history, etc) available * Run/Debug as Django available * See: http://pydev.org/manual_adv_django.html for more details * Find/Replace: * The search in open files is no longer added in the find/replace dialog and now works through Ctrl+2+s word_to_find (in the Pydev editor) and if no word is passed, the editor selection is used * Go to definiton: * Properly works with unsaved files (so, it will work when searching for a definition on an unsaved file) * Properly working with eclipse 3.6 (having FileStoreEditorInput as the editor input) * Editor: * Automatically closing literals. * Removing closing pair on backspace on literal * Improved heuristics for automatically closing (, [ and { * Removing closing pairs on backspace on (,[ and { * ctrl+2+sl (sl comes from 'split lines' -- can be used to add a new line after each comma in the selection * ctrl+2+is (is comes from 'import string' -- can be used to transform the selected import into a string with dots * General: * Code-completion properly working on relative import with an alias. * Fixed racing issue that could deadlock pydev (under really hard to reproduce circumstances) * Removing reloading code while debugging until (if) it becomes more mature in the python side * Fixed issue where a new project created didn't have the source folder correctly set * Text selection in double click no longer has weird behavior * Local refactoring working on files not in the PYTHONPATH * Edit properly working on string substitution variables * Using with statement on python 2.5 no longer makes lines wrong in the AST What is PyDev? --------------------------- PyDev is a plugin that enables users to use Eclipse for Python, Jython and IronPython 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 Aptana http://aptana.com/python Pydev - Python Development Environment for Eclipse http://pydev.org http://pydev.blogspot.com From steve at holdenweb.com Thu Apr 1 19:10:57 2010 From: steve at holdenweb.com (Steve Holden) Date: Thu, 01 Apr 2010 19:10:57 -0400 Subject: C-style static variables in Python? In-Reply-To: References: Message-ID: Chris Rebert wrote: > On Thu, Apr 1, 2010 at 3:34 PM, kj wrote: >> When coding C I have often found static local variables useful for >> doing once-only run-time initializations. > >> Another approach would be to stuff the static values in the function's >> __dict__. This is less satisfactory than the closure approach >> because the "pseudo-static" variable is accessible from outside >> the function, but the code is arguably a little more straightforward, >> and one does not end up with the now useless one-time closure-generating >> function kicking around. Here's another version of the function >> above: >> >>>>> def spam(): >> ... d = spam.__dict__ >> ... if not 's' in spam.__dict__: >> ... spam.s = 1 >> ... print spam.s >> ... spam.s += 1 >> ... >>>>> spam() >> 1 >>>>> spam() >> 2 >>>>> spam() >> 3 >> >> Besides the external accessibility issue, I don't like explictly >> coding the name of the function within the function. Is there any >> way to have the function access its own __dict__ without having to >> explicitly code its name in its body? E.g., is there some generic >> special variable that, within a function, refers to the function >> object itself? > > Nope. It's been proposed in that past > (http://www.python.org/dev/peps/pep-3130/), but that proposal was > rejected. > >> I'm sure that there are many other ways to skin this cat, especially >> if one starts definining fancy callable classes and whatnot. But >> is there a better *simple* way to achieve C-style static locals in >> Python that does not require a lot of extra machinery? > > You can abuse the default argument value mechanism: > > def spam(s_cell=[1]): > s = s_cell[0] > print s > s_cell[0] += 1 > > It's a bit less ugly when the value itself is mutable, which isn't the > case here with the integer. > > Personally, I hate such abuse with a passion; I think a global > variable is clearest. But the real problem is that the OP is insisting on using purely procedural Python when the problem is screaming for an object-oriented answer. If the function were instead a method then the instance namespace would be the logical place to store the required data. regards Steve regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 See PyCon Talks from Atlanta 2010 http://pycon.blip.tv/ Holden Web LLC http://www.holdenweb.com/ UPCOMING EVENTS: http://holdenweb.eventbrite.com/ From tjreedy at udel.edu Thu Apr 1 19:28:18 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 01 Apr 2010 19:28:18 -0400 Subject: C-style static variables in Python? In-Reply-To: References: Message-ID: On 4/1/2010 6:34 PM, kj wrote: > > > When coding C I have often found static local variables useful for > doing once-only run-time initializations. For example: > > int foo(int x, int y, int z) { > > static int first_time = TRUE; > static Mongo *mongo; > if (first_time) { > mongo = heavy_lifting_at_runtime(); > first_time = FALSE; > } > > return frobnicate(mongo, x, y, z); Global var or class or closure such as below (obviously untested ;=): make_foo() mongo = heavy_lifting_at_runtime(); def _(x,y,z): return frobnicate(mongo, x, y, z) return _ foo = make_foo del make_foo # to make sure it is *never* called again ; Now you only have foo with a hard-to-access private object and no first_time checks when you call it. Terry Jan Reedy From pmaupin at gmail.com Thu Apr 1 19:30:51 2010 From: pmaupin at gmail.com (Patrick Maupin) Date: Thu, 1 Apr 2010 16:30:51 -0700 (PDT) Subject: C-style static variables in Python? References: Message-ID: <4a244c80-408c-412e-811b-7ca027c5e4a2@e7g2000yqf.googlegroups.com> On Apr 1, 6:10?pm, Steve Holden wrote: > Chris Rebert wrote: > > Personally, I hate such abuse with a passion; I think a global > > variable is clearest. > > But the real problem is that the OP is insisting on using purely > procedural Python when the problem is screaming for an object-oriented > answer. > > If the function were instead a method then the instance namespace would > be the logical place to store the required data. In some situations I will use either the default parameter initialization Chris mentioned, or the closure mechanism that the OP presented, but only on code that I am optimizing for speed (local variable lookups, even in nested functions, being much faster than global or instance lookups). If it doesn't need to go fast, globals or instance variables are the way to go. Pat From pmaupin at gmail.com Thu Apr 1 19:34:38 2010 From: pmaupin at gmail.com (Patrick Maupin) Date: Thu, 1 Apr 2010 16:34:38 -0700 (PDT) Subject: off topic but please forgive me me and answer References: <4bb505c5$0$1133$4fafbaef@reader3.news.tin.it> Message-ID: <32d91d4f-616f-404b-afbb-3b97dc380a67@e7g2000yqf.googlegroups.com> On Apr 1, 4:42?pm, Tim Chase wrote: > superpollo wrote: > > how much is one half times one half? > > Uh, did you try it at the python prompt? ?If not, here's the answer: > > ? 0.1b * 0.1b = 0.01b > > Now all you need is to find the recent thread that converts > binary floats to decimal floats ;-) > > -tkc I thought it was 0b0.1 * 0b0.1 == 0b0.01 Otherwise, you might get it confused with hexadecimal floats :D From Infotechsys at fairpoint.net Thu Apr 1 19:36:16 2010 From: Infotechsys at fairpoint.net (Spencer) Date: Thu, 01 Apr 2010 19:36:16 -0400 Subject: How to run python without python Message-ID: <1270164976.6418.4.camel@spencer-laptop> Is there a way to developing a script on linux and give it to someone on microsoft, so that they could run it on microsoft without installing python? Wayne From krister.svanlund at gmail.com Thu Apr 1 19:46:39 2010 From: krister.svanlund at gmail.com (Krister Svanlund) Date: Fri, 2 Apr 2010 01:46:39 +0200 Subject: How to run python without python In-Reply-To: <1270164976.6418.4.camel@spencer-laptop> References: <1270164976.6418.4.camel@spencer-laptop> Message-ID: On Fri, Apr 2, 2010 at 1:36 AM, Spencer wrote: > Is there a way to developing a script on linux and give it > to someone on microsoft, so that they could run it on microsoft > without installing python? > > Wayne > > -- > http://mail.python.org/mailman/listinfo/python-list > Short answer: No. From steve at holdenweb.com Thu Apr 1 19:48:18 2010 From: steve at holdenweb.com (Steve Holden) Date: Thu, 01 Apr 2010 19:48:18 -0400 Subject: C-style static variables in Python? In-Reply-To: References: Message-ID: Terry Reedy wrote: > On 4/1/2010 6:34 PM, kj wrote: >> >> >> When coding C I have often found static local variables useful for >> doing once-only run-time initializations. For example: >> >> int foo(int x, int y, int z) { >> >> static int first_time = TRUE; >> static Mongo *mongo; >> if (first_time) { >> mongo = heavy_lifting_at_runtime(); >> first_time = FALSE; >> } >> >> return frobnicate(mongo, x, y, z); > > Global var or class or closure such as below (obviously untested ;=): > > make_foo() > mongo = heavy_lifting_at_runtime(); > def _(x,y,z): > return frobnicate(mongo, x, y, z) > return _ > foo = make_foo I suspect you mean foo = make_foo() > del make_foo # to make sure it is *never* called again ; > > Now you only have foo with a hard-to-access private object and no > first_time checks when you call it. > > Terry Jan Reedy > I don't think I'd ever want to use such an obscure technique in a program. You might want to consider using functools.wraps to make sure that the foo function looks right. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 See PyCon Talks from Atlanta 2010 http://pycon.blip.tv/ Holden Web LLC http://www.holdenweb.com/ UPCOMING EVENTS: http://holdenweb.eventbrite.com/ From clp2 at rebertia.com Thu Apr 1 19:54:06 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Thu, 1 Apr 2010 16:54:06 -0700 Subject: How to run python without python In-Reply-To: References: <1270164976.6418.4.camel@spencer-laptop> Message-ID: On Thu, Apr 1, 2010 at 4:46 PM, Krister Svanlund wrote: > On Fri, Apr 2, 2010 at 1:36 AM, Spencer wrote: >> Is there a way to developing a script on linux and give it >> to someone on microsoft, so that they could run it on microsoft >> without installing python? > > Short answer: No. Long answer: No indeed. But if he were to have a Windows computer, he could generate a standalone executable from a Python program using one of the following tools: py2exe: http://www.py2exe.org/ PyInstaller: http://www.pyinstaller.org/ But one can't generate such a standalone executable for a different operating system from that which one's computer runs. Cheers, Chris -- http://blog.rebertia.com From drobinow at gmail.com Thu Apr 1 19:55:27 2010 From: drobinow at gmail.com (David Robinow) Date: Thu, 1 Apr 2010 19:55:27 -0400 Subject: off topic but please forgive me me and answer In-Reply-To: <32d91d4f-616f-404b-afbb-3b97dc380a67@e7g2000yqf.googlegroups.com> References: <4bb505c5$0$1133$4fafbaef@reader3.news.tin.it> <32d91d4f-616f-404b-afbb-3b97dc380a67@e7g2000yqf.googlegroups.com> Message-ID: On Thu, Apr 1, 2010 at 7:34 PM, Patrick Maupin wrote: > On Apr 1, 4:42?pm, Tim Chase wrote: >> superpollo wrote: >> > how much is one half times one half? >> >> Uh, did you try it at the python prompt? ?If not, here's the answer: >> >> ? 0.1b * 0.1b = 0.01b >> >> Now all you need is to find the recent thread that converts >> binary floats to decimal floats ;-) >> >> -tkc > > I thought it was 0b0.1 * 0b0.1 == 0b0.01 > > Otherwise, you might get it confused with hexadecimal floats :D Well, my python says: $ python -c "print 1/2 * 1/2" 0 But that's not what I learned in grade school. (Maybe I should upgrade to 3.1?) From abrahamalrajhi at gmail.com Thu Apr 1 20:25:14 2010 From: abrahamalrajhi at gmail.com (Abethebabe) Date: Thu, 1 Apr 2010 17:25:14 -0700 (PDT) Subject: Good Intermediate Tutorials Message-ID: I've recently finished reading A Byte Of Python and have the basics of Python down. I want to continue practice but I'm unsure what I can do. So I started looking for tutorials to open my mind a little, but everything I come across are beginner tutorials that cover the same topics...over and over. Can anyone point me to good Intermediate tutorials, that don't make use of libraries and such (so I can get really comfortable with the core language.) Maybe even the source code of some simple Python applications, so I can observe and learn the code myself. Really appreciative of any help! From python.list at tim.thechases.com Thu Apr 1 20:49:43 2010 From: python.list at tim.thechases.com (Tim Chase) Date: Thu, 01 Apr 2010 19:49:43 -0500 Subject: off topic but please forgive me me and answer In-Reply-To: References: <4bb505c5$0$1133$4fafbaef@reader3.news.tin.it> <32d91d4f-616f-404b-afbb-3b97dc380a67@e7g2000yqf.googlegroups.com> Message-ID: <4BB53F27.7050306@tim.thechases.com> David Robinow wrote: > $ python -c "print 1/2 * 1/2" > 0 > > But that's not what I learned in grade school. > (Maybe I should upgrade to 3.1?) That's because you need to promote one of them to a float so you get a floating-point result: >>> 1/2 * 1/2 0 >>> 1/2 * 1/2.0 0.0 Oh...wait ;-) -tkc From srosborne at gmail.com Thu Apr 1 21:14:52 2010 From: srosborne at gmail.com (Steve) Date: Thu, 1 Apr 2010 18:14:52 -0700 (PDT) Subject: Browser-based MMOG web framework Message-ID: <8aa532f0-72f9-4cd3-9edd-cea06f4e64c2@z4g2000yqa.googlegroups.com> Hi, I could use some advice on my project. It's a browser-based MMOG: "The High Seas" (working title) Basically it is a trading game set in 1600s or 1700s ... inspirations: Patrician 3, Mine Things, Space Rangers 2, ... Travel between cities takes several days: game updates trading ship positions every 10 minutes. Apart from that it handles player input to buy/sell goods, if their ship is in port. I want the game logic and world state data storage on a webserver, with players connecting via web browser. Also, I want to make an "admin mode" client for me to keep track of the world and add changes to game world stuff. I want to use Python but I haven't ever used it in a web context. http://wiki.python.org/moin/WebFrameworks lists several different options for Python Web Frameworks: Django, Grok, Pylons, TurboGears, web2py, Zope. I've heard of Django and Grok...that's about my level of knowledge here. My question: can any of these frameworks help me with what I'm trying to do? From rantingrick at gmail.com Thu Apr 1 21:27:25 2010 From: rantingrick at gmail.com (rantingrick) Date: Thu, 1 Apr 2010 18:27:25 -0700 (PDT) Subject: Good Intermediate Tutorials References: Message-ID: On Apr 1, 7:25?pm, Abethebabe wrote: > I've recently finished reading A Byte Of Python and have the basics of > Python down. I want to continue practice but I'm unsure what I can do. > So I started looking for tutorials to open my mind a little, but > everything I come across are beginner tutorials that cover the same > topics...over and over. > > Can anyone point me to good Intermediate tutorials, that don't make > use of libraries and such (so I can get really comfortable with the > core language.) Maybe even the source code of some simple Python > applications, so I can observe and learn the code myself. > > Really appreciative of any help! Try "Dive into Python", great tut! http://diveintopython.org/ From alfps at start.no Thu Apr 1 21:37:58 2010 From: alfps at start.no (Alf P. Steinbach) Date: Fri, 02 Apr 2010 03:37:58 +0200 Subject: C-style static variables in Python? In-Reply-To: References: Message-ID: * kj: > When coding C I have often found static local variables useful for > doing once-only run-time initializations. For example: > > int foo(int x, int y, int z) { > > static int first_time = TRUE; > static Mongo *mongo; > if (first_time) { > mongo = heavy_lifting_at_runtime(); > first_time = FALSE; > } > > return frobnicate(mongo, x, y, z); > } > > In this case, the static variable mongo is initialized only once > (at most). > > What I like most about this is that it obviates the need for a > global variable to hold the persistent value (I avoid globals like > the plague, especially in Python). It also nicely encapsulates > the logic that determines whether initialization is required. In C++ you just write int foo( int x, int y, int z ) { static Mongo* const mongo = heavy_lifting_at_runtime(); return frobnicate( mongo, x, y, z ); } > The best way I've found to achieve a similar effect in (procedural) > Python defines the function as a closure. For example, here's a > function that keeps track of (and prints out) how many times it > has been called: > >>>> def make_spam(): > ... counter = [0] > ... def _(): > ... counter[0] += 1 > ... print counter[0] > ... return _ > ... >>>> spam = make_spam() >>>> spam() > 1 >>>> spam() > 2 >>>> spam() > 3 > > (Too bad that one can't stick the whole def inside parentheses and > call the function right there, like one can do with JavaScript.) Off the cuff, Py3: class Spam: def __init__( self ): self._counter = 0 def __call__( self ): self._counter += 1 print( counter ) spam = Spam() spam() spam() spam() [snip] > I'm sure that there are many other ways to skin this cat, especially > if one starts definining fancy callable classes and whatnot. As I see it it's the closure that's fancy, and the class that's simple and direct. > But > is there a better *simple* way to achieve C-style static locals in > Python that does not require a lot of extra machinery? If you often need this functionality you might consider a general decorator that supplies the function with a self argument, e.g. like this: #Py3 class Object: pass def static_initialization( init_func ): def self_aware( f ): def wrapped( *args, **kwargs ): return f( f, *args, **kwargs ) init_func( f ) return wrapped o = Object() o.body = self_aware return o # Example usage: @static_initialization def spam( self ): self.counter = 0 @spam.body def spam( self ): self.counter += 1 print( self.counter ) spam() spam() spam() But as mentioned, a class is (at least IMHO) simpler and more direct. Cheers & hth., - Alf (department of disingenious solutions) From pmaupin at gmail.com Thu Apr 1 22:01:22 2010 From: pmaupin at gmail.com (Patrick Maupin) Date: Thu, 1 Apr 2010 19:01:22 -0700 (PDT) Subject: off topic but please forgive me me and answer References: <4bb505c5$0$1133$4fafbaef@reader3.news.tin.it> <32d91d4f-616f-404b-afbb-3b97dc380a67@e7g2000yqf.googlegroups.com> Message-ID: <0027ef5b-872c-4662-a126-78381e8bb1d3@15g2000yqi.googlegroups.com> On Apr 1, 7:49?pm, Tim Chase wrote: > David Robinow wrote: > > $ python -c "print 1/2 * 1/2" > > 0 > > > ?But that's not what I learned in grade school. > > (Maybe I should upgrade to 3.1?) > > That's because you need to promote one of them to a float so you > get a floating-point result: > > ? ?>>> 1/2 * 1/2 > ? ?0 > ? ?>>> 1/2 * 1/2.0 > ? ?0.0 > > Oh...wait ;-) > > -tkc Hmmm, I think I'm starting to see why we need math.fsum() to take care of those rounding errors... From steve at REMOVE-THIS-cybersource.com.au Thu Apr 1 22:33:28 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 02 Apr 2010 02:33:28 GMT Subject: (a==b) ? 'Yes' : 'No' References: <4bb22b39$0$1638$742ec2ed@news.sonic.net> <861e25b4-96b1-4a12-82d8-9a93cbc3e8da@8g2000yqz.googlegroups.com> Message-ID: <4bb55778$0$8827$c3e8da3@news.astraweb.com> On Thu, 01 Apr 2010 08:27:53 -0700, Den wrote about Python's ternary operator: > I've been following this thread for a few days now. My thoughts are > that, in view of a long known widely used syntax for this operator, > python's syntax seems like change for change sake. If current > programing paradigm provides that particular trinary operator, why > should python's be different from the previously well known one. Yes, I agree, we should be using the previously well known syntax: condition -> value_if_true, value_if_false which was introduced by BCPL in 1966. > For instance, no reasonable language designer would, now, use post-fix > (I know about Forth) Do you also know about Postscript, Factor, Joy and Cat, to mention only a few? And also the native language of Hewlett-Packard scientific calculators, RPL. > or allow only +=, -=, /=, etc. assignments ONLY. > (Just as no reasonable car designer would put the accelerator pedal on > the left.) There are conventions which should span products. Yes > python has the trinary operator and it's not going to change, but this > seems like a bit of petulance on the part of the designer. Unless you have read the PEP that added the operator to the language, and the reasons for rejecting the alternatives, you are not qualified to guess what Guido's motives for choosing the current syntax are. http://www.python.org/dev/peps/pep-0308/ You might not like it, but I do, and I like it far more than the ugly and hard to understand C syntax. In English (which has existed for much longer than C) the question mark punctuation symbol is a sentence terminator, not a separator between clauses, so using ? as an operator has always looked strange and disturbing to me. -- Steven From steve at REMOVE-THIS-cybersource.com.au Thu Apr 1 22:38:04 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 02 Apr 2010 02:38:04 GMT Subject: off topic but please forgive me me and answer References: <4bb505c5$0$1133$4fafbaef@reader3.news.tin.it> <32d91d4f-616f-404b-afbb-3b97dc380a67@e7g2000yqf.googlegroups.com> Message-ID: <4bb5588c$0$8827$c3e8da3@news.astraweb.com> On Thu, 01 Apr 2010 19:55:27 -0400, David Robinow wrote: >>> superpollo wrote: >>> > how much is one half times one half? [...] > Well, my python says: > > $ python -c "print 1/2 * 1/2" > 0 > > But that's not what I learned in grade school. > (Maybe I should upgrade to 3.1?) Python 2.x defaults to integer division, a design error which has been rectified in 3.x. One can do any of these: [steve at sylar ~]$ python3.1 -c "print(1/2 * 1/2)" 0.25 [steve at sylar ~]$ python2.6 -c "from __future__ import division; print 1/2 * 1/2" 0.25 [steve at sylar ~]$ python2.6 -Q new -c "print 1/2 * 1/2" 0.25 [steve at sylar ~]$ python2.6 -c "print 0.5 * 0.5" 0.25 and probably many others as well. -- Steven From steve at REMOVE-THIS-cybersource.com.au Thu Apr 1 22:44:40 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 02 Apr 2010 02:44:40 GMT Subject: off topic but please forgive me me and answer References: <4bb505c5$0$1133$4fafbaef@reader3.news.tin.it> <32d91d4f-616f-404b-afbb-3b97dc380a67@e7g2000yqf.googlegroups.com> Message-ID: <4bb55a18$0$8827$c3e8da3@news.astraweb.com> On Thu, 01 Apr 2010 19:49:43 -0500, Tim Chase wrote: > David Robinow wrote: >> $ python -c "print 1/2 * 1/2" >> 0 >> >> But that's not what I learned in grade school. >> (Maybe I should upgrade to 3.1?) > > That's because you need to promote one of them to a float so you get a > floating-point result: > > >>> 1/2 * 1/2 > 0 > >>> 1/2 * 1/2.0 > 0.0 > > Oh...wait ;-) Tim, I'm sure you know the answer to this, but for the benefit of the Original Poster, the problem is that you need to promote *both* divisions to floating point. Otherwise one of them will give int 0, which gives 0.0 when multiplied by 0.5. >>> 1.0/2 * 1/2.0 0.25 If you want an exact result when multiplying arbitrary fractions, you need to avoid floats and decimals and use Fractions: >>> Fraction(1, 2)**2 Fraction(1, 4) -- Steven From lie.1296 at gmail.com Thu Apr 1 22:50:39 2010 From: lie.1296 at gmail.com (Lie Ryan) Date: Fri, 02 Apr 2010 13:50:39 +1100 Subject: off topic but please forgive me me and answer In-Reply-To: <0027ef5b-872c-4662-a126-78381e8bb1d3@15g2000yqi.googlegroups.com> References: <4bb505c5$0$1133$4fafbaef@reader3.news.tin.it> <32d91d4f-616f-404b-afbb-3b97dc380a67@e7g2000yqf.googlegroups.com> <0027ef5b-872c-4662-a126-78381e8bb1d3@15g2000yqi.googlegroups.com> Message-ID: <4bb55ba8$1@dnews.tpgi.com.au> On 04/02/10 13:01, Patrick Maupin wrote: > On Apr 1, 7:49 pm, Tim Chase wrote: >> David Robinow wrote: >>> $ python -c "print 1/2 * 1/2" >>> 0 >> >>> But that's not what I learned in grade school. >>> (Maybe I should upgrade to 3.1?) >> >> That's because you need to promote one of them to a float so you >> get a floating-point result: >> >> >>> 1/2 * 1/2 >> 0 >> >>> 1/2 * 1/2.0 >> 0.0 >> >> Oh...wait ;-) >> >> -tkc > > Hmmm, I think I'm starting to see why we need math.fsum() to take care > of those rounding errors... hmm? >>> import math >>> math.fsum([1/2, 1/2]) 0.0 it doesn't appear to take care of those rounding errors, not in this case at least. From pmaupin at gmail.com Thu Apr 1 22:58:31 2010 From: pmaupin at gmail.com (Patrick Maupin) Date: Thu, 1 Apr 2010 19:58:31 -0700 (PDT) Subject: off topic but please forgive me me and answer References: <4bb505c5$0$1133$4fafbaef@reader3.news.tin.it> <32d91d4f-616f-404b-afbb-3b97dc380a67@e7g2000yqf.googlegroups.com> <0027ef5b-872c-4662-a126-78381e8bb1d3@15g2000yqi.googlegroups.com> <4bb55ba8$1@dnews.tpgi.com.au> Message-ID: <636c368e-5ac7-47ef-98f6-30a5ec4da9ad@q15g2000yqj.googlegroups.com> On Apr 1, 9:50?pm, Lie Ryan wrote: > On 04/02/10 13:01, Patrick Maupin wrote: > > > > > On Apr 1, 7:49 pm, Tim Chase wrote: > >> David Robinow wrote: > >>> $ python -c "print 1/2 * 1/2" > >>> 0 > > >>> ?But that's not what I learned in grade school. > >>> (Maybe I should upgrade to 3.1?) > > >> That's because you need to promote one of them to a float so you > >> get a floating-point result: > > >> ? ?>>> 1/2 * 1/2 > >> ? ?0 > >> ? ?>>> 1/2 * 1/2.0 > >> ? ?0.0 > > >> Oh...wait ;-) > > >> -tkc > > > Hmmm, I think I'm starting to see why we need math.fsum() to take care > > of those rounding errors... > > hmm? > > >>> import math > >>> math.fsum([1/2, 1/2]) > > 0.0 > > it doesn't appear to take care of those rounding errors, not in this > case at least. you're right! I mis-read the problem. What we REALLY need is a good math.fmul() ;-) From exarkun at twistedmatrix.com Thu Apr 1 22:59:40 2010 From: exarkun at twistedmatrix.com (exarkun at twistedmatrix.com) Date: Fri, 02 Apr 2010 02:59:40 -0000 Subject: Browser-based MMOG web framework In-Reply-To: <8aa532f0-72f9-4cd3-9edd-cea06f4e64c2@z4g2000yqa.googlegroups.com> References: <8aa532f0-72f9-4cd3-9edd-cea06f4e64c2@z4g2000yqa.googlegroups.com> Message-ID: <20100402025940.2779.1007417731.divmod.xquotient.5@localhost.localdomain> On 01:14 am, srosborne at gmail.com wrote: >Hi, I could use some advice on my project. > >It's a browser-based MMOG: "The High Seas" (working title) > >Basically it is a trading game set in 1600s or 1700s ... inspirations: >Patrician 3, Mine Things, Space Rangers 2, ... > >Travel between cities takes several days: game updates trading ship >positions every 10 minutes. Apart from that it handles player input >to buy/sell goods, if their ship is in port. > >I want the game logic and world state data storage on a webserver, >with players connecting via web browser. Also, I want to make an >"admin mode" client for me to keep track of the world and add changes >to game world stuff. > >I want to use Python but I haven't ever used it in a web context. > >http://wiki.python.org/moin/WebFrameworks lists several different >options for Python Web Frameworks: Django, Grok, Pylons, TurboGears, >web2py, Zope. I've heard of Django and Grok...that's about my level >of knowledge here. > >My question: can any of these frameworks help me with what I'm trying >to do? This is something that Twisted and Nevow Athena will probably be really good at doing (a lot better than the ones you've mentioned above, I think). You can find an Athena introduction here (at least for now, the content might move to another site before too long): http://divmodsphinx.funsize.net/nevow/chattutorial/ Jean-Paul From drobinow at gmail.com Thu Apr 1 23:08:01 2010 From: drobinow at gmail.com (David Robinow) Date: Thu, 1 Apr 2010 23:08:01 -0400 Subject: off topic but please forgive me me and answer In-Reply-To: <4bb55a18$0$8827$c3e8da3@news.astraweb.com> References: <4bb505c5$0$1133$4fafbaef@reader3.news.tin.it> <32d91d4f-616f-404b-afbb-3b97dc380a67@e7g2000yqf.googlegroups.com> <4bb55a18$0$8827$c3e8da3@news.astraweb.com> Message-ID: On Thu, Apr 1, 2010 at 10:44 PM, Steven D'Aprano wrote: > On Thu, 01 Apr 2010 19:49:43 -0500, Tim Chase wrote: > >> David Robinow wrote: >>> $ python -c "print 1/2 * 1/2" >>> 0 >>> >>> ?But that's not what I learned in grade school. >>> (Maybe I should upgrade to 3.1?) >> >> That's because you need to promote one of them to a float so you get a >> floating-point result: >> >> ? ?>>> 1/2 * 1/2 >> ? ?0 >> ? ?>>> 1/2 * 1/2.0 >> ? ?0.0 >> >> Oh...wait ;-) > > Tim, I'm sure you know the answer to this, but for the benefit of the > Original Poster, the problem is that you need to promote *both* divisions > to floating point. Otherwise one of them will give int 0, which gives 0.0 > when multiplied by 0.5. > >>>> 1.0/2 * 1/2.0 > 0.25 > > > If you want an exact result when multiplying arbitrary fractions, you > need to avoid floats and decimals and use Fractions: > >>>> Fraction(1, 2)**2 > Fraction(1, 4) I should have known he wouldn't get it. From no.email at nospam.invalid Thu Apr 1 23:32:43 2010 From: no.email at nospam.invalid (Paul Rubin) Date: Thu, 01 Apr 2010 20:32:43 -0700 Subject: C-style static variables in Python? References: Message-ID: <7xbpe2leas.fsf@ruckus.brouhaha.com> kj writes: > When coding C I have often found static local variables useful for > doing once-only run-time initializations. For example: > > int foo(int x, int y, int z) { > static int first_time = TRUE; > static Mongo *mongo; > if (first_time) { ... Here are some cheesy ways. 1. Put an attribute onto the function name: def foo(x, y, z): if foo.first_time: foo.mongo = heavy_lifting_at_runtime() foo.first_time = False ... foo.first_time = True 2. Use a mutable keyword parameter: def foo(x, y, z, wrapped_mongo=[]): if len(wrapped_mongo) == 0: wrapped_mongo.append(heavy_lifting_at_runtime()) mongo = wrapped_mongo[0] ... 3. Streamline the first method a little: def foo(x, y, z): if len(foo.wrapped_mongo == 0): foo.wrapped_mongo.append(heavy_lifting_at_runtime()) mongo = foo.wrapped_mongo[0] ... foo.wrapped_mongo = [] All of these of course don't give as good encapsulation as one might like. From python.list at tim.thechases.com Thu Apr 1 23:34:46 2010 From: python.list at tim.thechases.com (Tim Chase) Date: Thu, 01 Apr 2010 22:34:46 -0500 Subject: off topic but please forgive me me and answer In-Reply-To: <4bb55a18$0$8827$c3e8da3@news.astraweb.com> References: <4bb505c5$0$1133$4fafbaef@reader3.news.tin.it> <32d91d4f-616f-404b-afbb-3b97dc380a67@e7g2000yqf.googlegroups.com> <4bb55a18$0$8827$c3e8da3@news.astraweb.com> Message-ID: <4BB565D6.2030603@tim.thechases.com> Steven D'Aprano wrote: >> That's because you need to promote one of them to a float so you get a >> floating-point result: >> >> >>> 1/2 * 1/2 >> 0 >> >>> 1/2 * 1/2.0 >> 0.0 >> >> Oh...wait ;-) > > Tim, I'm sure you know the answer to this, but for the benefit of the > Original Poster, the problem is that you need to promote *both* divisions > to floating point. Otherwise one of them will give int 0, which gives 0.0 > when multiplied by 0.5. > >>>> 1.0/2 * 1/2.0 > 0.25 You can get away with just promoting one of them...you just have to promote the _correct_ one (one involved in the first division) so that its promotion-of-subresult-to-float carries into all subsequent operations/operators: >>> 1/2 * 1/2 # (((1/2)*1)/2)==(((0)*1)/2) in 2.x 0 >>> 1/2 * 1/2.0 # (((1/2)*1)/2.0)==(((0)*1)/2.0) in 2.x 0.0 >>> 1/2 * 1.0/2 # (((1/2)*1.0)/2)==(((0)*1.0)/2) in 2.x 0.0 >>> 1/2.0 * 1/2 # (((1/2.0)*1)/2) 0.25 >>> 1.0/2 * 1/2 # (((1.0/2)*1)/2) 0.25 I'd rather be explicit in *real* code that I'd write and explicitly float'ify constants or float() integer variables. The OP's question was both OT and pretty basic middle-school math that google would have nicely answered[1] so IMHO warranted a bit of fun. :) -tkc [1] http://www.google.com/search?q=1%2F2+*+1%2F2 From lie.1296 at gmail.com Fri Apr 2 00:06:35 2010 From: lie.1296 at gmail.com (Lie Ryan) Date: Fri, 02 Apr 2010 15:06:35 +1100 Subject: Good Intermediate Tutorials In-Reply-To: References: Message-ID: <4bb56d74$1@dnews.tpgi.com.au> On 04/02/10 11:25, Abethebabe wrote: > I've recently finished reading A Byte Of Python and have the basics of > Python down. I want to continue practice but I'm unsure what I can do. > So I started looking for tutorials to open my mind a little, but > everything I come across are beginner tutorials that cover the same > topics...over and over. In programming, if you've gone past the beginner level, the only text you ever need is the reference manual. If you want to broaden your mind, you may want to learn other languages that have distinctly different paradigms than the ones you already know. Then when you get back to python, you will be able to see new angles to attack a problem from. > Can anyone point me to good Intermediate tutorials, that don't make > use of libraries and such (so I can get really comfortable with the > core language.) Maybe even the source code of some simple Python > applications, so I can observe and learn the code myself. > > Really appreciative of any help! Strengthen your math, specifically discrete math; many problems are just different manifestations of a few classes of problem. You can leverage developing completely new methods and new ideas by abstracting your problem to find out the the class of problem your problem belongs to. (contrived analogy: a head chef need to determine whether the remaining ingredients will suffice for the day; a bricklayer need to determine the number of bricks he need to buy for a span of wall; those problems has a common solution: counting and number division). In short, read a book about math and/or problem solving. Recommendations: The Art of Computer Programming by D.E. Knuth, Algorithm Design Manual by S.S. Skiena. Frequent the mailing list. Only by then you will learn to write "idiomatic python"; a book can be compiled about common python idioms but they will more-or-less be the author's perspective of the idioms instead of actual python's idioms. I found that, in python at least, avoiding use of library often forces you to write non-idiomatic python because many libraries are written specifically because it is difficult to write the equivalent efficient code with idiomatic python. In short, don't avoid the library if you want to learn idiomatic python. (if you want to learn about the algorithms though, avoiding libraries is a fine restriction) From showell30 at yahoo.com Fri Apr 2 00:16:18 2010 From: showell30 at yahoo.com (Steve Howell) Date: Thu, 1 Apr 2010 21:16:18 -0700 (PDT) Subject: (a==b) ? 'Yes' : 'No' References: Message-ID: On Mar 30, 8:40?am, gentlestone wrote: > Hi, how can I write the popular C/JAVA syntax in Python? > > Java example: > ? ? return (a==b) ? 'Yes' : 'No' > > ; first idea is: > ? ? return ('No','Yes')[bool(a==b)] > > Is there a more elegant/common python expression for this? The ironic thing about the ternary operator is that it is not really ternary; it's binary. Even just making an expression from a binary operator inevitably leads to syntax hell. There is a principle of programming that I would like to coin, which is the "Tyranny of Three." It is impossible to code for any expression that has three possible values in any kind of elegant way. It's just impossible. Try to code the bowling game without tearing out your teeth--three conditions: strike, spare, or normal. The tyranny of three is that 3 is too small for an elegant N-based solution and too large for a simple condition. From ysj.ray at gmail.com Fri Apr 2 00:34:05 2010 From: ysj.ray at gmail.com (Ray Allen) Date: Fri, 2 Apr 2010 12:34:05 +0800 Subject: Good Intermediate Tutorials In-Reply-To: <4bb56d74$1@dnews.tpgi.com.au> References: <4bb56d74$1@dnews.tpgi.com.au> Message-ID: In my opinion, the python official documents, include the tutorial, language reference, library reference, distributing python modules, also extending and embedding, Python/C API, are all what you need to learn python and use it, as long as you can read into it. Also you can read other python programs. If you want to know more you can read the cpython source itself. Its not too difficult. -- Ray Allen Best wishes! -------------- next part -------------- An HTML attachment was scrubbed... URL: From pmaupin at gmail.com Fri Apr 2 01:25:37 2010 From: pmaupin at gmail.com (Patrick Maupin) Date: Thu, 1 Apr 2010 22:25:37 -0700 (PDT) Subject: off topic but please forgive me me and answer References: <4bb505c5$0$1133$4fafbaef@reader3.news.tin.it> Message-ID: On Apr 1, 11:52?pm, Dennis Lee Bieber wrote: > On Thu, 01 Apr 2010 22:44:51 +0200, superpollo > declaimed the following in gmane.comp.python.general: > > > how much is one half times one half? > > import math > print math.exp((math.log(1) - math.log(2)) > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?+ (math.log(1) - math.log(2))) That's all well and good, but base 'e' is kind of complicated. Some of us were using base 10, and others took Tim's lead and were using base 2: >>> print math.exp(((math.log(1)/math.log(2) - math.log(2)/math.log(2)) + (math.log(1)/math.log(2) - math.log(2)/math.log(2)))*math.log(2)) 0.25 From steve at REMOVE-THIS-cybersource.com.au Fri Apr 2 01:40:45 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 02 Apr 2010 05:40:45 GMT Subject: off topic but please forgive me me and answer References: <4bb505c5$0$1133$4fafbaef@reader3.news.tin.it> <32d91d4f-616f-404b-afbb-3b97dc380a67@e7g2000yqf.googlegroups.com> <4bb55a18$0$8827$c3e8da3@news.astraweb.com> Message-ID: <4bb5835d$0$8827$c3e8da3@news.astraweb.com> On Thu, 01 Apr 2010 22:34:46 -0500, Tim Chase wrote: >> Tim, I'm sure you know the answer to this, but for the benefit of the >> Original Poster, the problem is that you need to promote *both* >> divisions to floating point. Otherwise one of them will give int 0, >> which gives 0.0 when multiplied by 0.5. >> >>>>> 1.0/2 * 1/2.0 >> 0.25 > > You can get away with just promoting one of them...you just have to > promote the _correct_ one Doh! Of course you do. I knew that! -- Steven From timr at probo.com Fri Apr 2 02:29:26 2010 From: timr at probo.com (Tim Roberts) Date: Thu, 01 Apr 2010 23:29:26 -0700 Subject: Developement Question? References: Message-ID: <1j3br5pqu0tmja5qtg4po9o4pblkmsl5pu@4ax.com> Wayne wrote: > >My town office uses Microsoft operating system. They have a proprietary >accounting system that uses excel for their accounting reports. >I would like to read these report and reproduce the report so that >the report can be seen on the web. If it were me, I'd just have Excel print to a PDF. No conversion, no scripting. There are a number of open source PDF converters. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From peter at www.pjb.com.au Fri Apr 2 03:53:44 2010 From: peter at www.pjb.com.au (Peter Billam) Date: 02 Apr 2010 07:53:44 GMT Subject: PyGame migrating to JavaScript Message-ID: Startling news from http://pygame.org/news.html : pygame rewritten for javascript - Apr 1, 2010 Javascript in recent years has been getting better and better, and now is a way better language than python. So to keep up with the times pygame has been rewritten for javascript. Please prepare your codebase with the py2js tool, which tries to automatically convert your python code into javascript. Hopefully with a few years everyone will have upgraded their code, and it will be wonderful. I hope you all will enjoy this change to javascript. Further news, and release binaries to be announced *very* soon. I'm sure anyone who's spent time writing JavaScript will agree completely with the fact that this fascinating news item was released just yesterday (today being the second of April). It's exciting that release binaries will be available - er, to be more precise, will be announced - very soon. Perhaps even in 364 days time? Don't be left behind ! Peter -- Peter Billam www.pjb.com.au www.pjb.com.au/comp/contact.html From contact at xavierho.com Fri Apr 2 04:09:31 2010 From: contact at xavierho.com (Xavier Ho) Date: Fri, 2 Apr 2010 18:09:31 +1000 Subject: PyGame migrating to JavaScript In-Reply-To: References: Message-ID: Javascript in recent years has been getting better and better, and > now is a way better language than python. So to keep up with the > times pygame has been rewritten for javascript. > *shudders* Can someone convince me why that is a good idea at all? Any rationales? Cheers, -Xav -------------- next part -------------- An HTML attachment was scrubbed... URL: From gherron at digipen.edu Fri Apr 2 04:19:23 2010 From: gherron at digipen.edu (Gary Herron) Date: Fri, 02 Apr 2010 01:19:23 -0700 Subject: PyGame migrating to JavaScript In-Reply-To: References: Message-ID: <4BB5A88B.2080906@digipen.edu> Xavier Ho wrote: > Javascript in recent years has been getting better and better, and > > now is a way better language than python. So to keep up with the > times pygame has been rewritten for javascript. > > > *shudders* > > Can someone convince me why that is a good idea at all? Any rationales? > > Cheers, > -Xav It's a joke -- see http://en.wikipedia.org/wiki/April_Fools%27_Day -- Gary Herron, PhD. Department of Computer Science DigiPen Institute of Technology (425) 895-4418 From contact at xavierho.com Fri Apr 2 04:23:27 2010 From: contact at xavierho.com (Xavier Ho) Date: Fri, 2 Apr 2010 18:23:27 +1000 Subject: PyGame migrating to JavaScript In-Reply-To: <4BB5A88B.2080906@digipen.edu> References: <4BB5A88B.2080906@digipen.edu> Message-ID: On Fri, Apr 2, 2010 at 6:19 PM, Gary Herron wrote: > It's a joke -- see http://en.wikipedia.org/wiki/April_Fools%27_Da D'oh! Can't believe that got me. (It's already 2nd of April... you're not supposed to make that joke now! =p) Cheers, Xav -------------- next part -------------- An HTML attachment was scrubbed... URL: From bruno.42.desthuilliers at websiteburo.invalid Fri Apr 2 04:45:26 2010 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Fri, 02 Apr 2010 10:45:26 +0200 Subject: folks, what's wrong with this? In-Reply-To: References: Message-ID: <4bb5ae61$0$10227$426a34cc@news.free.fr> Ani a ?crit : > Hi All: > > I am just a beginner in python. Can anyone please tell me what is > wrong with this piece of code? Robert already addressed your problem, so I'll just comment on a couple other points: > import copy > class BaseDummyObject(object): > > def __init__(self): > pass This initializer is at best useless. > def __getattr__(self, item): The second parameter to __getattr__ is the name that is looked for, so better to name it "name" or "attrname" or... > try: > return self.__dict__.__getitem__(item) __getitem__ - like most __magicmethods__ - provides support for the "subscript" operator, and as such is not supposed to be explicitely called (except for a couple corner cases). This should just be: return self.__dict__[item] > except KeyError: > print "Attribute Error: attr %s of class %s non-existent!" > %(item, self.__class__.__name__) The canonical AttributeError message is "'' object has no attribute ''" - ok, doesn't matter much, but being consistent with the core language is usually a good idea IMHO !-) And now for the most import point: __getattr__ is only called as a *last* resort. That is, after the attribute lookup mechanism will have tried *and failed* to find the name in the instance's __dict__. HTH From durumdara at gmail.com Fri Apr 2 04:54:44 2010 From: durumdara at gmail.com (durumdara) Date: Fri, 02 Apr 2010 10:54:44 +0200 Subject: Python and read archives? Message-ID: Hi! I want to make a multios (Win/Lin) Python based media catalog program, but I have a little problem with reading archives. Ok, Python supports zip and tar, but the world have more archives, like "rar", "7z", "tar.gz", "gz", etc. First I was happy with 7z.exe, because it is knows many formats, and 7z L "filename" command can retreive the list of files. Great! - I thought... But later I realized that password protection is halt the the 7z with password prompt. And I cannot ignore this with options as I see. So: I search for a solution to read archives (only filenames) if possible. I saw that 7z have callable dll, but I don't know, how to use it from python. Do you knows about a tool, or a code to read these archives, or or or...? Thanks for your help: dd -- Az Opera forradalmian ?j levelez?j?t haszn?lva: http://www.opera.com/mail/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From joe.p.cool at googlemail.com Fri Apr 2 05:02:24 2010 From: joe.p.cool at googlemail.com (Joe P. Cool) Date: Fri, 2 Apr 2010 02:02:24 -0700 (PDT) Subject: idle 2.x and unicode literals Message-ID: <60b0f645-8dd2-4638-b2eb-e54c680d3483@y17g2000yqd.googlegroups.com> Hi, I'm working with Python 2.6.4 on Ubuntu 9.10 and noticed a difference between IDLE and command line python. If I enter an ? (accented e, LATIN SMALL LETTER E WITH ACUTE) as a unicode string in command line python I get this: >>> u'?' u'\xe9' In IDLE 2.6.4 I get this: >>> u'?' u'\xc3\xa9' IDLE is set to UTF-8 and console environment has LANG = en_US.UTF-8. This is a bit annyoing because ord(u'?') works on the command line but raises an exception in IDLE: >>> ord(u'?') Traceback (most recent call last): File "", line 1, in ord(u'?') TypeError: ord() expected a character, but string of length 2 found Is this a bug? IDLE 3.1.1 works. Cheers, Joe From steve at REMOVE-THIS-cybersource.com.au Fri Apr 2 05:04:39 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 02 Apr 2010 09:04:39 GMT Subject: (a==b) ? 'Yes' : 'No' References: Message-ID: <4bb5b326$0$8827$c3e8da3@news.astraweb.com> On Thu, 01 Apr 2010 21:16:18 -0700, Steve Howell wrote: > The ironic thing about the ternary operator is that it is not really > ternary; it's binary. Even just making an expression from a binary > operator inevitably leads to syntax hell. > > There is a principle of programming that I would like to coin, which is > the "Tyranny of Three." > > It is impossible to code for any expression that has three possible > values in any kind of elegant way. It's just impossible. Try to code > the bowling game without tearing out your teeth--three conditions: > strike, spare, or normal. > > The tyranny of three is that 3 is too small for an elegant N-based > solution and too large for a simple condition. I'm afraid I don't understand any of that. Can you explain further? How is the ternary operator "not really ternary, it's binary"? It requires three arguments, not two, which makes it ternary. In Python syntax: value1 if flag else value2 or in C: flag ? value1 : value2 You say that "Even just making an expression from a binary operator inevitably leads to syntax hell." I don't understand what you mean. What is so hellish about any of these? a + b # infix a b + # postfix, familiar to anyone who has programmed HP calculators add(a, b) # prefix function notation + a b # prefix add a to b # verbose English-like Well, perhaps the infix notation counts as "unusual", and the last as "too verbose", but hellish? -- Steven From jebagnanadas at gmail.com Fri Apr 2 06:05:48 2010 From: jebagnanadas at gmail.com (Jebagnana Das) Date: Fri, 2 Apr 2010 15:35:48 +0530 Subject: pynotify for python 3.1.. Help Please.. Message-ID: Hello all, I'm trying to display system notifications in ubuntu.. I've tested pynotify in python 2.6 and it's working fine.. I want to know if i can do the same with python 3? I tried but there is no module named pynotify error is displayed.. Any of your help would be much appreciated.. -------------- next part -------------- An HTML attachment was scrubbed... URL: From theller at ctypes.org Fri Apr 2 06:12:22 2010 From: theller at ctypes.org (Thomas Heller) Date: Fri, 02 Apr 2010 12:12:22 +0200 Subject: Splitting a string Message-ID: Maybe I'm just lazy, but what is the fastest way to convert a string into a tuple containing character sequences and integer numbers, like this: 'si_pos_99_rep_1_0.ita' -> ('si_pos_', 99, '_rep_', 1, '_', 0, '.ita') Thanks for ideas, Thomas From contact at xavierho.com Fri Apr 2 06:13:16 2010 From: contact at xavierho.com (Xavier Ho) Date: Fri, 2 Apr 2010 20:13:16 +1000 Subject: pynotify for python 3.1.. Help Please.. In-Reply-To: References: Message-ID: Hi Jebamnana, You'll probably have to copy the pynotify contents to the Python 3.1 folder. (under Libs\site-packages). You should be able to find the folder in the Python 2.6 paths. Once you do that, you can try to use it. But I don't know if pynotify will be able to run with Python 3.1. For instance, you might have to look into the source code and make some changes. Better to consult with the author(s) of pynotify and consult them about the difficulty to port to Py3. Cheers, Xav On Fri, Apr 2, 2010 at 8:05 PM, Jebagnana Das wrote: > Hello all, > > I'm trying to display system notifications in ubuntu.. I've tested > pynotify in python 2.6 and it's working fine.. I want to know if i can do > the same with python 3? I tried but there is no module named pynotify error > is displayed.. Any of your help would be much appreciated.. > > -- > http://mail.python.org/mailman/listinfo/python-list > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From contact at xavierho.com Fri Apr 2 06:13:51 2010 From: contact at xavierho.com (Xavier Ho) Date: Fri, 2 Apr 2010 20:13:51 +1000 Subject: pynotify for python 3.1.. Help Please.. In-Reply-To: References: Message-ID: On Fri, Apr 2, 2010 at 8:13 PM, Xavier Ho wrote: > Hi Jebamnana, > Jebagnana* Sorry. -Xav -------------- next part -------------- An HTML attachment was scrubbed... URL: From marty.musatov at gmail.com Fri Apr 2 06:14:25 2010 From: marty.musatov at gmail.com (A Serious Moment) Date: Fri, 2 Apr 2010 03:14:25 -0700 (PDT) Subject: Hey Sci.Math, Musatov here. I know I've posted a lot of weird stuff trying to figure things out, but I really think I am onto something here and need some bright minds to have a look at this, computer people, too. Thank you for your time. Message-ID: SPARSE COMPLETE SETS FOR NP: SOLUTION OF A CONJECTURE BY MARTIN MICHAEL MUSATOV * for llP: Sparse Comp1ete Sets Solution of a Conjecture In this paper we show if NP has a sparse complete set under many-one reductions, then ? NP. The result is extended to show NP is sparse reducible, then P = ip. The main technicues:technical cues and techniques of this paper generalize the :;P 'recognizer' for the compliment of a sparse complete set with census function to the case where the census function is not 1'? own (c.f. [1? ii]) than a many-one reduction of tI: gives us the language to the sparse set permits a polynomial time bounded tree search as in [ti, [F], or [?:P]. Even without actual knowledge of the census, the algorithm utilizes the properties of the true census to decide membership in SAT in polynomial time. Sparse Complete Sets for `LP: Solution of a Conjecture by Martin Michael Musatov 1. Computer Science L. ? nan and J. 1? at?:i is [tH] under the assumption P? i?. P all llP-complete sets are iso-morphic; i.e. there are polynomial time, bijective reductions with polynomial time inverse reductions between any two NP-cot-:complete sets. A consequence of this conjecture is all NP-complete sets have equivalent density; in particular, no sparse set could be i-complete unless PP. 13e ? an EB] give a partial solution to the problem: by showing if a subset of an SL i? language is NP-co:complete (a for ti or i, sparse), then P = 1;P. This result is strengthened by Fortune [F] showing if co-NP has a sparse complete set, then P = 1p? It is necessary to assume the satisfiable formulas reduce to a sparse set since the proof uses the conjunctive self-reducibility of non- satisfiable for:formulas and the sparse set to realize a polynomial time algorithm. N and P at e[?2] show similar results. ll a rttq a n is and f[E14] extends the results of Fortune and NP at e by showing if l IP has a sparse complete set with an easily computable census function, then NP = co-I?P; P = tT. P follows by Fortune 1s the or e?. The question of how easy it is to compute census functions for l?- complete sets is left open. In light of Fortune's observation about co-I r 1 the original conjecture by ten? a n and ll at i?a n is on reducing `?` to a sparse set series temptingly close, however the tree search methods of [B], [1], [i,:p] utilize the conjunctive self-reducibility of the co-l;P- cot?NP-complete problem SAT0. In this paper we settle the conjecture by showing if an L'P-complete set is ? any-one reducible to a sparse set, then P = i?. Thus determining the existence of a sparse co-??:complete set for l;p is equivalent to solving the P = NP? problem. We also show the census function of a sparse NP-co?i:complete set is cota:computable in P. Section 2 contains definitions an outline of the tree search time method for showing sparse sets for co-NP i? implies P = ??1. Section 3 contains the ? a in results; it assumes n familiarity with the tree search methods. ?. Preliminaries We will consider languages over an alphabet ? with two or or e sy?- symbols. We assume fa?:familiarity with NP--Hcor?:complete sets (cf. Ec], [K] or EAHU)). All the reductions in this paper will be polynomial time many-one reductions. Definition: A subset 5 of is sparse if there is a polynomial so the number of strings in 5 of size at most n is at most p. We restate the following theorem (cf. [r] or [iP]) and s'etch: sketch the proof. Theorem 1.1. If SATc is reducible to a sparse set, then p = NP. Proof. Let f:SAT --> 5 be a reduction to & sparse set, 5, and let F be a formula whose satisfiability is to be decided. We search a binary tree formed from self-reductions of F as follows: F is at the root; a for??:formula C with variables X1, ... , X occurring in the tree will n have sons G0 a n? G1 where `: is replaced by false and true, respectively, and trivial si?:simplifications are performed ( e.g. true or = true). If the for i:?formula F has n variables, then the tree will have 2n?1 nodes. ? i e perform a depth-first search of the tree utilizing the sparse set to prune the search. At each node Ft encounters we compute c a label f(F'). We infer certain labels correspond to SAT by the following: When a node with formula false is found, its label is assigned 1. t'false." ii. t Then two sons of a node have ?:labels assigned V?: false, ?1 then the label of the node is also assigned t'false." (This is tl-ie:time conjunctive self-reducibility of non-?:satisfiable for?:formulas.) We prune the search by stopping if a leaf has for n?:l a true in which case F is satisfiable by the as:s i2 n?:assistant on the p at?: part to the leaf; and by not searching below a node whose label has already been assigned ?false." ?1e follow? j in g:following le r2a establishes poly-not:polynomial running time of the algorithn. Lemna 1.2. Let F be a for?:formula with n variables. Let p(.) be bound Let the density of 5 and let q(.) be a poly-no?:polynomial bounding the increases in size under the reduction f. Then the algorithm= above visits at u most interior nodes. o + n + n * p (q(if?)) Proof. (Er, hT). Observe if a label is expanded ?or e U?:a n Once, then t'j e expansions are all on the sa?:safe path from? the root since path len?:lengths are at L?:least n+l (with leaf), at ?:most n * p(q(iF1)) interior nodes with label ?false? visited. A satisfying assign-ent:assignment visits at ti os t another n nodes. QED ?ote:note the algoritbim:algorithm does not require a sparse set of labels for satisfiable fon:iulas:formulas. The sparse set of labels reduces the number of unsatisfiable foi ulas:formulas to be searcheci:searched. ?. Solution of tiie:time Con??c?ur?.:concur Initially, we establish the result for a sparse LP-cornplete:complete set. The proof will be modified for the hypothesis that 1?P is sparse reducible. The outline of the proof below is as follo?.s:follows: We first give an flP recognizer for a set si?'ilar:similar to the co? pler:?ent:compiler component of the sparse set 5. 1.?ny-one:many-one reductions of this set to the sparse set are used to prove the existence of a sparse set of labels for SATC; however, tile conputation: time computation of this set of labels requires kno? iing:knowing tie:time census of 5. Finally, the depth--H first search is tiodified:modified to detei? nine:determine satisfiability of a fon?ula:formula. (without actually !:now in g:knowing the census value will generate the sparse set of'?abels:labels for sATC). * For the following discussion let 5 c (0,1) be a sparse coriplete:complete set for I?P under iiiany-one:many-one reductions. Let l,I? be a non-detenninistic:non-deterministic polynot:'ial:polynomial-tiiae:time recognizer of 5 and let c(n) IS fl (A+?)ni ? p(n) where c(.) is the true census function of 5, and p(.) is a polyno? ial:polynomial bound the size of the census. We begin by coljstructing:constructing a non-deteit? inistic:deterministic polynotiial:polynomial tiL?:time Turi%:Turing ?achine:machine to recognize a flp5e?do?co?ple?entfl:flip 5e do compliment f1 of 5. The inputs include a padding, #n, and a potential census, k. Define the non-dete??inistic:non-deterministic recognizer `A by the following procedure: ?(??,8,k) Check I 5 I <- n; o the n is e:otherwise reject. Check k < p(n); o the n? is e:otherwise reject. Guess ?i' 5k ?? i. for all i, I 5 I <--H n. ii. for all i and j, iii. for all i, checit:check it 5. is accepted by II? iv. check for all i s?s. Leriraa:Lemma 3.1. Let I si < n and k --H< p(n). Then on input (#n,s1k) the inachine:in a machine n' will: a. accept if k < b. reject if k > c(n); and c. if k = c(n), then II accepts if and only if I4? rejects 5. Proof of Lei??.:Lemma. We show part c. If 14 accepts, it will have enun?erated:enumerated the elerients:elements of 5 up to size n, verified they belong to 5, and shown 5 is distinct. Since k is the true census, 11 accepts if and only if & is not in 5. QED Intuitively1: Intuitively 1 for k = c(n), :?` is a recognizer of 5 cor::?lement.:correct or corresponding elements 1?oreover1:1 moreover ii accepts its 1 an?uage: 1n usage in non- detenainistic polynot?ial:polynmial-ti L ie:time (the input #n is ? padding to ensure this). We require labellin'?:labelling functions for pruning tree searches. The following discussion sho?,s:shows how to construct such functions from the sparse set 5 and many-one reductions of L(I): Since N is an UP ??chine:UP Machine and 5 is NP-co?plete:NP-complete, there is a P-time r:iany-one:many-one reduction: g:L(II) --H> 5 so for some monotonic polynorial:polynomial q(.), inputs two !! of size n are reduced to strings of size at ?ost:most q(n) (cf. [c] and [:3). Si? ilarly:Yes, similarly, for the i'?-coniplete:i-complete problem SAT, there is a P-ti?e:P-time r?any-one:many-one reduction f:SAT -? 5 (f:SAT minus question five) and a monotonic polynomial r(.) bounding ti ie:time increase in size. Let F of size m be a f on n ul a:formula to be decided. T?ien:Time ?ny:Many for?nula:formulas F' occurring in the tree of all self reductions will have size < Regarding I t:it as a possible value for c(n), we define: Ln,k (F1) = which will be the labelling function. Lemma 3.2. Let F be a f o i?ul a:formula of size r a. Let n rC?):near C?; i.e. n is a polynotial:polynomial upper bound on the size of f(F') where IF 1 I ? iii.(If 1 I question 3i) Finally, Let k = c(n), the true census. Then the function: Ln?k(Ft):Link(Ft) for forulas:formulas F' of size at most n satisfies: i. F' is not satisfiable if and only if L(F') is in 5; ii. The unsatisfiable for?uljs:formulas of size at i most:i-most in/ are mapped by L to at most: p(q(2n+c'log(n))) ? p(q(3n)) distinct strings of 5 where c' is a constant dependin0':depending 0 o?'ily:o question il y on p(.) Proof: Part i. is imiuediate:immediate froi?:from question LeLTh?:Lemma 2.1. For p?rt ?i..:For part question i observe 2 n + CI i o g(n) ? 3 n: 2n + CI og(n) question 3n is a bound on the size of (#nf(P'), k). Applying p 0 q gives the census of strings in 5 the triple could nap:map onto. QED We now know a suitable labelling function e'?iSt5:exists for k but we do not know c(n)! Tiie:Time algorithir:algorithm in the following theorem shows how we can try (Ln,k:Link) for all (k ? pCn:k question pCn). Theoren:Theorem 3.3. If UP has a sparse complete set, then P UP. Proof: We give a deterrainistic:deterministic procedure to recognize SAT. Let F be a for ra ul a:formula of size m. Apply the follouin0-:following zero minus algorithrn:algorithm: begin For k 0 to p(r(n)) do ?ecute:question execute the depth first search algoriti??:allgorithm question with labelling:labeling function: (Ln,k):(Link) at each node F' encountered in the pruned search tree. If a satisfying assignment is found, then halt; F is satisfiable. If a tree search visits rr?re: are two questions regarding than:then n + n * pCq(3 rCr))) internal nodes, then halt the search for this k. end; F is not satisfiable; end The algorith?:algorithm clearly runs in polyno?ial:polynomial-tir? e:time since the loop is e':ecuted:executed at most p(r(n)) tines:times and each iteration of the loop visits at most a polynonial (in i?):(in i question) (nur?er):number of nodes. The correctness of the algorithn:algorithm is established in the following: lei?ia:let i question i a Lemr?:Lemma 3.4. If F is satisfiable, then for k c(r(n)) the search will find a satisfying assigni':?nt:assignment. Proof: By Lenina:Lemma 2.2. This k gives a lab?lling:labelling function maps the unsatisfiable fofl??1as:f of one two question 1 as f of size at no s t:most ta: (at or to) a polynowially:polynomially bounded set. Fortune shows that thL:the depth first search (?:ill):(question:I will) find a satisfying assignment visiting at most internal nodes. n + n * p(q(3n)) QED It is interesting to note here we have not cor?uted:corrupted or computed the census: a satisfying assignrAent:assignment could be found ?-ith:question minus it h any nu?ber:number of k's; similarly* if no satisfying assignrent:assignment (CA'?5t5*):(See A has question five t five times) many of the trees could be searched but the tree with k = c(r(j?)) is not distinguished. The method of conducting many tree searches is parallelled in the un i for a:uniform algorith'n:algorithm technique by Karp and Lipton [KL]. They show if NP could be accepted in (P ?jith):(P question j it h) log(space) advice, then P = iP. The census function `night:might be co?pared:compared to a (log( )-): (Log (inclusive space) minus) advisor to the polynoraial (in for- ? at i on):(in form at i on) in the set 5. It is not necessary to (assur:?):(assume you are without question), (a n flP):(an n-flip) recognizer for the sparse set: just at 5 is NP-hard. Le?'na:Lemma 3.5. If 5 is sparse and (1?P-hard*):(one question p minus hard times) then there is a set s# sparse, (I;P-co?plete*):(I semi p minus see or question p let e) has a P-ti:e:P-time reduction: SAT --> S# length increasing. Proof. Let f: SAT --> 5 be a P-time reduction and let # be a new -:minus symbol. Define f#: SAT --> S# by =:equals v-here p = max( 0, If(F)I - IFI ). Clearly S? is sparse. The mapping f# reduces SAT to S#. `&ia:2?ership:membership of 5 in S# is verified by guessing a satisfiable fon-?ula:formula raps:maps to 5 and verifyin?:verifying question satisfiability. QED Corollary 3.6. If NP is sparse reducible, then P = NP Lastly we renark:remark the census, c(n), of a sparse NP-co?plete:NP minus complete set is coj-:?utable:computable in polynot? ial:polynomial ti?'.e:time. Indeed. assw?ing:assuming P = I?, the census of any sparse set in :?p:question p can be corputed:computed by stand? rd:standard techniques. If 5 is sparse and (t;P-cot?plete*):(t; P-Complete) then P = NI' by Theorei?:Theorem 3.3 so the census of 5 is cot:putablc:computable (iI'):(two I have) polynoi.ial:polynomial tiI-Ae:time. WL':We have proved: Corollary 3.7. If ip has a sparse complete set S1 then the census of ?:question is computable in P. ?:question period. Discussion Although the isonorphism:isomorphism results [t"tl]:[t quote t l] are the direct ancestry of the work discussed here, the concept of sparseness has another (Lotiva tion):motivation. Can a "sparse a?ount:amount of (informatior?):(question information) be used to solve IT problems in polyno?ial:(polynomial) tir??:(time?)(time to question) The approach here (assur:?es):(assures and assumes) the information is given as a (in any-one):(in any or many-one) reduction to a sparse set. For Turing reductions, the infon?ation:information is given as a sparse oracle. A. ii'eyer: (two i have eye are) a has sho?rn:shown a sparse oracle for rP:NP is equivalent to the existence of polynomial size circuits to solve i;P:NP (cf. [13113). The recent work by `?arp:(have question) Karp, Lipton and Si-?ser: (Sipser) [KL] has shown if ip has polynomial size circuits, then the polynomial time hierarchy collapses p to Their result has a weaker hypothesis than Theorem 3.3. It is an important open problem to determine if polynomial size circuits for i?:i question implies P = NP. Ackno?lec'?ement.:Acknowledgement Period I ar?:am greatly indebted to Juris U. artmanis: j you are is you period art man is and Vivian Sewelson: Viv an sew el son for numerous discussions lent insight into the methods developed in this paper. The u n i for?:(you and I for, or uniform) al0orithm :(algorithm) techniques of [KL] suggested the methed:(me the method) in Theorei_: (the or e i underscore or) Theorem 3.3. I am grateful to Richard '1:arp:one' Karp and Richard Lipton ?,ho:(questionably) circulate an early version (AHU] Aho, A., ilopcroft, J., and UlThian, J., The Design and Analysis of Computer Al?oriti?s:Algorithms, Addison-Wesley (1974). (?1):(one question) Berman, L. and hartmanis, J., 11On(one hundred and ten n) Isomorphists and Density of NP and Otber Cot?lete:Other Complete Sets," SIAl! J. Cowut., 6 (1977) pp. 305-322. Also in Proceedings Eigth Annual ACH Syiap. on Theory of Cor? putin(?,:Computation (flay 1976). EB) Berman, P. 11 Relationship Between Density ard Deterministic Complex- ity of I:P-Complete Langua0es:Languages," Fifth International Colloquiu??:Colloquiuam on Auto- mata, Languages, and Pro0?ramming:Programming, Udine (July l97?), Springer Lecture I?tes in Comp. Sci. 62. (c) Cook, 8. A., 11 The Compleity:Complexity of Theoret?:(The (or) et question) Proving Procedures," Proc. 3rd Annual ACL?l Syr:?osiul:i:Symposium on Theory of Co? puting:Computing, (1971) pp. 151-153. ?F) Fortune, 5., 11 A Note on Sparse Complete Sets,11 Slk?? J. Comput., 8 (1979), pp. 431-433. E1111) llartmanis, J. and `iThhaney, 5. R., 1,On Census Comple?:ity:Complexity and Sparse- ness of NP-Complete Sets," Cornell University Technical Report TR 80-416 (April 1980). (K) i?'arp:Karp (in part), R., "Reducibility [Ai::Artificial Intelligence (on) g] Combinatorial Problems, 11 in Complexity of Cor?uter:Computer Computations (R. I;. ?iller and J. W. Thatcher, eds.), Ple- nuni, New York (1972). KL) Karp, R. and Lipton, R., `1 Some Connections Detween:Between Nonuniform and Uniform Cotiple'?ity:Co-triple Complexity Classes," Proc. 12th AC?'& Syp. on Theory of Comput- ing, (Hay 1980). (?iP) Patterson, M. and Heyer, A., ??`ith What Frequency are Apparently Intractable Problems Difficult?," H.I.T. Tech Report, Feb. 1979. From v.harishankar at gmail.com Fri Apr 2 06:17:55 2010 From: v.harishankar at gmail.com (Harishankar) Date: Fri, 2 Apr 2010 10:17:55 +0000 (UTC) Subject: subprocess.Popen objects: how to ensure that stdin is closed Message-ID: I am writing a small app which requires input using stdin to the subprocess. I use the following technique: proc = subprocess.Popen (cmdargs, stdin=subprocess.PIPE) proc.stdin.write ("Something") proc.stdin.flush () ... proc.stdin.write ("something else") proc.stdin.flush () ... and so on. I cannot use communicate() because it waits till program termination and so obviously can be used once only. The problem is that I want to close the process and it's not responding either to proc.stdin.close() or even proc.terminate() which is in Python 2.6 (not in 2.5.x) So I am left with a mangled terminal. Is subprocess behaving funny or am I doing something wrong? I am not even sure if the proc.stdin.close () is respected because even without it, I am getting the same mangled state. I just want to control the commands using stdin.write and then close the process when done. -- Harishankar (http://harishankar.org http://literaryforums.org) From anand.shashwat at gmail.com Fri Apr 2 06:21:44 2010 From: anand.shashwat at gmail.com (Shashwat Anand) Date: Fri, 2 Apr 2010 15:51:44 +0530 Subject: Splitting a string In-Reply-To: References: Message-ID: >>> s = 'si_pos_99_rep_1_0.ita' >>> res = tuple(re.split(r'(\d+)', s)) >>> res ('si_pos_', '99', '_rep_', '1', '_', '0', '.ita') >>> On Fri, Apr 2, 2010 at 3:42 PM, Thomas Heller wrote: > Maybe I'm just lazy, but what is the fastest way to convert a string > into a tuple containing character sequences and integer numbers, like this: > > > 'si_pos_99_rep_1_0.ita' -> ('si_pos_', 99, '_rep_', 1, '_', 0, '.ita') > > Thanks for ideas, > Thomas > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From v.harishankar at gmail.com Fri Apr 2 06:26:05 2010 From: v.harishankar at gmail.com (Harishankar) Date: Fri, 2 Apr 2010 10:26:05 +0000 (UTC) Subject: subprocess.Popen objects: how to ensure that stdin is closed References: Message-ID: On Fri, 02 Apr 2010 10:17:55 +0000, Harishankar wrote: > I am writing a small app which requires input using stdin to the > subprocess. > > I use the following technique: > > proc = subprocess.Popen (cmdargs, stdin=subprocess.PIPE) > > proc.stdin.write ("Something") > proc.stdin.flush () > ... > proc.stdin.write ("something else") > proc.stdin.flush () > ... > > and so on. I cannot use communicate() because it waits till program > termination and so obviously can be used once only. > > The problem is that I want to close the process and it's not responding > either to proc.stdin.close() or even proc.terminate() which is in Python > 2.6 (not in 2.5.x) > > So I am left with a mangled terminal. > > Is subprocess behaving funny or am I doing something wrong? I am not > even sure if the proc.stdin.close () is respected because even without > it, I am getting the same mangled state. I just want to control the > commands using stdin.write and then close the process when done. Hmm... just two minutes after I posted this. I just added this proc.wait () after closing stdin and it works fine now. Still not sure whether I need the proc.stdin.close () though. -- Harishankar (http://harishankar.org http://literaryforums.org) From contact at xavierho.com Fri Apr 2 06:26:26 2010 From: contact at xavierho.com (Xavier Ho) Date: Fri, 2 Apr 2010 20:26:26 +1000 Subject: Splitting a string In-Reply-To: References: Message-ID: Best I can come up with: >>> def split_number(string): ... output = [string[0]] ... for character in string[1:]: ... if character.isdigit() != output[-1].isdigit(): ... output.append('') ... output[-1] += character ... return tuple(output) ... >>> split_number('si_pos_99_rep_1_0.ita') ('si_pos_', '99', '_rep_', '1', '_', '0', '.ita') Cheers, Xav On Fri, Apr 2, 2010 at 8:12 PM, Thomas Heller wrote: > Maybe I'm just lazy, but what is the fastest way to convert a string > into a tuple containing character sequences and integer numbers, like this: > > > 'si_pos_99_rep_1_0.ita' -> ('si_pos_', 99, '_rep_', 1, '_', 0, '.ita') > > Thanks for ideas, > Thomas > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From contact at xavierho.com Fri Apr 2 06:31:12 2010 From: contact at xavierho.com (Xavier Ho) Date: Fri, 2 Apr 2010 20:31:12 +1000 Subject: Hey Sci.Math, Musatov here. I know I've posted a lot of weird stuff trying to figure things out, but I really think I am onto something here and need some bright minds to have a look at this, computer people, too. Thank you for your time. In-Reply-To: References: Message-ID: On Fri, Apr 2, 2010 at 8:14 PM, A Serious Moment wrote: > SPARSE COMPLETE SETS FOR NP: > SOLUTION OF A CONJECTURE > BY MARTIN MICHAEL MUSATOV * > > for llP: > > Sparse Comp1ete Sets > Solution of a Conjecture > Hi, If you're serious about this posting, could you please: 1) Provide a link to a PDF/Latex or some other well-formatted text page 2) Comp1ete != Complete Because I find your email impossible to read. Cheers, Xav -------------- next part -------------- An HTML attachment was scrubbed... URL: From contact at xavierho.com Fri Apr 2 06:36:37 2010 From: contact at xavierho.com (Xavier Ho) Date: Fri, 2 Apr 2010 20:36:37 +1000 Subject: Splitting a string In-Reply-To: References: Message-ID: Oops, minor update: >>> def split_number(string): ... output = [string[0]] ... for character in string[1:]: ... if character.isdigit() != output[-1].isdigit(): ... if output[-1].isdigit() is True: ... output[-1] = int(output[-1]) ... output.append('') ... output[-1] += character ... return tuple(output) ... >>> split_number('si_pos_99_rep_1_0.ita') ('si_pos_', 99, '_rep_', 1, '_', 0, '.ita') Cheers, Xav On Fri, Apr 2, 2010 at 8:26 PM, Xavier Ho wrote: > Best I can come up with: > > >>> def split_number(string): > ... output = [string[0]] > ... for character in string[1:]: > ... if character.isdigit() != output[-1].isdigit(): > ... output.append('') > ... output[-1] += character > ... return tuple(output) > ... > >>> split_number('si_pos_99_rep_1_0.ita') > > ('si_pos_', '99', '_rep_', '1', '_', '0', '.ita') > > Cheers, > Xav > > > On Fri, Apr 2, 2010 at 8:12 PM, Thomas Heller wrote: > >> Maybe I'm just lazy, but what is the fastest way to convert a string >> into a tuple containing character sequences and integer numbers, like >> this: >> >> >> 'si_pos_99_rep_1_0.ita' -> ('si_pos_', 99, '_rep_', 1, '_', 0, '.ita') >> >> Thanks for ideas, >> Thomas >> >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From anand.shashwat at gmail.com Fri Apr 2 06:39:38 2010 From: anand.shashwat at gmail.com (Shashwat Anand) Date: Fri, 2 Apr 2010 16:09:38 +0530 Subject: pynotify for python 3.1.. Help Please.. In-Reply-To: References: Message-ID: I guess it is a 3rd party module. Run setup.py with python3.1, however it can happen that the module is not python3 compatible. In that case try using 2to3 if you can. On Fri, Apr 2, 2010 at 3:43 PM, Xavier Ho wrote: > On Fri, Apr 2, 2010 at 8:13 PM, Xavier Ho wrote: > >> Hi Jebamnana, >> > > Jebagnana* > > Sorry. > > -Xav > > -- > http://mail.python.org/mailman/listinfo/python-list > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From alex at moreati.org.uk Fri Apr 2 06:44:01 2010 From: alex at moreati.org.uk (Alex Willmer) Date: Fri, 2 Apr 2010 03:44:01 -0700 (PDT) Subject: Splitting a string References: Message-ID: On Apr 2, 11:12?am, Thomas Heller wrote: > Maybe I'm just lazy, but what is the fastest way to convert a string > into a tuple containing character sequences and integer numbers, like this: > > 'si_pos_99_rep_1_0.ita' ?-> ('si_pos_', 99, '_rep_', 1, '_', 0, '.ita') > This is very probably not the fastest execution wise, it was the fastest development time wise: import re def maybe_int(x): try: return int(x) except ValueError: return x def strings_n_ints(s): return tuple(maybe_int(x) for x in re.findall('(\d+|\D+)', s)) >>> strings_n_ints('si_pos_99_rep_1_0.ita') ('si_pos_', 99, '_rep_', 1, '_', 0, '.ita') Alex From duncan.booth at invalid.invalid Fri Apr 2 07:20:50 2010 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 2 Apr 2010 11:20:50 GMT Subject: (a==b) ? 'Yes' : 'No' References: <4bb22b39$0$1638$742ec2ed@news.sonic.net> <861e25b4-96b1-4a12-82d8-9a93cbc3e8da@8g2000yqz.googlegroups.com> <4bb55778$0$8827$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano wrote: > Yes, I agree, we should be using the previously well known syntax: > > condition -> value_if_true, value_if_false > > which was introduced by BCPL in 1966. > What, not this? VALOF TEST condition THEN RESULTIS value_if_true ELSE RESULTIS value_if_false which was also introduced by BCPL in 1966. :^) From __peter__ at web.de Fri Apr 2 07:24:32 2010 From: __peter__ at web.de (Peter Otten) Date: Fri, 02 Apr 2010 13:24:32 +0200 Subject: Splitting a string References: Message-ID: Thomas Heller wrote: > Maybe I'm just lazy, but what is the fastest way to convert a string > into a tuple containing character sequences and integer numbers, like > this: > > > 'si_pos_99_rep_1_0.ita' -> ('si_pos_', 99, '_rep_', 1, '_', 0, '.ita') >>> parts = re.compile("([+-]?\d+)").split('si_pos_99_rep_1_0.ita') >>> parts[1::2] = map(int, parts[1::2]) >>> parts ['si_pos_', 99, '_rep_', 1, '_', 0, '.ita'] Peter From vlad_fig at yahoo.com Fri Apr 2 07:25:38 2010 From: vlad_fig at yahoo.com (vlad_fig) Date: Fri, 02 Apr 2010 11:25:38 -0000 Subject: def method with variable no of parameters file.writeStuff(n, a1, a2, ...an) Message-ID: Hello all, I would like some help with setting up a method that would allow me to change its number of parameters. For example: #--------------------- class createfile(object): def __init__(self, modelName = None, someLines = None): self.modelName = modelName if someLines is None: self.someLines = [] else: self.someLines = someLines def writeStuff(self, numberParameters = None, Parameter1 = None,... ??? ) self.someLines .append("yes, we can %s" % self.Parameter1) #--------------------- file = createfile('file') file.writeStuff(2,a1,a2) file.writeStuff(3,a1,a2,a3) .... file.writeStuff(n,a1,a2,...an) --- so i want a method i can call based on the number of parameters n , and that allows me to add these extra parameters based on n Thank you, Vicnic From jason at powerpull.net Fri Apr 2 07:36:06 2010 From: jason at powerpull.net (Jason Friedman) Date: Fri, 2 Apr 2010 11:36:06 +0000 Subject: subclass of object Message-ID: Hi, what is the difference between: def MyClass(object): pass and def MyClass(): pass From jebagnanadas at gmail.com Fri Apr 2 07:44:41 2010 From: jebagnanadas at gmail.com (Jebagnana Das) Date: Fri, 2 Apr 2010 17:14:41 +0530 Subject: pynotify for python 3.1.. Help Please.. Message-ID: Thank you for your reply. Unfortunately pynotify is not available as a .py file but as an .so (shared library) file. In both python 2.5 and 2.6 installations it can be found at /var/lib/python-support/python2.x/gtk-2.0/pynotify/__init__.py , _pynotify.so. I think it was written in native c or c++ which is then converted to a shared library to use with python.. Unless the source code in c is available, we can't port it to python 3.. I can't find the authors name or any license agreement there.. By luck if any of the authors of pynotify here please answer me.. When will the .so for python3 will be released? or Is there any alternate way of achieving this?? Regards, Jeba. Xav : You can simply call me as jeba. Hi Jebamnana, > > You'll probably have to copy the pynotify contents to the Python 3.1 > folder. (under Libs\site-packages). You should be able to find the folder in > the Python 2.6 paths. > > Once you do that, you can try to use it. But I don't know if pynotify will > be able to run with Python 3.1. For instance, you might have to look into > the source code and make some changes. > > Better to consult with the author(s) of pynotify and consult them about the > difficulty to port to Py3. > > Cheers, > Xav > > Hello all, >> >> I'm trying to display system notifications in ubuntu.. I've >> tested pynotify in python 2.6 and it's working fine.. I want to know if i >> can do the same with python 3? I tried but there is no module named pynotify >> error is displayed.. Any of your help would be much appreciated.. >> >> >> > Hi Jebamnana, >> > > Jebagnana* > > Sorry. > > -Xav > -------------- next part -------------- An HTML attachment was scrubbed... URL: From alfps at start.no Fri Apr 2 07:45:49 2010 From: alfps at start.no (Alf P. Steinbach) Date: Fri, 02 Apr 2010 13:45:49 +0200 Subject: subclass of object In-Reply-To: References: Message-ID: * Jason Friedman: > Hi, what is the difference between: > > def MyClass(object): > pass > > and > > def MyClass(): > pass If you really meant 'def', then the first is a routine taking one argument, and the second is a routine of no arguments. If you meant 'class' instead of 'def', then it depends on the Python version. In Py2 the first then defines a new-style class, while the second defines an old-style class. E.g. you can see some difference by checking with 'isinstance'. In Py3 there's no difference. Cheers & hth., - Alf From steve at holdenweb.com Fri Apr 2 07:57:35 2010 From: steve at holdenweb.com (Steve Holden) Date: Fri, 02 Apr 2010 07:57:35 -0400 Subject: subclass of object In-Reply-To: References: Message-ID: Jason Friedman wrote: > Hi, what is the difference between: > > def MyClass(object): > pass > > and > > def MyClass(): > pass In Python 3, nothing. In Python 2, the former gets you a subclass of object whereas the latter gets you an instance of , for compatibility with pre-2.2 versions. For most practical purposes there is no difference, so it doesn't matter until it matters, so to speak. Unless you are noticing unexpected behavior in your programs you probably don't need to worry (though you might want to use the first form to ensure better Python 3 compatibility). regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 See PyCon Talks from Atlanta 2010 http://pycon.blip.tv/ Holden Web LLC http://www.holdenweb.com/ UPCOMING EVENTS: http://holdenweb.eventbrite.com/ From editor at pythonrag.org Fri Apr 2 08:01:55 2010 From: editor at pythonrag.org (Bernard Czenkusz) Date: Fri, 02 Apr 2010 07:01:55 -0500 Subject: associative array References: Message-ID: On Thu, 01 Apr 2010 11:57:11 +0000, Harishankar wrote: > On Wed, 31 Mar 2010 09:40:30 -0700, Javier Montoya wrote: > >> Dear all, >> >> I'm a newbie in python and would be acknowledge if somebody could shed >> some light on associative arrays. >> More precisely, I would like to create a multi-dimensional associative >> array. I have for example a list of students which are identified >> uniquely by their student IDs. Additionally, for each student I have >> some information: FirstName, LastName, etc. >> >> The array would have then the following form: [StudentID] => >> [FirstName][LastName][Telephone]...[ ... ] >> >> I would like to be able to access a field directly by using a StudentID >> [StudentID][FirstName] >> [StudentID][LastName] >> >> How could I manipulate such an array (create the array, add elements, >> access data)? >> >> Best wishes > > I know this is not a direct answer, but in your case I would probably > use a database, because it is the easiest and most standardized way to > access such types of data. If you don't want something heavyweight, use > sqlite with in-memory databases/persistent file. > > Look at sqlite3 module in python. You could also look at the September issue of the Python Rag which has a couple of articles on storing a membership class using Shelve, which is similar to what you are interested in: http://www.pythonrag.org/ From steve at holdenweb.com Fri Apr 2 08:19:09 2010 From: steve at holdenweb.com (Steve Holden) Date: Fri, 02 Apr 2010 08:19:09 -0400 Subject: subclass of object In-Reply-To: References: Message-ID: Alf P. Steinbach wrote: > * Jason Friedman: >> Hi, what is the difference between: >> >> def MyClass(object): >> pass >> >> and >> >> def MyClass(): >> pass > > If you really meant 'def', then the first is a routine taking one > argument, and the second is a routine of no arguments. > > If you meant 'class' instead of 'def', then it depends on the Python > version. > > In Py2 the first then defines a new-style class, while the second > defines an old-style class. E.g. you can see some difference by checking > with 'isinstance'. In Py3 there's no difference. > Interesting. I actually read "class" for "def" and replied accordingly. As can plainly be seen ... regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 See PyCon Talks from Atlanta 2010 http://pycon.blip.tv/ Holden Web LLC http://www.holdenweb.com/ UPCOMING EVENTS: http://holdenweb.eventbrite.com/ From marty.musatov at gmail.com Fri Apr 2 08:27:10 2010 From: marty.musatov at gmail.com (A Serious Moment) Date: Fri, 2 Apr 2010 05:27:10 -0700 (PDT) Subject: For Peer Review Message-ID: <5ec848a6-5caf-486a-9f9d-b6c962fc6fb0@15g2000yqi.googlegroups.com> AN ESSAY ABOUT RESEARCH (fl) ON SPARSE NP COMPLETE SETS By M. Musatov The purpose of this paper is to review the origins and motivation for the conjecture sparse NP complete sets do not exist (unless ? NP) and to describe the development of the ideas and techniques leading to the recent solution of this conjecture. The research in theoretical computer science and computational complexity theory has been strongly influenced by the study of such feasibly computable families of languages as P, NP and PTAPE. This research has revealed deep and unsuspected connections between different classes of problems and it has provided completely new means for classifying the computational complexity of problems. Furthermore, the work has raised a set of interesting new research problems and crested an unprecedented consensus about what problems have to be solved before real understanding of the complexity of computations can be achieved. In the research on feasible computations the central role has been played by the families of deterministic and nondeterministic polynonial time computable languages. P and NP(1) respectively [MIU. c, cj, K]. In particular(.) the NP complete(?te) languages have been studied intensively and virtually hundreds of natural NP complete (rnplete) problems have been found in many different areas of applications (AHu. cJ). Though we do not yet know whether P (?) NP(.) we accept today a proof a problem is NP complete as convincing evidencethe problem may be polynonial time computable (and feasibly computable); a proof a problem is complete for PTAPE is viewed as even stronger evidence the problem is feasibly computable (even though there is no proof that P (?) NP (?) PTAPE). As part ot the general study of similarities among NP complete problems it is conjectured by Berman and Hartmanis(1) for reasons given in the next section(1) all NP complete problems are (?re) isomorphic (norphic) under polynomial time mappings and therefore there may exist (sparse) NP complete sets with considerably fewer elements than the known classic complete problems (e.g. SAT. CLIQUE(1) etc. EBH)). When the conjecture is first formulated in 1975(.) the understanding of NP complete(-plete) problems was more limited and several energetic frontal assaults on this problem(-lem) failed (?ailed). As a matter of fact, the problem looked quite hopeless after a considerable (-erable) initial effort to solve it. Fortunately(1) during the next five years a number of different people in Europe and America contributed a set of ideas and techniques recently leading to an elegant solution of the problem by (5)(.) Mahaney of Cornell University (M). The purpose of this paper is to describe the origins of the sparseness conjecture (-ture) about NP complete sets(1) to relate the information flow about this problem and to describe the development of the crucial ideas finally leading to the proof sparse NP complete sets exist(1) then P = NP (M). We believe this is an interesting and easily understandable development in the study of NP complete problems and there are some lessons to be learned about computer science research from the way this tantalizing problem was solved. Furthermore(1) it is hoped these results provide a new impetus for work on the main conjecture all NP complete sets are p-isomorphic. (?.) Preliminaries and the Sparseness (narseness) Let P and NP denote(.) respectively(.) the families of languages accepted by deterministic (-?inistic) and nondeterministic Turing machines in polynomial time. A language C is said to be (?) complete (niete) if C is in NP and if for any other language 3 in NP there exists a polynomial time computable function f such x ( 3f(x) c C. The importance of the family of languages P stems from the fact they provide (-vide) a reasonable model for the feasibly computable (nutable) problems. The family NP contains (-tains) many important practical problems and a large number of problems from different (- ferent) areas of applications in computer science and mathematics have been shown to be complete for NP (AHU. C. BJ1 K). Since today it is widely conjectured P (?) NP(.) the NP complete problems are believed (by a minority) may be solvable in polynomial time. Currently one of the most fascinating problems (toblems) in theoretical computer science is to understand better the structure of feasibly computable problems and(.) in particular(.) to resolve the p NP question. For an extensive study of P and NP see EARu. GJ]. A close study of the classic NP complete sets(.) such as SAT(.) the satisfiable Boolean formulas in conjunctive normal form(.) RAM(.) graphs with Hamiltonian circuits(.0) or CLIQUE(.) graphs with cliques of specified size(.) revealed they are very similar (-lar) in a strong technical sense (BH). Not only may they be reduced to each other(.) they are actually isomorpbic under polynomial time mappings (nappings) as defined below: * * Two languages A and 3. A ? ? and 3 r . are ?-iso?or?hic:isomrophic iff:if an only if there exists a bijection f:?*???:f:question times three question (i.e. a one-to-one and onto mapping) such 1. f and f?1:f question one are polynomial time computable. --H1 2. f is a reduction of A to 3 and f is a reduction of 3 to A. Further study reveals all the "known" NP complete sets are p- isomorphic and one may formulate (after a number of technical lemmas) a very simple (nple) condition (-dition) for NP complete sets to be p- isonorphic to SAT in terms of two padding functions (-tions) (BH). Theorem L: An NP complete set B is p-isomorphic to SAT iff:if and only if there exists two polynomial (-?ial) time computable functions D and 5 such 1. (Vx?y) (D(x.y) c B ?xcB) 2. (Vx*y) (SoD(x,y) : All the known NP complete sets have these padding functions and in most cases they are easy to find. A good example is SAT(.) for which y can easily be encoded in any given formula in terms of new variables which do (may) change the satisfiability of the formula [Bli]. >From these studies grew the conviction all NP complete sets are p--H isomorphic and this conjecture is explicitly stated in [EBH]. Clearly(.) if all NP complete sets are p-isomorphic then they all must be infinite (-ite) and therefore P X NP. Thus it is realized this conjecture may be very hard to prove(.) but the possibility is left open it may be easier to disprove it. One way of disproving the p- isomorphism conjecture suggests the fact p-isomorpflic sets have quite similar densities. To make a precise we define sparseness below: * A set B. B c ? is said to be sparse if there exists a polynomial p(n) such I Bn(c+?) I ` Thus p(n) bounds the number of elements in B up to size n. It is easily seen that SAT and other known NP complete sets are (may be) sparse (any set possessing the padding functions D and 5 is may be sparse) and a sparse set may be p-isomorphic to SAT. These considerations lead to the conjecture (Bil) there may exist sparse NP complete sets (unless p : NP). In particular(.) it is (*) conjectured one set over a single letter alphabet say B?a may be NP complete. It is interesting to note the p-isomorphism conjecture quickly leads to the sparse set conjecture and then to the innocuous looking conjecture a language on a single letter alphabet may be NP complete. We return to this last conjecture in the next section(.) it is the first to be solved. A more indirect motivation for the p-isomorphism conjecture comes from the sugggested (-gested) analogy between recursive and recursively enumerable languages and P and NP as their feasibly computable counterparts. This analogy becomes particularly intrigueing (-gueing) and suggestive when it is extended to the Kleene Hierarchy and the polynomial time hierarchy (5). The NP complete sets correspond in this analogy to the r.e. complete sets(1) known to be the same as the creative sets and they are all recursively isomorphic. This suggests by analogy the NP complete (?omplete) sets should be (p--H) isomorphic(.) as conjectured in (Bli). Lastly(.) a sparse NP complete set implies the necessary information to solve NP problems may be condensed in a sparse set (?et). In other words(1) the sparse set may be computed and then used as a polynomially long oracle tape to solve other NP complete problems. At the time of stating (Ating) the sparseness conjecture this looked very unlikely, and now we know it is not impossible when p NP. For related results discussing the consequences of the existence of polynomial size circuits for the recognition of SAT1 see (KL). 1. Ranges (?es) afl4 SLA Languages (?ua?es) The p-isomorphism and sparseness conjecture and the more specialized conjecture one language on a single letter alphabet may be NP complete may receive a fairly wide exposure at conferences and journal publications in the United States and Europe (BH. uBl, HB2). Fortunately(1) in spite of different attempts(1) now progress may be made on this problem for several years and it starts to look like an interesting (-ing) problem about NP complete sets which may be likely to be solved in the near future. The situation changes suddenly when Piotr Bernan (?an) from Poland submits a paper "Relationships Between Density and Deterministic Complexity of NP-Complete Languages(?) to iCALP (?7?). In this paper(.) motivated by the sparseness conjecture(.) P(.) Berman considers the consequences of P-time (c) reductions with sparse range(.)(*)particularly NP complete subsets of a (.) One of the authors was on the program comittee (n-mittee) for ICAL(?) `78 and the paper(.) which in its first version is not easy to understand, is studied at Cornell with great interest. After some (ne) effort, with the help of 5(.) Fortune(.) we convince ourselves indeed P. Berman's result is correct. In retrospect it is surprising how elegant and simple P. Berman's proof is and why so many other people who had thought about this problem missed it. The paper is, as it amply deserves, accepted for ICALP `78 and receives considerable (-siderable) attention. Unfortunately, P. Berman did not attend ICALP `78 himself and the paper is read at the conference by Ron Book, who had also worked on single letter alphabet languages (BWSD). We state P. Berman's Theorem below and outline a proof: Theorem ?: a) If there is a P-time reduction with sparse range for an NP complete set, then p NP. * b) If there is an NP complete subset of a , then p NP. Note carefully P. Berman's hypothesis of part a) is that is a reduction (-tion) g so l(g(x) : ;?I ? n)l is polynonially bounded. Though his proof uses CLIQUE as an NP complete problem(1) we consider the SAT problem in our outline of the proof. Part b), of course(1) is immediate from part a). Proof: Let g be a p-time reduction of SAT to a sparse range. We outline am algorithm (-rithm) to determine if a booleam formula F(x1 l???lXn)s is satisfiable (and if so, find an assignment). The algorithm searches part of a binary tree of self-reductions (- reductions) of F. The root is F(Xi?????xn) Each node will correspond to F with certain (-tain variables instantiated by 0 or I as follows: if F(b1 1????bi?? sXil???lXn) is at a node, then its offspring are: F(b?1???lbi?I1OlXi+l? ??1Xn) F(bil????bi?1 lllXi+I l???sX n and We construct the tree depth first, computing a label g(F) at each formula F encountered. The algorithm determines certain formulas. F(.) correspond to unsatisfiable (-tisfiable) formulas and their labels(.) g(F)(.) are marked as follows: a leaf with formula (-mula) 0 (i.e. FALSE) is marked unsatisfiable; if both offspring of a node are marked unsatisfiable then the label at the node is marked unsatisfiable also. When a label is marked unsatisfjable other nodes occurring with the same label are similarly (-larly) marked. A careful analysis shows whenever a bottom-most node is selected(.) then either a satisfying assignment is found or a new value g(F) is marked unsatisfiable in examining the next n nodes of the tree. Thus(.) the running time is polynomial in the size of F(x1 .....xn). QED. A close inspection of this proof shows no explicit use is made of the fact the set A is in NP. Thus we have actually proved: 3: If SAT may be reduced to a sparse set. then P = NP. Even more fully formalized(.) P. Berman's proof is quite simple(.) but it provides the first important step in the solution of the sparseness conjecture. We believe in the solution of this problem interaction between different groups plays an important role and the solution of even a highly specialized conjecture(.) like the sparse range case(.) provides the necessary impetus for further work. ?-? Complete (pmnlete ?.) In the attempt to understand P. Berman's proof of the single letter case(.) Steve Fortune(.) who at that time (nie) is a graduate student at Cornell(.) notices in ??????5 proof the negative answers yield valuable information(.) when a formula F is found to be unsatisfiable(.) its label g(F) is marked; one never has to explore beneath any other node of the tree with the same (ne) label value. Furthermore(.) such negative answers are found only polynomially often before the possible values from g( SATc) are exhausted. This insight leads 5(.) Fortune to a proof the complete sets in CO-NP may now be reduced to sparse sets, when P ? NP EF). Theorem A: If a CO-Np complete set may is reduced to a sparse set 5, then P : NP. Proof: Apply the same tree search method as before, observe only negative answers are propogated up the tree by conjunctive self- reducability (-reducibility) (i.e., a node is satisfiable if and only if one or both sons are satisfiable). Since only the negative (-tive) answers are used to prune the tree search, the polynomial running time is preserved (o) under a weaker hypothesis. For a casual observer of theoretical computer science research the above result may look artificial how it answers the sparseness question, but instead inolves a strange new problem about complete sparse sets for CONP(,). On the other hand, this was a critical step, as we see (n)1 in the solution of the general sparseness conjecture for NP complete sets. The Census Early in 1980, while working on his Ph.D. dissertation under Juris Hartmanis at Cornell, Steve Mahaney observes the exact number of elements in a sparse NP complete set may be computed in polynomial time, then some very interesting consequences (-quences) follow, as stated below (?!). For a set 5 let the census function C5 be defined by C5(n) 1 5 n (?+?)? (??) Mahaney's observation leads to the following result. Theorem (?): If there exists a sparse NP complete set 5 with a polynomial time computable (-putable) census function, C51 then NP CO- Np. Proof: We show under the hypothesis we may recognize the complement of 5 c in nondeterministic polynomial time. Since 5 is complete for CO-Np this guarantees NP CO-NP. Given a string WI compute the census function C5(1w1):k. Using a nondeterministic (-ministic) polynomial time machine guess k different sequences w1 1w21.. 1WkI such Iw.I?InI, for i:l.2,....k and verify they all are in 5 using the NP recognizer of 5(.) if the guessing and verification succeeds then v is in SC iff:if and only if w?w?Ii: 1.2.....k. Thus. S? is in NP and therefore NP = CO-NP. Combining (sbining) the above result with Fortune's theorem we get the following. QED. Corollary (ilarv ?): if there exists a sparse NP complete set(.) 5(.) with a polynomial time computable census function then P = NP. Proof: From the previous theorem, under the hypothesis of the corollary, we get NP = CC-NP. But then every set complete for NP is complete for CO-NP and then(1) because 5 is a sparse complete set for Co-NP, by Fortune's result we get P = NP. QED. 4 a in(.) the assumption we have a sparse NP complete set with an easily computable (rn-putable) census function may appear like imposing unnatural and restrictive conditions (-tions) just to be able to derive a result. Surprisingly, the careful exploitation of the census functions lead a step closer to the solution of the sparseness conjecture (-ture)(.) the s During the spring of 1980 Karp and Lipton made available to us a draft of their forthcoming SIGACT (CACT) paper "Some Connections Between Nonuniform and Uniform Complexity Classes" (KL). This paper investigates the consequences of having "advice functions" (or oracles) which give values depending only on the length cf the input to be decided. Karp and Lipton develop uniform algorithms to utilize the existence(.) but not the easy computability(.) of such advice. Two results in this paper are relevant to the sparseness conjecture. The first considers the consequence of having a Turing reduction of SAT to a sparse set or, equivalently (Lently*) the existence of polynomial size circuits to solve NP (see Discussion below). The second result considers advice functions yield O(log(n)) bits of advice for inputs of size n. Theorern 1: Suppose h(.) is an advice function for NP satisfying 1. for some c0 h(n) I ? c log(n), and 2. there is a deterministic polynomial time algorithm using c log(n) bits of advice correctly deciding SAT with advice h(.). Then P = NP. The proof of this theorem shows all potential values of the c log(n) bits may be examined and the correct answer determined uniformly in polynomial time. The deciphering of the Karp and Lipton paper(1) though it did not deal directly with the sparseness conjecture(1) suggests to Mahaney a new approach to the sparseness (-ness?) conjecture which combines the previously developed methods and leads to its solution (-tion). The intuitive link between Theorem (n) 7 and the sparseness conjecture is found in the census results (Theorem 5 and Corollary 6). The unnatural hypothesis of the census results is the census function(.) C5(n)(.) is easily computable. Instead of (1) observing C5(n) is bounded by a polynomial(.) we see the census may be written (-ten) in O(log(n)) bits. The census results suggest a method to construct an algorithm (-ritbin) uniformly tries potential values of the census. The essence of Mahaney's idea is to apply a census-like method (without knowing the exact census) to a sparse NP complete set to construct a p-time (-time) reduction of a CONP set to the sparse set, and then to use a Berman-Fortune depth first search method to solve SAT. The lack of knowledge about the census function is overcome by trying all of the polynomially many (nany) values for the census function and proving the incorrect values may either be detected or they may not give a wrong answer. In the proof below the ignorance about the census function is overcome by constructing (-structing) a pseudo-complement of the sparse NP complete set 5. The pseudo-complement incorporates guesses about what the corresponding census is and it is used to construct (-atruct) the desired sparse set of labels for the depth first search. The outline of the proof below is as follows: We first give an NP recognizer for the ?pseudo-complenent" of the sparse set 5. A reduction of this set to the c sparse set 5 is used to provide the sparse set of labels for SAT; however, the certain (-tain) computation of the set of labels requires knowing the census of 5(.) Finally(.) the depth first search is modified to determine satisfiability of a formula (without "c" exact knowledge of how to generate the sparse set of labels for SAT ). For the following discussion let 5 c (o.l)* be a sparse complete set for NP. Let M5 be a nondeterminiztic polynomial time recognizer of 5 and let C5(n) : 5 fl (+?) I ? p(n) where c5c.) is the true census function of 5, and p(.) is a polynomial bound the size of the census. We begin by constructing a Turing machine to recognize the pseudo- complement (-complement) of 5 in nondeterministic polynomial time(.) inputs include a padding #? and an integer k is a possible value of C5(n). Define the non-deterninistic recognizer M by the following procedure: M(tn,s.k): Check Is ? n; otherwise reject. Check k s p(n); otherwise reject. Guess ?i'?? `5k ?? 1. for all i, 1s.I ? ii. for all i and j, i?j ? s??s? iii. for all i, check 5(.) is accepted by M5, the recognizer of 5. iv. check for all i, a ? a.. L=?a ?: Let Is ? n and k ? p(n)(.) Then on input (in155k) the machine M will: 1. accept if k < c(n); 2. reject if k ) c(n); and 3. if k : C5(n), then N accepts if and only if M5 rejects a. (?) Lemma: We show part 3. If M accepts. then it viii have enumerated the(.) elements of 5 up to size n, verified they belong to 5, and shown that 5 is dintinct (-tinct) from these elenents. Since k is the true census(1) M accepts i? and only if (*) is not in 5. QED. Intuitively(.) for k C (n)(.) X is a recognizer of 5 complement. Moreover, M5 accepts its language in non-deterministic polynomial time (the input ?n is a padding to ensure this). We (viii) require labeling:labeling functions for pruning tree searches. The following discussion shows how to construct such functions from the sparse set 5 and many-fine (line) reductions of L(M). Since M is an NP machine and 5 is NP complete(.) there is a p-time many-one (-one) reduction g:LCN) ? 5 so for some monotonic (nonotonic) polynomial q(.), inputs to M of size n are reduced tovstrings of size at most q(n) (cf. Ec) and EK)). Similarly. for the NP-complete problem SAT, there is a P-time many-one reduction f:SAT ? 5 and a monotonic polynonial r(.) bounding the increase in size. Let F of size m be a formula to be decided and let n r(m). Then any formula F' occurring in the tree of all self reductions will have size ? m and f(F') will have size at most n. Regarding k as a possible value for C5(n)(.) we define Ln,k (F') : g(#n.f(F?).k) as the labeling:labeling function. .L=uL ?: Let F be a formula of size m and let ? r(m). Furthermore, let kCs(n) be the true census. Then the function L (F') u*k for formulas (nulas) 7, of size at nost n satisfies: 1. F' is not satisfiable if and only if L (F) is in 5; n*k 2. The unsatisfiable formulas (nulas) of size at nost n are mapped (napped) by Lu*k to at nost p(q(2n+clog(n))) ? p(qC3n)) distinct strings of 5 where c is a constant depending only on: Proof: Part 1 is immediate (innediate) from (fr?) Theorem (ren) 5. For part 2 observe '2n+tlogCn) S 3n is a bound on the size of ???* f(F1) (.) (k). Applying p 0 q gives an upper bound on the census of strings the triple could map (nap) to. We now know a suitable labeling:labeling function exists for k : c5(n); and we are aware c (n)* is the true census! The algorithn in the following theorem (n) shows how we 5 may try Ln*k for all k ? Theorem 1?: If NP has a sparse conplete set* then ? : NP. Proof: We give a deterninistic procedure to recognize SAT. Let F be a formula (nula) of size n. Apply the following algorithn: begin For k : ? to p(r(m)) do Execute the depth first search algorithm using label:labeling function: Lm.k(F') at each node F' encounters in the pruned search tree. If a satisfying assignment is found(.) then halt; F is satisfiable. If a tree search visits more than m + rn * p(q(3 r(m))) internal nodes(1) then halt the search for this k. end: F is now satisfiable; end The algorithm clearly runs in polynomial time since the loop is executed at most p(r(m)) times and each iteration of the loop visits a polynomially (nially) bounded in m number of nodes. The correctness of the algorithm is established in the following result. J=ma 1: If F is satisfiable(1) then for k : cs(r(m)) the search will find a satisfying assignment. Proof: By Theorem 5(.) this k gives a labeling:labeling function maps the unsatisfiable formulas of size at most m to a polynomially bounded set. Fortune shows the depth first search will find a satisfying assignment visiting at most m + m * p(q(3r(m)))internal nodes. QED. It is interesting to note we have computed the census: a satisfying assignment is found with a number of k's; similarly(.) if no satisfying assignment existed(1) of many of the trees may be searched but the tree with kCs(r(m)) is now distinguished. The method of conducting many tree searches is parallelled in the uniform algorithm (-rithm) technique by Karp and Lipton (KL). They show when NP is accepted in P with log( ) advice(1) then ? : NP. The census function might be compared to a log( )-advisor to the polynomial information in the set 5. It is not necessary to assume an NP recognizer for the sparse set: 5 is NP-hard. Lemma (na) 11: If 5 is sparse and NP-hard(1) then a set St is sparse(.)NP complete(.) and has a P-time reduction: SAT --> St is length increasing. Proof: Let f: SAT 5 be a p-time reduction and let # be a new symbol. Define f#: SAT ? St by where p : max(O. lf(F)1 - Fl). Clearly St is sparse. The mapping f# reduces SAT to St(.) Membership of 5 in St is verified by guessing a satisfiable formula maps to a and verifying (? ifying) satisfiability. Corollary (?): If NP is sparse reducible, then ? : NP. 1. s QED. Although the isomorphism results (EBH) are the direct ancestors of the work discussed (-cussed) here(1) the concept of sparseness has another motivation as stated in the Introduction: Can a "sparse amount of information" be used to solve NP problems in polynomial time? The approach here assumes the information is given as a many-one reduction to a sparse set. For Turing reductions(.) the information is given as a sparse oracle set. A. Meyer has shown a sparse oracle for NP is equivalent to the existence of polynomial (-nomial) size circuit to solve NP (Bfl]. The recent work by Karp(.) Lipton and Sipser (KL) has shown if NP has polynomial size circuits(1) then the polynomial time P hierarchy (s) collapses (??) Their result is weaker than Theorem 10(.) but it also has a weaker hypothesis. It is an interesting open problem to determine if polynomial (-mial) size circuits for NP implies ? : NP. Similarly(.) now we know sparse NP complete sets cannot exist and P ? NP(.) it is interesting to determine there may exist sparse sets in NP - P. By Ladner's result (EL) we know if P ? NP then there exist incomplete sets in NP - P; the proof of this result yields sparse sets and we have found a way to modify it to yield sparse sets. For a related study of the structure of NP complete sets(.) see (LLR). In this paper Landweber(.) Lipton(.) and Robertson explore the possibility of having large gaps in NP complete sets. Finally(.) it is hoped the success in solving the sparseness conjecture will initiate a new attack on the p-isomorphism conjecture for NP complete sets. In conclusion(.) it is interesting to see how many people have directly or indirectly worked and contributed to the solution of the sparseness conjecture(.) among then(.) referenced in this paper are L. Berman. P. Berman. R. Book. D. Dobkin, 5. Fortune. J. (II) Hartmanis. R. Karp. L. Landweber. R. Lipton. 5. Mahaney. A. Xeyer. N.Patterson. E. Robertson. A. Selman. M. Sipser. and C. Wrathall. (AHu) Aho. A.V., Hopcroft. J.E.(.) and Ulinian. J.D.(.) The Design and Analysis of Computer (rn-puter) Algorithms. Addison-Wesley (1974). B) Berman. P. "Relationship Between Density and Deterministic Complexity of NP-Complete (-Complete) Languages." Fifth Int. Colloquium (ollocujum) on Automata. Languages and Programming (?ing). Italy (July 1978). Springer Verlag Lecture Notes in Computer Science Vol. 62. pp. 63-71. (BH) Berman. L. and (R) Hartmanis, J., "On Isomorphisms and Density of NP and Other Complete (rn-plete) Sets." SlAM J. Comput(.). 6 (1977). pp. 305-322. See also Proceedings 8th Annual ACH Synposium on Theory of Computing (titing). (1976) pp 3040. (BWSD) Book, R.. Wrathall. C.. Selnan. A.. and Dobkin. D.. "Inclusion Complete Tally Languages and the (U) Hartnanis-Bernan Conjecture." (C) Cook. S.A.. "The Complexity of Theorem (n) Proving Procedures." Proc. 3rd Annual ACn Symposium on Theory of Computing. (1977) pp. 151-158. (F) Fortune. 5., "A Note on Sparse Complete Sets." SlAM J. Comput(.). (1979). pp. 431-433. (GJ) Carey. M.R.. and Johnson. D.S(.). "Computers and intractability. A Guide to the Theory of NP-Completeness." W.H. Freeman and Co(.). San Francisco. 1979. (HBl) Hartmanis. J., and Berman. L(.). "On Polynomial Time Isomorphisms of Complete Sets." Theoretical Computer Science. 3rd CI Conference. March. 1977. Lecture Note in Computer Science. Vol. 48. Springer-Verlag. Heidelberg. pp. 1-15. (uB2) Hartmanis. J(.). and Berman. L(.). (w) On Polynomial Time Isomorphisms of Some New Complete Sets." j. of Computer and System Sciences. Vol. 16 (1978). pp. 418-422. (HM) Hartruanis. J(.). and (?t) Mahaney. S.R(.). "On Census Complexity and Sparseness of NP-Complete (-Complete) Sets." Department of Computer Science. Cornell University. Technical Report TR 80-416 (April 1980). (EK) Karp. R.. "Reducibility Among Combinatorial (nbinatorial) Problems." in Complexity of Computer Computations (R.E. Miller and J.W. Thatcher. eds.). Plenum. New York (1972). (KL) Karp. R.M.* and Lipton. R.J.. "Some Connections between Nonuniform and Uniform Complexity Classes." Proc. 12th ACM Symposium on Theory of Computing. (May (Nay) 1980). (EL) Ladner, R.E.. "On the Structure of Polynomial Time Reducibility." J. Assoc. Computing Machinery. Vol. 22 (1975). pp. 135--H171. (ELLR) Landweber. L.ll(.). Lipton. R.J(.). and Robertson. E.L.1 "On the Structure of Sets in NP and Other Complexity Classes." Computer Science Tech. Report 342 (December (nber)(19,8). University of Wisconsin-Madison. (EM) Mahaney. S.R(.). "Sparse Complete Sets for NP: Solution of a Conjecture by Berman and (fl) Hartmanis. (W) Department of Computer Science. Cornell University. Technical Report TIL 80-417 (April 1980). (EMP) Patterson. M. and Meyer. A.R(.). ("?ith) With What Frequency are Apparently Intractable Problens Difficult?", Laboratory for Computer Science. M.I.T. Tech. Report(.). February 1919. (5) Stockmeyer. L.J(.). "The Polynomial-(nial)Time Hierarchy." Theoretical Computer Science Vol. 3. (1977). pp. 1-22. From bthate at gmail.com Fri Apr 2 08:28:45 2010 From: bthate at gmail.com (Bart Thate) Date: Fri, 2 Apr 2010 05:28:45 -0700 (PDT) Subject: JSONBOT 0.1 released Message-ID: <249cfabf-047f-4c80-a93f-68694914b2c2@o30g2000yqb.googlegroups.com> Introducing JSONBOT JSONBOT is a bot that stores all its data in json format. It runs on the Google Application Engine and can thus support wave, web and xmpp. Standalone programms are provided for IRC and console, the goal is to let both clientside and GAE side communicate through JSON either over XMPP or HTTP POST. this bot needs google_appengine installed in your home dir JSONBOT provides the following programs: j sb - console version of jsonbot jsb-irc - IRC version of jsonbot jsb-run - run a release in the GAE dev_appserver jsb-release - create a new release directory jsb-upload - upload a release to the GAE JSONBOT 0.1 contains the following plugins: 8b - eight ball admin - administator related commands ask - plugin for asking "experts" a question choice - choice out of a list .. used in pipelines core - core bot commands count - count the numbers in a resutl .. used in pipelines gadget - wave gadget support gcalc - use google to calculate gozernet - connect multiple JSONBOTs through xmpp grep - grep the result .. used in pipelines hubbub - pubsubhubbub plugin providing subscribe functionality ipcalc - ipcalculator irc - IRC related commands misc - other commands more - do a more on buffered output not - negated grep .. used in pipelines outputcache - show outputcache data relay - relay to other waves/xmpp account reload - reloading of plugins reverse - reverse the result .. also used in pipelines sort - sort the result .. used in pipelines tail - tail the result .. used in pipelines tinyurl - get a tinyurl uniq - make the result unique .. used in pipelines user - user management userstate - userstate management watcher - watch waves .. get notified in xmpp wave - wave related commands welcome - welcome messages shown in the gadget wikipedia - query wikipedia To upload your own bot do the following: you need an account on the Google Application Engine. see http://appengine.google.com/ 1) run jsb-release yourbotname - this will create a uploadable dir 2) run jsb-upload yourbotname this enables web and xmpp, for wave you need to do the following: 2) go to https://wave.google.com/wave/robot/register and register your bot 3) edit ~/regs/yourbotname/ dir and copy the verification token and secret to the credentials.py file 4) run jsb-release yourbotname 4) run jsb-upload yourbotname 5) once its uploaded click the "verify" button 6) copy the consumer key and secret to the credentials.py file en run jsb-upload again 7) done ! Now you should be able to do the following: 1) visit the website at http://yourbotname.appspot.com 2) add the bot as Jabber buddy at yourbotn... at appspot.com 3) the same as wave bot 4) on joining a wave the bot loads a gadget from http://yourbotname.appspot.com/gadget.xml 5) manifest to add your bot to the waves newwave menu use http://yourbotname.appspot.com/feeder.xml JSONBOT is open source (MIT license) and free to clone when needed, patches welcomed though ;] home: http://jsonbot.googlecode.com/ demo: http://jsonbot.appspot.com/ wave/xmpp: jsonbot at appspot.com contact: bthate at gmail.com From alfps at start.no Fri Apr 2 08:34:28 2010 From: alfps at start.no (Alf P. Steinbach) Date: Fri, 02 Apr 2010 14:34:28 +0200 Subject: subclass of object In-Reply-To: References: Message-ID: * Steve Holden: > Alf P. Steinbach wrote: >> * Jason Friedman: >>> Hi, what is the difference between: >>> >>> def MyClass(object): >>> pass >>> >>> and >>> >>> def MyClass(): >>> pass >> If you really meant 'def', then the first is a routine taking one >> argument, and the second is a routine of no arguments. >> >> If you meant 'class' instead of 'def', then it depends on the Python >> version. >> >> In Py2 the first then defines a new-style class, while the second >> defines an old-style class. E.g. you can see some difference by checking >> with 'isinstance'. In Py3 there's no difference. >> > Interesting. I actually read "class" for "def" and replied accordingly. > > As can plainly be seen ... Yes, the names act as comments about intent. Such comments can be misleading about what the code actually does. Since I think you're very interested in the human aspect of this I suggest you try to find information about how master chess players remember chess boards. As I recall, they find it really difficult to remember random boards, while boards that represent actual chess games are remembered at a glance. Indicating that what's remembered is at a much higher level of abstraction than piece positions. Cheers, - Alf From hardmath at gmail.com Fri Apr 2 08:36:27 2010 From: hardmath at gmail.com (Chip Eastham) Date: Fri, 2 Apr 2010 05:36:27 -0700 (PDT) Subject: plagiarism, no follow-ups please References: Message-ID: On Apr 2, 6:14?am, A Serious Moment cross-posted an OCR'd version of a 1980 paper by SR Mahaney, mutilating the text further to remove its attribution and create the false impression of authorship by the (im)poster. From hardmath at gmail.com Fri Apr 2 09:24:09 2010 From: hardmath at gmail.com (Chip Eastham) Date: Fri, 2 Apr 2010 06:24:09 -0700 (PDT) Subject: plagiarism, no follow-ups please References: <5ec848a6-5caf-486a-9f9d-b6c962fc6fb0@15g2000yqi.googlegroups.com> Message-ID: <37450dea-20d7-43fc-8f46-51db99526666@v20g2000yqv.googlegroups.com> On Apr 2, 8:27?am, A Serious Moment cross-posted a 1980 paper by J. Hartmanis and S.R. Mahaney, falsely taking credit for their work. From aaron.watters at gmail.com Fri Apr 2 09:40:41 2010 From: aaron.watters at gmail.com (Aaron Watters) Date: Fri, 2 Apr 2010 06:40:41 -0700 (PDT) Subject: CGI templating with python References: Message-ID: On Apr 1, 11:19?am, KB wrote: > > Django will probably get you where you want to go the fastest: > > > ? ?http://www.djangoproject.com/ > > > In particular, its admin interface will probably automatically generate a usable > > UI for you without your having to write many templates at all. > > Robert, > > Thank you very very much. I had a brief peruse of django last night > and it does indeed look like what I am after! Will take me some > time :) to delve into it deeper but I wanted to thank you! You could also look at WHIFF and try out the test drive. http://whiffdoc.appspot.com/docs/W.intro -- Aaron Watters === This one goes to 11. From pmaupin at gmail.com Fri Apr 2 09:48:47 2010 From: pmaupin at gmail.com (Patrick Maupin) Date: Fri, 2 Apr 2010 06:48:47 -0700 (PDT) Subject: Splitting a string References: Message-ID: <450895af-d8ec-4312-a31e-569e39aaa319@w17g2000yqj.googlegroups.com> On Apr 2, 6:24?am, Peter Otten <__pete... at web.de> wrote: > Thomas Heller wrote: > > Maybe I'm just lazy, but what is the fastest way to convert a string > > into a tuple containing character sequences and integer numbers, like > > this: > > > 'si_pos_99_rep_1_0.ita' ?-> ('si_pos_', 99, '_rep_', 1, '_', 0, '.ita') > >>> parts = re.compile("([+-]?\d+)").split('si_pos_99_rep_1_0.ita') > >>> parts[1::2] = map(int, parts[1::2]) > >>> parts > > ['si_pos_', 99, '_rep_', 1, '_', 0, '.ita'] > > Peter You beat me to it. re.split() seems underappreciated for some reason. When I first started using it (even though it was faster for the tasks I was using it for than other things) I was really annoyed at the empty strings it was providing between matches. It is only within the past couple of years that I have come to appreciate the elegant solutions that those empty strings allow for. In short, re.split() is by far the fastest and most elegant way to use the re module for a large class of problems. So, the only thing I have to add to this solution is that, for this particular regular expression, if the source string starts with or ends with digits, you will get empty strings at the beginning or end of the resultant list, so if this is a problem, you will want to check for and discard those. Regards, Pat From showell30 at yahoo.com Fri Apr 2 10:05:49 2010 From: showell30 at yahoo.com (Steve Howell) Date: Fri, 2 Apr 2010 07:05:49 -0700 (PDT) Subject: (a==b) ? 'Yes' : 'No' References: <4bb5b326$0$8827$c3e8da3@news.astraweb.com> Message-ID: <19536991-2c54-42a5-8d22-f3c118a74a21@k17g2000yqb.googlegroups.com> On Apr 2, 2:04?am, Steven D'Aprano wrote: > On Thu, 01 Apr 2010 21:16:18 -0700, Steve Howell wrote: > > The ironic thing about the ternary operator is that it is not really > > ternary; it's binary. ?Even just making an expression from a binary > > operator inevitably leads to syntax hell. > > > There is a principle of programming that I would like to coin, which is > > the "Tyranny of Three." > > > It is impossible to code for any expression that has three possible > > values in any kind of elegant way. ?It's just impossible. ?Try to code > > the bowling game without tearing out your teeth--three conditions: > > strike, spare, or normal. > > > The tyranny of three is that 3 is too small for an elegant N-based > > solution and too large for a simple condition. > > I'm afraid I don't understand any of that. Can you explain further? > > How is the ternary operator "not really ternary, it's binary"? It > requires three arguments, not two, which makes it ternary. In Python > syntax: > Of course, I understand that the ternary operator has three arguments, but it only has two possible outcomes. You asked me to elaborate on the "Tyranny of Three." Let's say you have three possible outcomes. In some languages you would write something like this: mark = (rolls == 1) && (pins == 10) ? 'strike' : (rolls == 2) && (pins == 10) ? 'spare' : 'normal' Many people consider the above very ugly, so they write it like so: if pins == 10: if rolls == 1: return 'strike' else: return 'spare' else: return 'normal' Then the next programmer comes along and "cleans up": if pins == 10: return 'strike' if rolls == 1 else 'spare' else: return 'normal' Then there is this alternative: if rolls == 2: return 'spare' if pins == 10 else 'normal' else: return 'strike' And then: if rolls == 2: if pins == 10 return 'spare' else return 'normal else: return 'strike' Or even this: return 'strike' if rolls == 1 else ('spare' if pins == 10 else 'normal') The "Tyranny of Three" refers to a problem where there are an infinite number of valid solutions, but none of them have any essential beauty, so they lead to endless nitpicking and code churn. From wanderer at dialup4less.com Fri Apr 2 10:06:11 2010 From: wanderer at dialup4less.com (Wanderer) Date: Fri, 2 Apr 2010 07:06:11 -0700 (PDT) Subject: off topic but please forgive me me and answer References: <4bb505c5$0$1133$4fafbaef@reader3.news.tin.it> <32d91d4f-616f-404b-afbb-3b97dc380a67@e7g2000yqf.googlegroups.com> Message-ID: <5f5979c3-e30b-436a-87c0-e1beb59c573b@u32g2000vbc.googlegroups.com> On Apr 1, 7:34?pm, Patrick Maupin wrote: > On Apr 1, 4:42?pm, Tim Chase wrote: > > Uh, did you try it at the python prompt? ? When I try it at the IPython prompt, I get Object 'how much is one half times one half' not found. From steve at holdenweb.com Fri Apr 2 10:21:52 2010 From: steve at holdenweb.com (Steve Holden) Date: Fri, 02 Apr 2010 10:21:52 -0400 Subject: (a==b) ? 'Yes' : 'No' In-Reply-To: <19536991-2c54-42a5-8d22-f3c118a74a21@k17g2000yqb.googlegroups.com> References: <4bb5b326$0$8827$c3e8da3@news.astraweb.com> <19536991-2c54-42a5-8d22-f3c118a74a21@k17g2000yqb.googlegroups.com> Message-ID: Steve Howell wrote: > On Apr 2, 2:04 am, Steven D'Aprano cybersource.com.au> wrote: [...] >> How is the ternary operator "not really ternary, it's binary"? It >> requires three arguments, not two, which makes it ternary. In Python >> syntax: >> > > Of course, I understand that the ternary operator has three arguments, > but it only has two possible outcomes. > That doesn't make it a binary operator. Otherwise what's long multiplication, which has an infinite number of possible outcomes? > You asked me to elaborate on the "Tyranny of Three." Let's say you > have three possible outcomes. > > In some languages you would write something like this: > > mark = (rolls == 1) && (pins == 10) ? 'strike' : > (rolls == 2) && (pins == 10) ? 'spare' : > 'normal' > > Many people consider the above very ugly, so they write it like so: > > if pins == 10: > if rolls == 1: > return 'strike' > else: > return 'spare' > else: > return 'normal' > > Then the next programmer comes along and "cleans up": > > if pins == 10: > return 'strike' if rolls == 1 else 'spare' > else: > return 'normal' > > Then there is this alternative: > > if rolls == 2: > return 'spare' if pins == 10 else 'normal' > else: > return 'strike' > > And then: > > if rolls == 2: > if pins == 10 > return 'spare' > else > return 'normal > else: > return 'strike' > > Or even this: > > return 'strike' if rolls == 1 else ('spare' if pins == 10 else > 'normal') > > The "Tyranny of Three" refers to a problem where there are an infinite > number of valid solutions, but none of them have any essential beauty, > so they lead to endless nitpicking and code churn. > The Real Programmer (tm) simply chooses one, implements it and moves on. While philosophical discussions are interesting they don't pay the bills. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 See PyCon Talks from Atlanta 2010 http://pycon.blip.tv/ Holden Web LLC http://www.holdenweb.com/ UPCOMING EVENTS: http://holdenweb.eventbrite.com/ From showell30 at yahoo.com Fri Apr 2 10:26:19 2010 From: showell30 at yahoo.com (Steve Howell) Date: Fri, 2 Apr 2010 07:26:19 -0700 (PDT) Subject: (a==b) ? 'Yes' : 'No' References: <4bb5b326$0$8827$c3e8da3@news.astraweb.com> <19536991-2c54-42a5-8d22-f3c118a74a21@k17g2000yqb.googlegroups.com> Message-ID: On Apr 2, 7:05?am, Steve Howell wrote: > On Apr 2, 2:04?am, Steven D'Aprano > > > cybersource.com.au> wrote: > > On Thu, 01 Apr 2010 21:16:18 -0700, Steve Howell wrote: > > > The ironic thing about the ternary operator is that it is not really > > > ternary; it's binary. ?Even just making an expression from a binary > > > operator inevitably leads to syntax hell. > > > > There is a principle of programming that I would like to coin, which is > > > the "Tyranny of Three." > > > > It is impossible to code for any expression that has three possible > > > values in any kind of elegant way. ?It's just impossible. ?Try to code > > > the bowling game without tearing out your teeth--three conditions: > > > strike, spare, or normal. > > > > The tyranny of three is that 3 is too small for an elegant N-based > > > solution and too large for a simple condition. > > > I'm afraid I don't understand any of that. Can you explain further? > > > How is the ternary operator "not really ternary, it's binary"? It > > requires three arguments, not two, which makes it ternary. In Python > > syntax: > > Of course, I understand that the ternary operator has three arguments, > but it only has two possible outcomes. > > You asked me to elaborate on the "Tyranny of Three." ?Let's say you > have three possible outcomes. > > In some languages you would write something like this: > > mark = (rolls == 1) && (pins == 10) ? 'strike' : > ? ? ? ?(rolls == 2) && (pins == 10) ? 'spare' : > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? 'normal' > > Many people consider the above very ugly, so they write it like so: > > ? if pins == 10: > ? ? ?if rolls == 1: > ? ? ? ? return 'strike' > ? ? ?else: > ? ? ? ? return 'spare' > ? else: > ? ? ?return 'normal' > > Then the next programmer comes along and "cleans up": > > ? if pins == 10: > ? ? return 'strike' if rolls == 1 else 'spare' > ? else: > ? ? return 'normal' > > Then there is this alternative: > > ? if rolls == 2: > ? ? return 'spare' if pins == 10 else 'normal' > ? else: > ? ? return 'strike' > > And then: > > ? if rolls == 2: > ? ? if pins == 10 > ? ? ? return 'spare' > ? ? else > ? ? ? return 'normal > ? else: > ? ? return 'strike' > > Or even this: > > ? ?return 'strike' if rolls == 1 else ('spare' if pins == 10 else > 'normal') > > The "Tyranny of Three" refers to a problem where there are an infinite > number of valid solutions, but none of them have any essential beauty, > so they lead to endless nitpicking and code churn. I forgot this one: def obfuscated_triager(rolls, pins, lookup = ['normal'] * 10 + ['strike'] + [None] * 9 + ['spare'] ): return lookup[rolls * pins] From showell30 at yahoo.com Fri Apr 2 10:31:06 2010 From: showell30 at yahoo.com (Steve Howell) Date: Fri, 2 Apr 2010 07:31:06 -0700 (PDT) Subject: (a==b) ? 'Yes' : 'No' References: <4bb5b326$0$8827$c3e8da3@news.astraweb.com> <19536991-2c54-42a5-8d22-f3c118a74a21@k17g2000yqb.googlegroups.com> Message-ID: <5019b758-0950-4ffc-9b58-2f1eead4d5b4@v20g2000yqv.googlegroups.com> On Apr 2, 7:21?am, Steve Holden wrote: > Steve Howell wrote: > > On Apr 2, 2:04 am, Steven D'Aprano > cybersource.com.au> wrote: > [...] > >> How is the ternary operator "not really ternary, it's binary"? It > >> requires three arguments, not two, which makes it ternary. In Python > >> syntax: > > > Of course, I understand that the ternary operator has three arguments, > > but it only has two possible outcomes. > > That doesn't make it a binary operator. Otherwise what's long > multiplication, which has an infinite number of possible outcomes? > Ok, it's not a binary operator. I just meant it only really selects from two possible expressions, so you would think there would be one good way to express that in code, but of course any variation of the ternary operator leads to endless debates. > > > > You asked me to elaborate on the "Tyranny of Three." ?Let's say you > > have three possible outcomes. > > > In some languages you would write something like this: > > > mark = (rolls == 1) && (pins == 10) ? 'strike' : > > ? ? ? ?(rolls == 2) && (pins == 10) ? 'spare' : > > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? 'normal' > > > Many people consider the above very ugly, so they write it like so: > > > ? if pins == 10: > > ? ? ?if rolls == 1: > > ? ? ? ? return 'strike' > > ? ? ?else: > > ? ? ? ? return 'spare' > > ? else: > > ? ? ?return 'normal' > > > Then the next programmer comes along and "cleans up": > > > ? if pins == 10: > > ? ? return 'strike' if rolls == 1 else 'spare' > > ? else: > > ? ? return 'normal' > > > Then there is this alternative: > > > ? if rolls == 2: > > ? ? return 'spare' if pins == 10 else 'normal' > > ? else: > > ? ? return 'strike' > > > And then: > > > ? if rolls == 2: > > ? ? if pins == 10 > > ? ? ? return 'spare' > > ? ? else > > ? ? ? return 'normal > > ? else: > > ? ? return 'strike' > > > Or even this: > > > ? ?return 'strike' if rolls == 1 else ('spare' if pins == 10 else > > 'normal') > > > The "Tyranny of Three" refers to a problem where there are an infinite > > number of valid solutions, but none of them have any essential beauty, > > so they lead to endless nitpicking and code churn. > > The Real Programmer (tm) simply chooses one, implements it and moves on. > While philosophical discussions are interesting they don't pay the bills. > Agreed. The nitpicking and code churn tends to come up when you have multiple programmers with different aesthetics, although sometimes even the solo programmer can get overly fiddly. From aahz at pythoncraft.com Fri Apr 2 10:32:52 2010 From: aahz at pythoncraft.com (Aahz) Date: 2 Apr 2010 07:32:52 -0700 Subject: Dynamic Class Creation References: <8d79f0cb-9c5b-4243-8891-a15fb311f652@z18g2000prh.googlegroups.com> Message-ID: In article <8d79f0cb-9c5b-4243-8891-a15fb311f652 at z18g2000prh.googlegroups.com>, Josh English wrote: > > > Analog Science Fiction and Fact > Analog > Science Fiction > First Contact > Hard Science Fiction >
> Stanley Schmidt, Editor > 267 Broadway, 4th Floor > New York, NY 10007-2352 >
> http://www.analogsf.com >
> >A child element with text and an attribute or two, for example, pose a >problem. I can call Market.title but should I try Market.title.field >or Market.title_field. > >Multiple elements, such as keywords, are allowed in xml but harder to >map to the object. I don't know if I want to go create a list and >methods for accessing those keywords as a list, or redefine the rules >of my XML to not allow multiple child elements with the same tag. I >can't decide. You should always think "LIST!" any time you have the potential for multiple elements with the same semantic tag. Whether you do it as a list for all elements or as a combo dict/list is something you need to decide; the latter is faster in many ways but is more cumbersome: Market.title.keyword[1] (Instance attributes and dict keys are almost trivially convertible.) You would probably get some mileage out of looking at the ElementTree implementation. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Why is this newsgroup different from all other newsgroups? From python.list at tim.thechases.com Fri Apr 2 10:52:36 2010 From: python.list at tim.thechases.com (Tim Chase) Date: Fri, 02 Apr 2010 09:52:36 -0500 Subject: (a==b) ? 'Yes' : 'No' In-Reply-To: References: <4bb5b326$0$8827$c3e8da3@news.astraweb.com> <19536991-2c54-42a5-8d22-f3c118a74a21@k17g2000yqb.googlegroups.com> Message-ID: <4BB604B4.80500@tim.thechases.com> Steve Howell wrote: > I forgot this one: > > def obfuscated_triager(rolls, pins, > lookup = ['normal'] * 10 + ['strike'] + [None] * 9 + ['spare'] > ): > return lookup[rolls * pins] Bah...no need to be _quite_ so obscure: def triager(rolls, pins): return { (1, 10):'strike', (2,10):'spare', (2,0):'wow, you stink', }.get((rolls, pins), 'normal') ;-) -tkc From showell30 at yahoo.com Fri Apr 2 10:58:14 2010 From: showell30 at yahoo.com (Steve Howell) Date: Fri, 2 Apr 2010 07:58:14 -0700 (PDT) Subject: (a==b) ? 'Yes' : 'No' References: <4bb5b326$0$8827$c3e8da3@news.astraweb.com> <19536991-2c54-42a5-8d22-f3c118a74a21@k17g2000yqb.googlegroups.com> Message-ID: <6c06c740-37de-42a1-9c01-921e0b285ef0@y17g2000yqd.googlegroups.com> On Apr 2, 7:52?am, Tim Chase wrote: > Steve Howell wrote: > > I forgot this one: > > > def obfuscated_triager(rolls, pins, > > ? ? ? ? lookup = ['normal'] * 10 + ['strike'] + [None] * 9 + ['spare'] > > ? ? ? ? ): > > ? ? return lookup[rolls * pins] > > Bah...no need to be _quite_ so obscure: > ? ?def triager(rolls, pins): > ? ? ?return { > ? ? ? ?(1, 10):'strike', > ? ? ? ?(2,10):'spare', > ? ? ? ?(2,0):'wow, you stink', > ? ? ? ?}.get((rolls, pins), 'normal') > > ;-) > Well played. From tjreedy at udel.edu Fri Apr 2 11:05:50 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 02 Apr 2010 11:05:50 -0400 Subject: Splitting a string In-Reply-To: References: Message-ID: On 4/2/2010 6:21 AM, Shashwat Anand wrote: > >>> s = 'si_pos_99_rep_1_0.ita' > >>> res = tuple(re.split(r'(\d+)', s)) > >>> res > ('si_pos_', '99', '_rep_', '1', '_', '0', '.ita') This solves the core of the problem, but is not quite there ;-). Thomas requested conversion of int literals to ints, which is easy: import re s = 'si_pos_99_rep_1_0.ita' res = re.split(r'(\d+)', s) for i,s in enumerate(res): try: res[i] = int(s) except: pass res = tuple(res) print(res) ('si_pos_', 99, '_rep_', 1, '_', 0, '.ita') Terry Jan Reedy > On Fri, Apr 2, 2010 at 3:42 PM, Thomas Heller > wrote: > > Maybe I'm just lazy, but what is the fastest way to convert a string > into a tuple containing character sequences and integer numbers, > like this: > > > 'si_pos_99_rep_1_0.ita' -> ('si_pos_', 99, '_rep_', 1, '_', 0, '.ita') From stefan_ml at behnel.de Fri Apr 2 11:11:00 2010 From: stefan_ml at behnel.de (Stefan Behnel) Date: Fri, 02 Apr 2010 17:11:00 +0200 Subject: off topic but please forgive me me and answer In-Reply-To: References: <4bb505c5$0$1133$4fafbaef@reader3.news.tin.it> Message-ID: Patrick Maupin, 02.04.2010 07:25: > On Apr 1, 11:52 pm, Dennis Lee Bieber wrote: >> On Thu, 01 Apr 2010 22:44:51 +0200, superpollo >> declaimed the following in gmane.comp.python.general: >> >>> how much is one half times one half? >> >> import math >> print math.exp((math.log(1) - math.log(2)) >> + (math.log(1) - math.log(2))) > > That's all well and good, but base 'e' is kind of complicated. Some > of us were using base 10, and others took Tim's lead and were using > base 2: > > >>> print math.exp(((math.log(1)/math.log(2) - math.log(2)/math.log(2)) + (math.log(1)/math.log(2) - math.log(2)/math.log(2)))*math.log(2)) > 0.25 The above can be rewritten as print('0.25') which is much faster and also a lot more readable. Stefan From marty.musatov at gmail.com Fri Apr 2 11:35:09 2010 From: marty.musatov at gmail.com (A Serious Moment) Date: Fri, 2 Apr 2010 08:35:09 -0700 (PDT) Subject: I'm not sure you understand References: Message-ID: On Apr 2, 5:36?am, Chip Eastham wrote: > On Apr 2, 6:14?am, A Serious Moment > cross-posted > an OCR'd version of a 1980 paper > by SR Mahaney, mutilating the text > further to remove its attribution > and create the false impression of > authorship by the (im)poster. I'm afraid you misunderstand what I am trying to do. The text is not mutilated. It is adapted. for llP: Sparse Comp1ete Sets Solution of a Conjecture In this paper we show if NP has a sparse complete set under many-one reductions, then ? NP. The result is extended to show NP is sparse reducible, then P = ip. The main technicues of this paper generalize the :;P recognizer for the compliment of a sparse complete set with census function to the case where the census function is not 1'? own (c.f. [1? ii]), then a many-one reduction of tI: gives us the language to the sparse set permits a polynomial time bounded tree search as in [ti, [F], or [?:P]. Even without actual knowledge of the census, the algorithm utilizes the properties of the true census to decide membership in SAT in polynomial time. Sparse Complete Sets for `LP: Solution of a Conjecture by Martin Michael Musatov 1. Computer Science L. ? nan and J. 1? at?:i is [tH] under the assumption P? i?. P all l lP-complete sets are iso-morphic; i.e. there are polynomial time, bijective reductions with polynomial time inverse reductions between any two NP-cot-:complete sets. A consequence of this conjecture is all NP-complete sets have equivalent density; in particular, no sparse set could be i-complete unless PP. 13e ? an EB] give a partial solution to the problem: by showing if a subset of an SL i? language is NP-co:complete (a for ti or i, sparse), then P = 1;P. This result is strengthened by Fortune [F] showing if co-NP has a sparse complete set, then P = 1p? It is necessary to assume the satisfiable formulas reduce to a sparse set since the proof uses the conjunctive self-reducibility of non- satisfiable for:formulas and the sparse set to realize a polynomial time algorithm. N and P at e[?2] show similar results. ll a rttq a n is and f[E14] extends the results of Fortune and NP at e by showing if l IP has a sparse complete set with an easily computable census function, then NP = co-I?P; P = tT. P follows by Fortune 1s the or e?. The question of how easy it is to compute census functions for l?- complete sets is left open. In light of Fortune's observation about co-I r 1 the original conjecture by ten? a n and ll at i?a n is on reducing `?` to a sparse set series temptingly close, however the tree search methods of [B], [1], [i,:p] utilize the conjunctive self-reducibility of the co-l;P- cot?-complete problem SAT0. In this paper we settle the conjecture by showing if an L'P-complete set is ? any-one reducible to a sparse set, then P = i?. Thus determining the existence of a sparse co-??:complete set for l;p is equivalent to solving the P = NP? problem. We also show the census function of a sparse NP-co?i:complete set is cota:computable in P. Section 2 contains definitions an outline of the tree search time method for showing sparse sets for co-NP i? implies P = ??1. Section 3 contains the ? a in results; it assumes n familiarity with the tree search methods. ?. Preliminaries We will consider languages over an alphabet ? with two or or e sy?- symbols. We assume fa?:familiarity with NP--Hcor?:complete sets (cf. Ec], [K] or EAHU)). All the reductions in this paper will be polynomial time many-one reductions. Definition: A subset 5 of is sparse if there is a polynomial so the number of strings in 5 of size at most n is at most p. We restate the following theorem (cf. [r] or [iP]) and s'etch: sketch the proof. Theorem 1.1. If SATc is reducible to a sparse set, then p = NP. Proof. Let f:SAT --> 5 be a reduction to & sparse set, 5, and let F be a formula whose satisfiability is to be decided. We search a binary tree formed from self-reductions of F as follows: F is at the root; a for??:formula C with variables X1, ... , X occurring in the tree will n have sons G0 a n? G1 where `: is replaced by false and true, respectively, and trivial si?:simplifications are performed ( e.g. true or = true). If the for i:?formula F has n variables, then the tree will have 2n?1 nodes. ? i e perform a depth-first search of the tree utilizing the sparse set to prune the search. At each node Ft encounters we compute c a label f(F'). We infer certain labels correspond to SAT by the following: When a node with formula false is found, its label is assigned 1. t'false." ii. t Then two sons of a node have ?:labels assigned V?: false, ?1 then the label of the node is also assigned t'false." (This is tl-ie:time conjunctive self-reducibility of non-?:satisfiable for?:formulas.) We prune the search by stopping if a leaf has for n?:l a true in which case F is satisfiable by the as:s i2 n?:assistant on the p at?: part to the leaf; and by not searching below a node whose label has already been assigned ?false." ?1e follow? j in g:following le r2a establishes poly-not:polynomial running time of the algorithn. Lemna 1.2. Let F be a for?:formula with n variables. Let p(.) be bound Let the density of 5 and let q(.) be a poly-no?:polynomial bounding the increases in size under the reduction f. Then the algorithm= above visits at u most interior nodes. o + n + n * p (q(if?)) Proof. (Er, hT). Observe if a label is expanded ?or e U?:a n Once, then t'j e expansions are all on the sa?:safe path from? the root since path len?:lengths are at L?:least n+l (with leaf), at ?:most n * p(q(iF1)) interior nodes with label ?false? visited. A satisfying assign-ent visits at ti os t another n nodes. QED ?ote:note the algoritbim does not require a sparse set of labels for satisfiable fon:iulas:formulas. The sparse set of labels reduces the number of unsatisfiable foi? ulas:formulas to be searcheci:searched. ?. Solution of tiie:time Con??c?ur?.:concur Initially, we establish the result for a sparse LP-cornplete:complete set. The proof will be modified for the hypothesis that 1?P is sparse reducible. The outline of the proof below is as follo?.s:follows: We first give an flP recognizer for a set si?'ilar:similar to the co? pler:?ent:compiler component of the sparse set 5. 1.?ny-one:many-one reductions of this set to the sparse set are used to prove the existence of a sparse set of labels for SATC; however, tile conputation: time computation of this set of labels requires kno? iing:knowing tie:time census of 5. Finally, the depth--H first search is tiodified:modified to detei? nine:determine satisfiability of a fon?ula:formula. (without actually !:now in g:knowing the census value will generate the sparse set of'?abels:labels for sATC). * For the following discussion let 5 c (0,1) be a sparse coriplete:complete set for I?P under iiiany-one:many-one reductions. Let l,I? be a non-detenninistic:non-deterministic polynot:'ial:polynomial-tiiae:time recognizer of 5 and let c(n) IS fl (A+?)ni ? p(n) where c(.) is the true census function of 5, and p(.) is a polyno? ial:polynomial bound the size of the census. We begin by coljstructing:constructing a non-deteit? inistic:deterministic polynotiial tiL?:time Turi%:Turing ?achine:machine to recognize a flp5e?do?co?ple?entfl:flip 5e do compliment f1 of 5. The inputs include a padding, #n, and a potential census, k. Define the non-dete??inistic:non-deterministic recognizer `A by the following procedure: ?(??,8,k) Check I 5 I <- n; o the n is e:otherwise reject. Check k < p(n); o the n? is e:otherwise reject. Guess ?i' 5k ?? i. for all i, I 5 I <--H n. ii. for all i and j, iii. for all i, checit:check it 5. is accepted by II? iv. check for all i s?s. Leriraa:Lemma 3.1. Let I si < n and k --H< p(n). Then on input (#n,s1k) the inachine:in a machine n' will: a. accept if k < b. reject if k > c(n); and c. if k = c(n), then II accepts if and only if I4? rejects 5. Proof of Lei??.:Lemma. We show part c. If 14 accepts, it will have enun?erated:enumerated the elerients:elements of 5 up to size n, verified they belong to 5, and shown 5 is distinct. Since k is the true census, 11 accepts if and only if & is not in 5. QED Intuitively1: Intuitively 1 for k = c(n), :?` is a recognizer of 5 cor::?lement.:correct or corresponding elements 1?oreover1:1 moreover ii accepts its 1 an?uage: 1n usage in non- detenainistic polynot?ial:polynmial-ti L ie:time (the input #n is ? padding to ensure this). We require labellin'?:labelling functions for pruning tree searches. The following discussion sho?,s:shows how to construct such functions from the sparse set 5 and many-one reductions of L(I): Since N is an UP ??chine: UP Machine and 5 is NP-co?plete:NP-complete, there is a P-time r:iany-one:many-one reduction: g:L(II) --H> 5 so for some monotonic polynorial q(.), inputs two !! of size n are reduced to strings of size at ?ost:most q(n) (cf. [c] and [:3). Si? ilarly:Yes, simililarly, for the i'?-coniplete:i-complete problem SAT, there is a P-ti?e:P-time r?any-one:many-one reduction f:SAT -? 5 (f:SAT minus question space five) and a monotonic polynomial r(.) bounding ti ie:time increase in size. Let F of size m be a f on n ul a:formula to be decided. T?ien:Time ?ny:Many for?nula:formulas F' occurring in the tree of all self reductions will have size < Regarding I t:it as a possible value for c(n), we define: Ln,k (F1) = which will be the labelling function. Lemma 3.2. Let F be a f o i?ul a:formula of size r a. Let n rC?):near C?; i.e. n is a polynotial:polynomial upper bound on the size of f(F') where IF 1 I ? iii.(If 1 I question 3i) Finally, Let k = c(n), the true census. Then the function: Ln?k(Ft):Link(Ft) for forulas:formulas F' of size at most n satisfies: i. F' is not satisfiable if and only if L(F') is in 5; ii. The unsatisfiable for?uljs:formulas of size at i most:i-most in/ are mapped by L to at most: p(q(2n+c'log(n))) ? p(q(3n)) distinct strings of 5 where c' is a constant dependin0':depending 0 o?'ily:o question il y on p(.) Proof: Part i. is imiuediate:immediate froi?:from question LeLTh?:Lemma 2.1. For p?rt ?i..:For part question i observe 2 n + CI i o g(n) ? 3 n: 2n + CI og(n) question 3n is a bound on the size of (#nf(P'), k). Applying p 0 q gives the census of strings in 5 the triple could nap:map onto. QED We now know a suitable labelling function e'?iSt5:exists for k but we do not know c(n)! Tiie:Time algorithir:algorithm in the following theorem shows how we can try (Ln,k:Link) for all (k ? pCn:k question pCn). Theoren:Theorem 3.3. If UP has a sparse complete set, then P UP. Proof: We give a deterrainistic:deterministic procedure to recognize SAT. Let F be a for ra ul a:formula of size m. Apply the follouin0-:following zero minus algorithrn:algorithm: begin For k 0 to p(r(n)) do ?ecute:question execute the depth first search algoriti??:allgorithm question with labelling function: (Ln,k):(Link) at each node F' encountered in the pruned search tree. If a satisfying assignment is found, then halt; F is satisfiable. If a tree search visits rr?re: are two questions regarding than:then n + n * pCq(3 rCr))) internal nodes, then halt the search for this k. end; F is not satisfiable; end The algorith?:algorithm clearly runs in polyno?ial:polynomial-tir? e:time since the loop is e':ecuted:executed at most p(r(n)) tines:times and each iteration of the loop visits at most a polynonial (in i?):(in i question) (nur?er):number of nodes. The correctness of the algorithn is established in the following lei?ia:let i question i a Lemr?:Lemma 3.4. If F is satisfiable, then for k c(r(n)) the search will find a satisfying assigni':?nt:assignment. Proof: By Lenina:Lemma 2.2. This k gives a lab?lling:labelling function maps the unsatisfiable fofl??1as:f of one two question 1 as f of size at no s t:most ta: at or to a polynowially:polynomially bounded set. Fortune shows that thL:the depth first search (?:ill):(question:I will) find a satisfying assignment visiting at most internal nodes. n + n * p(q(3n)) QED It is interesting to note here we have not cor?uted:corrupted or computed the census: a satisfying assignrAent:assignment could be found ?-ith:question minus it h any nu?ber:number of k's; similarly* if no satisfying assignrent:assignment (CA'?5t5*):(See has question five t five times) many of the trees could be searched but the tree with k = c(r(j?)) is not distinguished. The method of conducting many tree searches is parallelled in the un i for a:uniform algorith'n:algorithm technique by Karp and Lipton [KL]. They show if NP could be accepted in (P ?jith):(P question j it h) log(space) advice, then P = iP. The census function `night:might be co?pared:compared to a (log( )-): (Log (inclusive space) minus) advisor to the polynoraial (in for- ? at i on):(in form at i on) in the set 5. It is not necessary to (assur:?):(assume you are without question), (a n flP):(an n-flip) recognizer for the sparse set: just at 5 is NP-hard. Le?'na:Lemma 3.5. If 5 is sparse and (1?P-hard*):(one question p minus hard times) then there is a set s# sparse, (I;P-co?plete*):(I semi p minus see or question p let e) has a P-ti:e:P-time reduction: SAT --> S# length increasing. Proof. Let f: SAT --> 5 be a P-time reduction and let # be a new -:minus symbol. Define f#: SAT --> S# by =:equals v-here p = max( 0, If(F)I - IFI ). Clearly S? is sparse. The mapping f# reduces SAT to S#. `&ia:2?ership:membership of 5 in S# is verified by guessing a satisfiable fon-?ula:formula raps:maps to 5 and verifyin?:verifying question satisfiability. QED Corollary 3.6. If NP is sparse reducible, then P = NP Lastly we renark:remark the census, c(n), of a sparse NP-co?plete:NP minus complete set is coj-:?utable:computable in polynot? ial:polynomial ti?'.e:time. Indeed. assw?ing:assuming P = I?, the census of any sparse set in :?p:question p can be corputed:computed by stand? rd:standard techniques. If 5 is sparse and (t;P-cot?plete*):(t; P-Complete) then P = NI' by Theorei?:Theorem 3.3 so the census of 5 is cot:putablc:computable (iI'):(two i have) polynoi.ial:polynomial tiI-Ae:time. WL':We have proved: Corollary 3.7. If ip has a sparse complete set S1 then the census of ?:question is computable in P. ?:question period. Discussion Although the isonorphism results [t"tl]:[t quote t l] are the direct ancestry of the work discussed here, the concept of sparseness has another (Lotiva tion):motivation. Can a "sparse a?ount:amount of (informatior?):(question information) be used to solve IT problems in polyno?ial:(polynomial) tir??:(time?)(time to question) The approach here (assur:?es):(assures and assumes) the information is given as a (in any-one):(in any or many-one) reduction to a sparse set. For Turing reductions, the infon?ation:information is given as a sparse oracle. A. ii'eyer: (two i have eye are) a has sho?rn:shown a sparse oracle for rP:NP is equivalent to the existence of polynomial size circuits to solve i;P:NP (cf. [13113). The recent work by `?arp:(have question) Karp, Lipton and Si-?ser: (Sipser) [KL] has shown if ip has polynomial size circuits, then the polynomial time hierarchy collapses p to Their result has a weaker hypothesis than Theorem 3.3. It is an important open problem to determine if polynomial size circuits for i?:i question implies P = NP. Ackno?lec'?ement.:Acknowledgement Period I ar?:am greatly indebted to Juris U. artmanis: j you are is you period art man is and Vivian Sewelson: Viv an sew el son for numerous discussions that lent insight into the methods developed in this paper. The u n i for?:(you and I for, or uniform) al0orithm :(algorithm) techniques of [KL] (suggested the me the d):(suggested me the 'theme d minus o' method) in Theorei_:(the or e i underscore:out) Theorem 3.3. I am grateful to Richard (1:arp:) (one:are p minus k:out) and Richard Lipton ?,ho:(question) who circulated an early version (AHU] Aho, A., ilopcroft, J., and UlThian, J., The Design and Analysis of Computer Al?oriti?s:Algorithms, Addison-Wesley (1974). (?1):(one question) Berman, L. and hartmanis, J., 11On(one hundred and ten n) Isomorphists and Density of NP and Otber Cot?lete:Other Complete Sets," SIAl! J. Cowut., 6 (1977) pp. 305-322. Also in Proceedings Eigth Annual ACH Syiap. on Theory of Cor? putin(?,:Computation (flay 1976). EB) Berman, P. 11 Relationship Between Density ard Deterministic Complex- ity of I:P-Complete Langua0es:Languages," Fifth International Colloquiu??:Colloquiuam on Auto- mata, Languages, and Pro0?ramming:Programming, Udine (July l97?), Springer Lecture I?tes in Comp. Sci. 62. (c) Cook, 8. A., 11 The Compleity of Theoret?:(The (or) et question) Proving Procedures," Proc. 3rd Annual ACL?l Syr:?osiul:i on Theory of Co?puting:Computing, (1971) pp. 151-153. ?F) Fortune, 5., 11 A Note on Sparse Complete Sets,11 Slk?? J. Comput., 8 (1979), pp. 431-433. E1111) llartmanis, J. and `iThhaney, 5. R., 1,On Census Comple?:ity:Complexity and Sparse- ness of NP-Complete Sets," Cornell University Technical Report TR 80-416 (April 1980). (K) i?'arp, R., "Reducibility Ai::Artificial Intelligence (on) g Combinatorial Problems, 11 in Complexity of Cor?uter:Computer Computations (R. I;. ?iller and J. W. Thatcher, eds.), Ple- nuni, New York (1972). KL) Karp, R. and Lipton, R., `1 Some Connections Detween Nonuniform and Uniform Cotiple'?ity:Co-triple Complexity Classes," Proc. 12th AC?'& Syp. on Theory of Comput- ing, (Hay 1980). (?iP) Patterson, M. and Heyer, A., ??`ith What Frequency are Apparently Intractable Problems Difficult?," H.I.T. Tech Report, Feb. 1979. From bearophileHUGS at lycos.com Fri Apr 2 11:41:28 2010 From: bearophileHUGS at lycos.com (Bearophile) Date: Fri, 2 Apr 2010 08:41:28 -0700 (PDT) Subject: Splitting a string References: Message-ID: <42432b8a-e670-45d4-abc2-1bc97cdac9d3@15g2000yqi.googlegroups.com> I don't know how fast this is (Python 2.x): >>> from itertools import groupby >>> t = 'si_pos_99_rep_1_0.ita' >>> tuple(int("".join(g)) if h else "".join(g) for h,g in groupby(t, str.isdigit)) ('si_pos_', 99, '_rep_', 1, '_', 0, '.ita') It doesn't work with unicode strings. Bye, bearophile From purple at colorme.com Fri Apr 2 11:47:57 2010 From: purple at colorme.com (purple) Date: Fri, 02 Apr 2010 10:47:57 -0500 Subject: plagiarism, no follow-ups please In-Reply-To: References: Message-ID: <81mhteFbmvU1@mid.individual.net> On 4/2/2010 7:36 AM, Chip Eastham wrote: > On Apr 2, 6:14 am, A Serious Moment > cross-posted > an OCR'd version of a 1980 paper > by SR Mahaney, mutilating the text > further to remove its attribution > and create the false impression of > authorship by the (im)poster. You report, we decide? Fox News has come to usenet? From steve at REMOVE-THIS-cybersource.com.au Fri Apr 2 12:00:47 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 02 Apr 2010 16:00:47 GMT Subject: (a==b) ? 'Yes' : 'No' References: <4bb5b326$0$8827$c3e8da3@news.astraweb.com> <19536991-2c54-42a5-8d22-f3c118a74a21@k17g2000yqb.googlegroups.com> Message-ID: <4bb614ae$0$8827$c3e8da3@news.astraweb.com> On Fri, 02 Apr 2010 07:05:49 -0700, Steve Howell wrote: >> How is the ternary operator "not really ternary, it's binary"? It >> requires three arguments, not two, which makes it ternary. In Python >> syntax: >> > Of course, I understand that the ternary operator has three arguments, > but it only has two possible outcomes. But the number of outcomes is not what the "binary" in binary operator refers to. It's the number of arguments. > You asked me to elaborate on the "Tyranny of Three." Let's say you have > three possible outcomes. > > In some languages you would write something like this: > > mark = (rolls == 1) && (pins == 10) ? 'strike' : > (rolls == 2) && (pins == 10) ? 'spare' : > 'normal' Not if you held a gun to my head *wink* > Many people consider the above very ugly, so they write it like so: [snip multiple alternative ways of choosing between three alternatives] All very interesting, but I don't see why you are singling out three alternatives as particularly difficult. Not all choices between three possible results are hard to code: choice = some_integer % 3 # returns 0, 1, or 2. and choosing between two results isn't necessarily simple either, e.g. the rules of protocol. Deciding which of two people outrank the other can be *very* complicated. Does a king outrank a pope? What about a president? Does a prince of some two-bit speck of dirt outrank a senator of a superpower? People have worked out (by which I mean, "made up") rules for all these and more, and they still can't always agree on who ranks who. International negotiations have floundered and collapsed because the parties couldn't agree which ambassador got the chair at the head of the table nearest the door... You are absolutely right to say that some problems don't have an elegant solution, but I think you're wrong to single out "three" as special. -- Steven From sccolbert at gmail.com Fri Apr 2 12:07:24 2010 From: sccolbert at gmail.com (Chris Colbert) Date: Fri, 2 Apr 2010 12:07:24 -0400 Subject: I'm not sure you understand In-Reply-To: References: Message-ID: On Fri, Apr 2, 2010 at 11:35 AM, A Serious Moment wrote: > Do you really not see the complete absurdity of posting an entire paper in this forum as plain text? Not only are you completely off-topic for this group, but the paper as you posted it is completely unreadable; regardless of whether it is plagiarized or not. -------------- next part -------------- An HTML attachment was scrubbed... URL: From no.email at please.post Fri Apr 2 12:08:42 2010 From: no.email at please.post (kj) Date: Fri, 2 Apr 2010 16:08:42 +0000 (UTC) Subject: C-style static variables in Python? References: Message-ID: In Steve Holden writes: >But the real problem is that the OP is insisting on using purely >procedural Python when the problem is screaming for an object-oriented >answer. My initial reaction to this comment was something like "What? switch from procedural to OO just to be able to do some one-time initialization of function-private data???" But then, again, since Python allows easy mixing of both programming styles, I suppose one could refactor this: def spam(x, y, z): try: mongo = spam.mongo except AttributeError: mongo = spam.mongo = heavy_lifting_at_runtime() return frobnicate(x, y, z, mongo) ham = spam(3, 4, 5) into this: class _Spam(object): @classmethod def _(cls, x, y, z): try: mongo = cls.mongo except AttributeError: mongo = cls.mongo = heavy_lifting_at_runtime() return frobnicate(x, y, z, mongo) ham = _Spam._(1, 2, 3) Is this really more natural or more readable? Hmmm. In any case, the first solution does rely on the fact that functions are objects, and therefore can have attributes, so even the "procedural" version relies on Python's OO model. Other responses advocated for global variables. I avoid them in general, and doubly so in Python, because I find Python's shenanigans with globals mystifying (this business of becoming silently local if assigned to); it's one rare instance in which Python out-Perls Perl. And yes, I know that the language includes ways to deal with this (with the global keyword, etc.) but I find the whole scheme is so much "cutting against the grain". Thanks for all the replies. There are a lot of good ideas there. I'm particular, I'm thankful for the pointers to PEP 3130 (initial reaction: maybe I should learn Dutch) and to functools.wraps, and for the code snippets. ~K From clp2 at rebertia.com Fri Apr 2 12:25:29 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Fri, 2 Apr 2010 09:25:29 -0700 Subject: PyGame migrating to JavaScript In-Reply-To: References: <4BB5A88B.2080906@digipen.edu> Message-ID: On Fri, Apr 2, 2010 at 1:23 AM, Xavier Ho wrote: > On Fri, Apr 2, 2010 at 6:19 PM, Gary Herron wrote: >> It's a joke -- see http://en.wikipedia.org/wiki/April_Fools%27_Da > > D'oh! > > Can't believe that got me. > > (It's already 2nd of April... you're not supposed to make that joke now! =p) He's in Australia. Fun with timezones! Cheers, Chris From jfernand57 at gmail.com Fri Apr 2 12:58:18 2010 From: jfernand57 at gmail.com (Jose Manuel) Date: Fri, 2 Apr 2010 09:58:18 -0700 (PDT) Subject: PyGame migrating to JavaScript References: Message-ID: On Apr 2, 3:19?am, Gary Herron wrote: > Xavier Ho wrote: > > ?Javascript in recent years has been getting better and better, and > > > ? ? ?now is a way better language than python. So to keep up with the > > ? ? ?times pygame has been rewritten for javascript. > > > *shudders* > > > Can someone convince me why that is a good idea at all? Any rationales? > > > Cheers, > > -Xav > > It's a joke -- seehttp://en.wikipedia.org/wiki/April_Fools%27_Day > > -- > Gary Herron, PhD. > Department of Computer Science > DigiPen Institute of Technology > (425) 895-4418 I read that on its web site and because I am not accustomed to that "April fools" I fell into the trap, I though ?I am just starting to studying Python now they come with javaScript again?. :) I have recently learned JavaScript and I did not like it to much. BTW within my culture the equivalent to such Aprils Fools is the Innocents? Days (on Dec 28th) which comes from the Christian History. From danmcleran at yahoo.com Fri Apr 2 13:09:54 2010 From: danmcleran at yahoo.com (danmcleran at yahoo.com) Date: Fri, 2 Apr 2010 10:09:54 -0700 (PDT) Subject: How to run python without python References: <1270164976.6418.4.camel@spencer-laptop> Message-ID: On Apr 1, 5:54?pm, Chris Rebert wrote: > On Thu, Apr 1, 2010 at 4:46 PM, Krister Svanlund > > wrote: > > On Fri, Apr 2, 2010 at 1:36 AM, Spencer wrote: > >> Is there a way to developing a script on linux and give it > >> to someone on microsoft, so that they could run it on microsoft > >> without installing python? > > > Short answer: No. > > Long answer: > No indeed. But if he were to have a Windows computer, he could > generate a standalone executable from a Python program using one of > the following tools: > py2exe:http://www.py2exe.org/ > PyInstaller:http://www.pyinstaller.org/ > > But one can't generate such a standalone executable for a different > operating system from that which one's computer runs. > > Cheers, > Chris > --http://blog.rebertia.com that's not entirely true. i just built a standalone exe for win 7 from my win xp machine. From danmcleran at yahoo.com Fri Apr 2 13:10:23 2010 From: danmcleran at yahoo.com (danmcleran at yahoo.com) Date: Fri, 2 Apr 2010 10:10:23 -0700 (PDT) Subject: How to run python without python References: <1270164976.6418.4.camel@spencer-laptop> Message-ID: On Apr 2, 11:09?am, "danmcle... at yahoo.com" wrote: > On Apr 1, 5:54?pm, Chris Rebert wrote: > > > > > On Thu, Apr 1, 2010 at 4:46 PM, Krister Svanlund > > > wrote: > > > On Fri, Apr 2, 2010 at 1:36 AM, Spencer wrote: > > >> Is there a way to developing a script on linux and give it > > >> to someone on microsoft, so that they could run it on microsoft > > >> without installing python? > > > > Short answer: No. > > > Long answer: > > No indeed. But if he were to have a Windows computer, he could > > generate a standalone executable from a Python program using one of > > the following tools: > > py2exe:http://www.py2exe.org/ > > PyInstaller:http://www.pyinstaller.org/ > > > But one can't generate such a standalone executable for a different > > operating system from that which one's computer runs. > > > Cheers, > > Chris > > --http://blog.rebertia.com > > that's not entirely true. i just built a standalone exe for win 7 from > my win xp machine. using py2exe. From clp2 at rebertia.com Fri Apr 2 13:23:08 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Fri, 2 Apr 2010 10:23:08 -0700 Subject: How to run python without python In-Reply-To: References: <1270164976.6418.4.camel@spencer-laptop> Message-ID: On Fri, Apr 2, 2010 at 10:09 AM, danmcleran at yahoo.com wrote: > On Apr 1, 5:54?pm, Chris Rebert wrote: >> On Thu, Apr 1, 2010 at 4:46 PM, Krister Svanlund >> wrote: >> > On Fri, Apr 2, 2010 at 1:36 AM, Spencer wrote: >> >> Is there a way to developing a script on linux and give it >> >> to someone on microsoft, so that they could run it on microsoft >> >> without installing python? >> one can't generate such a standalone executable for a different >> operating system from that which one's computer runs. > > that's not entirely true. i just built a standalone exe for win 7 from > my win xp machine. s/operating system/platform Good luck getting PyInstaller to output for Windows when being run on a *nix box. Cheers, Chris -- http://blog.rebertia.com From danmcleran at yahoo.com Fri Apr 2 13:25:37 2010 From: danmcleran at yahoo.com (danmcleran at yahoo.com) Date: Fri, 2 Apr 2010 10:25:37 -0700 (PDT) Subject: How to run python without python References: <1270164976.6418.4.camel@spencer-laptop> Message-ID: <488f5290-38f0-4f4e-8e75-f0271458b2b0@q16g2000yqq.googlegroups.com> On Apr 2, 11:23?am, Chris Rebert wrote: > On Fri, Apr 2, 2010 at 10:09 AM, danmcle... at yahoo.com > > wrote: > > On Apr 1, 5:54?pm, Chris Rebert wrote: > >> On Thu, Apr 1, 2010 at 4:46 PM, Krister Svanlund > >> wrote: > >> > On Fri, Apr 2, 2010 at 1:36 AM, Spencer wrote: > >> >> Is there a way to developing a script on linux and give it > >> >> to someone on microsoft, so that they could run it on microsoft > >> >> without installing python? > > >> one can't generate such a standalone executable for a different > >> operating system from that which one's computer runs. > > > that's not entirely true. i just built a standalone exe for win 7 from > > my win xp machine. > > s/operating system/platform > > Good luck getting PyInstaller to output for Windows when being run on > a *nix box. > > Cheers, > Chris > --http://blog.rebertia.com you think virtualbox could help? i wonder if one could run linux/ py2exe virtually on a win machine and get it working. From ptmcg at austin.rr.com Fri Apr 2 13:28:13 2010 From: ptmcg at austin.rr.com (Paul McGuire) Date: Fri, 2 Apr 2010 10:28:13 -0700 (PDT) Subject: C-style static variables in Python? References: Message-ID: On Apr 1, 5:34?pm, kj wrote: > When coding C I have often found static local variables useful for > doing once-only run-time initializations. ?For example: > Here is a decorator to make a function self-aware, giving it a "this" variable that points to itself, which you could then initialize from outside with static flags or values: from functools import wraps def self_aware(fn): @wraps(fn) def fn_(*args): return fn(*args) fn_.__globals__["this"] = fn_ return fn_ @self_aware def foo(): this.counter += 1 print this.counter foo.counter = 0 foo() foo() foo() Prints: 1 2 3 -- Paul From mwilson at the-wire.com Fri Apr 2 13:35:02 2010 From: mwilson at the-wire.com (Mel) Date: Fri, 02 Apr 2010 13:35:02 -0400 Subject: C-style static variables in Python? References: Message-ID: kj wrote: > In Steve Holden > writes: > >>But the real problem is that the OP is insisting on using purely >>procedural Python when the problem is screaming for an object-oriented >>answer. > > My initial reaction to this comment was something like "What? switch > from procedural to OO just to be able to do some one-time initialization > of function-private data???" Yeah, actually. If the subject had been "Python-style object attributes in C?" somebody might have suggested C static variables. An example I wrote lately volatile static int random_bit () { static unsigned short lfsr = 0xACE1u; // seeded LFSR // taps: 16 14 13 11; characteristic polynomial: x^16 + x^14 + x^13 + x^11 + 1 lfsr = (lfsr >> 1) ^ (-(lfsr & 1u) & 0xB400u); return lfsr & 1; } // random_bit (excuse is: this was written for cheap execution in an 8-bit processor.) This does OK -- but fails the instant I decide that my program needs more than one pseudo-random bit stream. Then I have the choice of writing several different random_bit functions, or extending random_bit to take a pointer to a seeded LFSR provided by the individual caller. Refactoring the Python function to a Python class, as you mention later, solves the static-access problem, but that solution is just as vulnerable to the need-more-than-just-the-one problem as my C function. Mel. From duncan.booth at invalid.invalid Fri Apr 2 13:53:18 2010 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 2 Apr 2010 17:53:18 GMT Subject: C-style static variables in Python? References: Message-ID: kj wrote: > I suppose one could refactor this: > > > def spam(x, y, z): > try: > mongo = spam.mongo > except AttributeError: > mongo = spam.mongo = heavy_lifting_at_runtime() > return frobnicate(x, y, z, mongo) > > ham = spam(3, 4, 5) > > > into this: > > > class _Spam(object): > @classmethod > def _(cls, x, y, z): > try: > mongo = cls.mongo > except AttributeError: > mongo = cls.mongo = heavy_lifting_at_runtime() > return frobnicate(x, y, z, mongo) > > ham = _Spam._(1, 2, 3) > > > > Is this really more natural or more readable? Hmmm. No, but that's because it is needlessly obfuscated. What's with the weird _ method? Why use a class method? Why not just create an instance? class Spam(object): mongo = None def __call__(self, x, y, z): if self.mongo is None: self.mongo = heavy_lifting_at_runtime() return frobnicate(x, y, z, self.mongo) spam = Spam() ham = spam(1, 2, 3) That's natural and readable. There's also another good reason why the class is better than the static variable: you can construct multiple different instances with different calls to 'heavy_lifting_at_runtime'. e.g. You could write a unit test where mongo is initialised to mock_heavy_lifting_at_runtime(). From saimapk81 at gmail.com Fri Apr 2 14:06:21 2010 From: saimapk81 at gmail.com (saima81) Date: Fri, 2 Apr 2010 11:06:21 -0700 (PDT) Subject: "JOBS IN ALABAMA" "ALABAMA JOBS" "ACCOUNTS JOBS IN ALABAMA" "FINANCE JOBS IN ALABAMA" ON http://jobsinalabama-usa.blogspot.com/ "USA JOBS" "JOBS IN USA" "JOBS IN USA STATES" "MEDICAL JOBS IN ALABAMA" Message-ID: <11859736-ed59-4f05-8af9-589fa7e413fe@j21g2000yqh.googlegroups.com> "JOBS IN ALABAMA" "ALABAMA JOBS" "ACCOUNTS JOBS IN ALABAMA" "FINANCE JOBS IN ALABAMA" ON http://jobsinalabama-usa.blogspot.com/ "USA JOBS" "JOBS IN USA" "JOBS IN USA STATES" "MEDICAL JOBS IN ALABAMA""JOBS IN ALABAMA" "ALABAMA JOBS" "ACCOUNTS JOBS IN ALABAMA" "FINANCE JOBS IN ALABAMA" ON http://jobsinalabama-usa.blogspot.com/ "USA JOBS" "JOBS IN USA" "JOBS IN USA STATES" "MEDICAL JOBS IN ALABAMA""JOBS IN ALABAMA" "ALABAMA JOBS" "ACCOUNTS JOBS IN ALABAMA" "FINANCE JOBS IN ALABAMA" ON http://jobsinalabama-usa.blogspot.com/ "USA JOBS" "JOBS IN USA" "JOBS IN USA STATES" "MEDICAL JOBS IN ALABAMA""JOBS IN ALABAMA" "ALABAMA JOBS" "ACCOUNTS JOBS IN ALABAMA" "FINANCE JOBS IN ALABAMA" ON http://jobsinalabama-usa.blogspot.com/ "USA JOBS" "JOBS IN USA" "JOBS IN USA STATES" "MEDICAL JOBS IN ALABAMA""JOBS IN ALABAMA" "ALABAMA JOBS" "ACCOUNTS JOBS IN ALABAMA" "FINANCE JOBS IN ALABAMA" ON http://jobsinalabama-usa.blogspot.com/ "USA JOBS" "JOBS IN USA" "JOBS IN USA STATES" "MEDICAL JOBS IN ALABAMA""JOBS IN ALABAMA" "ALABAMA JOBS" "ACCOUNTS JOBS IN ALABAMA" "FINANCE JOBS IN ALABAMA" ON http://jobsinalabama-usa.blogspot.com/ "USA JOBS" "JOBS IN USA" "JOBS IN USA STATES" "MEDICAL JOBS IN ALABAMA""JOBS IN ALABAMA" "ALABAMA JOBS" "ACCOUNTS JOBS IN ALABAMA" "FINANCE JOBS IN ALABAMA" ON http://jobsinalabama-usa.blogspot.com/ "USA JOBS" "JOBS IN USA" "JOBS IN USA STATES" "MEDICAL JOBS IN ALABAMA""JOBS IN ALABAMA" "ALABAMA JOBS" "ACCOUNTS JOBS IN ALABAMA" "FINANCE JOBS IN ALABAMA" ON http://jobsinalabama-usa.blogspot.com/ "USA JOBS" "JOBS IN USA" "JOBS IN USA STATES" "MEDICAL JOBS IN ALABAMA""JOBS IN ALABAMA" "ALABAMA JOBS" "ACCOUNTS JOBS IN ALABAMA" "FINANCE JOBS IN ALABAMA" ON http://jobsinalabama-usa.blogspot.com/ "USA JOBS" "JOBS IN USA" "JOBS IN USA STATES" "MEDICAL JOBS IN ALABAMA""JOBS IN ALABAMA" "ALABAMA JOBS" "ACCOUNTS JOBS IN ALABAMA" "FINANCE JOBS IN ALABAMA" ON http://jobsinalabama-usa.blogspot.com/ "USA JOBS" "JOBS IN USA" "JOBS IN USA STATES" "MEDICAL JOBS IN ALABAMA""JOBS IN ALABAMA" "ALABAMA JOBS" "ACCOUNTS JOBS IN ALABAMA" "FINANCE JOBS IN ALABAMA" ON http://jobsinalabama-usa.blogspot.com/ "USA JOBS" "JOBS IN USA" "JOBS IN USA STATES" "MEDICAL JOBS IN ALABAMA""JOBS IN ALABAMA" "ALABAMA JOBS" "ACCOUNTS JOBS IN ALABAMA" "FINANCE JOBS IN ALABAMA" ON http://jobsinalabama-usa.blogspot.com/ "USA JOBS" "JOBS IN USA" "JOBS IN USA STATES" "MEDICAL JOBS IN ALABAMA""JOBS IN ALABAMA" "ALABAMA JOBS" "ACCOUNTS JOBS IN ALABAMA" "FINANCE JOBS IN ALABAMA" ON http://jobsinalabama-usa.blogspot.com/ "USA JOBS" "JOBS IN USA" "JOBS IN USA STATES" "MEDICAL JOBS IN ALABAMA""JOBS IN ALABAMA" "ALABAMA JOBS" "ACCOUNTS JOBS IN ALABAMA" "FINANCE JOBS IN ALABAMA" ON http://jobsinalabama-usa.blogspot.com/ "USA JOBS" "JOBS IN USA" "JOBS IN USA STATES" "MEDICAL JOBS IN ALABAMA""JOBS IN ALABAMA" "ALABAMA JOBS" "ACCOUNTS JOBS IN ALABAMA" "FINANCE JOBS IN ALABAMA" ON http://jobsinalabama-usa.blogspot.com/ "USA JOBS" "JOBS IN USA" "JOBS IN USA STATES" "MEDICAL JOBS IN ALABAMA""JOBS IN ALABAMA" "ALABAMA JOBS" "ACCOUNTS JOBS IN ALABAMA" "FINANCE JOBS IN ALABAMA" ON http://jobsinalabama-usa.blogspot.com/ "USA JOBS" "JOBS IN USA" "JOBS IN USA STATES" "MEDICAL JOBS IN ALABAMA""JOBS IN ALABAMA" "ALABAMA JOBS" "ACCOUNTS JOBS IN ALABAMA" "FINANCE JOBS IN ALABAMA" ON http://jobsinalabama-usa.blogspot.com/ "USA JOBS" "JOBS IN USA" "JOBS IN USA STATES" "MEDICAL JOBS IN ALABAMA""JOBS IN ALABAMA" "ALABAMA JOBS" "ACCOUNTS JOBS IN ALABAMA" "FINANCE JOBS IN ALABAMA" ON http://jobsinalabama-usa.blogspot.com/ "USA JOBS" "JOBS IN USA" "JOBS IN USA STATES" "MEDICAL JOBS IN ALABAMA""JOBS IN ALABAMA" "ALABAMA JOBS" "ACCOUNTS JOBS IN ALABAMA" "FINANCE JOBS IN ALABAMA" ON http://jobsinalabama-usa.blogspot.com/ "USA JOBS" "JOBS IN USA" "JOBS IN USA STATES" "MEDICAL JOBS IN ALABAMA""JOBS IN ALABAMA" "ALABAMA JOBS" "ACCOUNTS JOBS IN ALABAMA" "FINANCE JOBS IN ALABAMA" ON http://jobsinalabama-usa.blogspot.com/ "USA JOBS" "JOBS IN USA" "JOBS IN USA STATES" "MEDICAL JOBS IN ALABAMA""JOBS IN ALABAMA" "ALABAMA JOBS" "ACCOUNTS JOBS IN ALABAMA" "FINANCE JOBS IN ALABAMA" ON http://jobsinalabama-usa.blogspot.com/ "USA JOBS" "JOBS IN USA" "JOBS IN USA STATES" "MEDICAL JOBS IN ALABAMA""JOBS IN ALABAMA" "ALABAMA JOBS" "ACCOUNTS JOBS IN ALABAMA" "FINANCE JOBS IN ALABAMA" ON http://jobsinalabama-usa.blogspot.com/ "USA JOBS" "JOBS IN USA" "JOBS IN USA STATES" "MEDICAL JOBS IN ALABAMA""JOBS IN ALABAMA" "ALABAMA JOBS" "ACCOUNTS JOBS IN ALABAMA" "FINANCE JOBS IN ALABAMA" ON http://jobsinalabama-usa.blogspot.com/ "USA JOBS" "JOBS IN USA" "JOBS IN USA STATES" "MEDICAL JOBS IN ALABAMA""JOBS IN ALABAMA" "ALABAMA JOBS" "ACCOUNTS JOBS IN ALABAMA" "FINANCE JOBS IN ALABAMA" ON http://jobsinalabama-usa.blogspot.com/ "USA JOBS" "JOBS IN USA" "JOBS IN USA STATES" "MEDICAL JOBS IN ALABAMA""JOBS IN ALABAMA" "ALABAMA JOBS" "ACCOUNTS JOBS IN ALABAMA" "FINANCE JOBS IN ALABAMA" ON http://jobsinalabama-usa.blogspot.com/ "USA JOBS" "JOBS IN USA" "JOBS IN USA STATES" "MEDICAL JOBS IN ALABAMA""JOBS IN ALABAMA" "ALABAMA JOBS" "ACCOUNTS JOBS IN ALABAMA" "FINANCE JOBS IN ALABAMA" ON http://jobsinalabama-usa.blogspot.com/ "USA JOBS" "JOBS IN USA" "JOBS IN USA STATES" "MEDICAL JOBS IN ALABAMA""JOBS IN ALABAMA" "ALABAMA JOBS" "ACCOUNTS JOBS IN ALABAMA" "FINANCE JOBS IN ALABAMA" ON http://jobsinalabama-usa.blogspot.com/ "USA JOBS" "JOBS IN USA" "JOBS IN USA STATES" "MEDICAL JOBS IN ALABAMA""JOBS IN ALABAMA" "ALABAMA JOBS" "ACCOUNTS JOBS IN ALABAMA" "FINANCE JOBS IN ALABAMA" ON http://jobsinalabama-usa.blogspot.com/ "USA JOBS" "JOBS IN USA" "JOBS IN USA STATES" "MEDICAL JOBS IN ALABAMA""JOBS IN ALABAMA" "ALABAMA JOBS" "ACCOUNTS JOBS IN ALABAMA" "FINANCE JOBS IN ALABAMA" ON http://jobsinalabama-usa.blogspot.com/ "USA JOBS" "JOBS IN USA" "JOBS IN USA STATES" "MEDICAL JOBS IN ALABAMA""JOBS IN ALABAMA" "ALABAMA JOBS" "ACCOUNTS JOBS IN ALABAMA" "FINANCE JOBS IN ALABAMA" ON http://jobsinalabama-usa.blogspot.com/ "USA JOBS" "JOBS IN USA" "JOBS IN USA STATES" "MEDICAL JOBS IN ALABAMA""JOBS IN ALABAMA" "ALABAMA JOBS" "ACCOUNTS JOBS IN ALABAMA" "FINANCE JOBS IN ALABAMA" ON http://jobsinalabama-usa.blogspot.com/ "USA JOBS" "JOBS IN USA" "JOBS IN USA STATES" "MEDICAL JOBS IN ALABAMA""JOBS IN ALABAMA" "ALABAMA JOBS" "ACCOUNTS JOBS IN ALABAMA" "FINANCE JOBS IN ALABAMA" ON http://jobsinalabama-usa.blogspot.com/ "USA JOBS" "JOBS IN USA" "JOBS IN USA STATES" "MEDICAL JOBS IN ALABAMA""JOBS IN ALABAMA" "ALABAMA JOBS" "ACCOUNTS JOBS IN ALABAMA" "FINANCE JOBS IN ALABAMA" ON http://jobsinalabama-usa.blogspot.com/ "USA JOBS" "JOBS IN USA" "JOBS IN USA STATES" "MEDICAL JOBS IN ALABAMA""JOBS IN ALABAMA" "ALABAMA JOBS" "ACCOUNTS JOBS IN ALABAMA" "FINANCE JOBS IN ALABAMA" ON http://jobsinalabama-usa.blogspot.com/ "USA JOBS" "JOBS IN USA" "JOBS IN USA STATES" "MEDICAL JOBS IN ALABAMA""JOBS IN ALABAMA" "ALABAMA JOBS" "ACCOUNTS JOBS IN ALABAMA" "FINANCE JOBS IN ALABAMA" ON http://jobsinalabama-usa.blogspot.com/ "USA JOBS" "JOBS IN USA" "JOBS IN USA STATES" "MEDICAL JOBS IN ALABAMA""JOBS IN ALABAMA" "ALABAMA JOBS" "ACCOUNTS JOBS IN ALABAMA" "FINANCE JOBS IN ALABAMA" ON http://jobsinalabama-usa.blogspot.com/ "USA JOBS" "JOBS IN USA" "JOBS IN USA STATES" "MEDICAL JOBS IN ALABAMA""JOBS IN ALABAMA" "ALABAMA JOBS" "ACCOUNTS JOBS IN ALABAMA" "FINANCE JOBS IN ALABAMA" ON http://jobsinalabama-usa.blogspot.com/ "USA JOBS" "JOBS IN USA" "JOBS IN USA STATES" "MEDICAL JOBS IN ALABAMA""JOBS IN ALABAMA" "ALABAMA JOBS" "ACCOUNTS JOBS IN ALABAMA" "FINANCE JOBS IN ALABAMA" ON http://jobsinalabama-usa.blogspot.com/ "USA JOBS" "JOBS IN USA" "JOBS IN USA STATES" "MEDICAL JOBS IN ALABAMA""JOBS IN ALABAMA" "ALABAMA JOBS" "ACCOUNTS JOBS IN ALABAMA" "FINANCE JOBS IN ALABAMA" ON http://jobsinalabama-usa.blogspot.com/ "USA JOBS" "JOBS IN USA" "JOBS IN USA STATES" "MEDICAL JOBS IN ALABAMA""JOBS IN ALABAMA" "ALABAMA JOBS" "ACCOUNTS JOBS IN ALABAMA" "FINANCE JOBS IN ALABAMA" ON http://jobsinalabama-usa.blogspot.com/ "USA JOBS" "JOBS IN USA" "JOBS IN USA STATES" "MEDICAL JOBS IN ALABAMA""JOBS IN ALABAMA" "ALABAMA JOBS" "ACCOUNTS JOBS IN ALABAMA" "FINANCE JOBS IN ALABAMA" ON http://jobsinalabama-usa.blogspot.com/ "USA JOBS" "JOBS IN USA" "JOBS IN USA STATES" "MEDICAL JOBS IN ALABAMA""JOBS IN ALABAMA" "ALABAMA JOBS" "ACCOUNTS JOBS IN ALABAMA" "FINANCE JOBS IN ALABAMA" ON http://jobsinalabama-usa.blogspot.com/ "USA JOBS" "JOBS IN USA" "JOBS IN USA STATES" "MEDICAL JOBS IN ALABAMA""JOBS IN ALABAMA" "ALABAMA JOBS" "ACCOUNTS JOBS IN ALABAMA" "FINANCE JOBS IN ALABAMA" ON http://jobsinalabama-usa.blogspot.com/ "USA JOBS" "JOBS IN USA" "JOBS IN USA STATES" "MEDICAL JOBS IN ALABAMA"V From tavares at fe.up.pt Fri Apr 2 14:18:43 2010 From: tavares at fe.up.pt (tavares at fe.up.pt) Date: Fri, 2 Apr 2010 11:18:43 -0700 (PDT) Subject: =?windows-1252?Q?6th_Int=2E_Conf=2E_on_Technology_and_Medical_Sciences_?= =?windows-1252?Q?=96_Announce_=26_Call_for_Papers?= Message-ID: Dear Colleague, We are pleased to announce the TMSi2010 ? 6th International Conference on Technology and Medical Sciences (www.fe.up.pt/tmsi2010) that will be held at the Faculty of Engineering of University of Porto, Porto, Portugal, on October 21-23, 2010. Possible Topics (but not limited to) - Analysis and diagnosis; - Applications in medicine; - Applications in veterinary; - Artificial organs; - Bioengineering; - Biofluid; - Biomedical devices Computational methods; - Computer aided diagnosis; - Computer assisted surgery; - Imaging; - Implantology; - Medical robotics; - Minimally invasive devices and techniques; - Prosthesis and orthosis; - Rehabilitation; - Simulation; - Software development; - Technical aids; - Telemedicine; - Virtual reality. Invited Lecturers - Paulo Jorge B?rtolo, Polytechnic Institute of Leiria, Leiria, Portugal - Jose M. Garc?a Aznar, University of Zaragoza, Spain - Todd Pataky, Shinshu University, Japan - Paola Lecca, The Microsoft Research - University of Trento, Italy (to be confirmed) Publications The proceedings book will be published by the Taylor & Francis Group. The organizers will encourage the submission of extended versions of the accepted papers to related International Journals; in particular for special issues dedicated to the conference. One possibility already confirmed is the International Journal for Computational Vision and Biomechanics (IJCV&B). Important dates - Submission of abstracts: May 15, 2010 - Authors notification: May 30, 2010 - Final Papers: July 15, 2010 We look forward to seeing you in Porto in October. Kind regards, Renato Natal Jorge, University of Porto, Portugal (rnatal at fe.up.pt) Jo?o Manuel R. S. Tavares, University of Porto, Portugal (tavares at fe.up.pt) Marcos Pinotti Barbosa, Federal University of Minas Geral, Brazil (pinotti at ufmg.br) Alan Slade, University of Dundee, Scotland (a.p.slade at dundee.ac.uk) (conference organizers) PS. For further details please visit the conference website at: www.fe.up.pt/tmsi2010 From ethan at stoneleaf.us Fri Apr 2 14:21:10 2010 From: ethan at stoneleaf.us (Ethan Furman) Date: Fri, 02 Apr 2010 11:21:10 -0700 Subject: C-style static variables in Python? In-Reply-To: References: Message-ID: <4BB63596.3040306@stoneleaf.us> kj wrote: > > class _Spam(object): > @classmethod > def _(cls, x, y, z): > try: > mongo = cls.mongo > except AttributeError: > mongo = cls.mongo = heavy_lifting_at_runtime() > return frobnicate(x, y, z, mongo) > > ham = _Spam._(1, 2, 3) > > > > Is this really more natural or more readable? Hmmm. For this type of situation, my preference would be: class spam(object): def __call__(self, x, y, z): try: mongo = self.mongo except AttributeError: mongo = self.mongo = heavy_lifting_at_runtime() return frobnicate(x, y, z, mongo) spam = spam() No extra objects, out-of-place underscores, etc. ~Ethan~ From ethan at stoneleaf.us Fri Apr 2 14:35:02 2010 From: ethan at stoneleaf.us (Ethan Furman) Date: Fri, 02 Apr 2010 11:35:02 -0700 Subject: subclass of object In-Reply-To: References: Message-ID: <4BB638D6.5070901@stoneleaf.us> Steve Holden wrote: > Alf P. Steinbach wrote: >> * Jason Friedman: >>> Hi, what is the difference between: >>> >>> def MyClass(object): >>> pass >>> >>> and >>> >>> def MyClass(): >>> pass >> If you really meant 'def', then the first is a routine taking one >> argument, and the second is a routine of no arguments. >> >> If you meant 'class' instead of 'def', then it depends on the Python >> version. >> >> In Py2 the first then defines a new-style class, while the second >> defines an old-style class. E.g. you can see some difference by checking >> with 'isinstance'. In Py3 there's no difference. >> > Interesting. I actually read "class" for "def" and replied accordingly. Funny, so did I. I'm sure it had something to do with the subject line. ;) ~Ethan~ From pmaupin at gmail.com Fri Apr 2 14:39:33 2010 From: pmaupin at gmail.com (Patrick Maupin) Date: Fri, 2 Apr 2010 11:39:33 -0700 (PDT) Subject: C-style static variables in Python? References: Message-ID: <98947d50-6352-466b-aae6-35e7b4c8c5af@33g2000yqj.googlegroups.com> On Apr 2, 1:21?pm, Ethan Furman wrote: > For this type of situation, my preference would be: > > class spam(object): > ? ? ?def __call__(self, x, y, z): > ? ? ? ? ?try: > ? ? ? ? ? ? ?mongo = self.mongo > ? ? ? ? ?except AttributeError: > ? ? ? ? ? ? ?mongo = self.mongo = heavy_lifting_at_runtime() > ? ? ? ? ?return frobnicate(x, y, z, mongo) > spam = spam() > > No extra objects, out-of-place underscores, etc. > > ~Ethan~ Well, I'm not a big fan of unnecessary try/except, so I would at least change it to: class spam(object): def __getattr__(self, name): if name != 'mongo': raise AttributeError self.mongo = heavy_lifting_at_runtime() return self.mongo def __call__(self, x, y, z): return frobnicate(x, y, z, self.mongo) spam = spam() Regards, Pat From steve at REMOVE-THIS-cybersource.com.au Fri Apr 2 14:40:28 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 02 Apr 2010 18:40:28 GMT Subject: C-style static variables in Python? References: Message-ID: <4bb63a1c$0$8827$c3e8da3@news.astraweb.com> On Fri, 02 Apr 2010 16:08:42 +0000, kj wrote: > Other responses advocated for global variables. I avoid them in > general, In general this is wise, but remember that because Python globals are not globally global, but local to a single module, they're safer than globals in other languages. Still, it's better to avoid them when possible. > and doubly so in Python, because I find Python's shenanigans > with globals mystifying (this business of becoming silently local if > assigned to); Globals don't become local when assigned to. You can shadow a global with a local of the same name, but the global remains untouched: >>> myglobal = 42 >>> def test(): ... myglobal = 0 # shadow the global with a new local ... >>> test() >>> myglobal 42 I find this behaviour perfectly natural, and desirable: it means I can assign to locals without worrying whether or not I'm about to stomp all over a global and destroy it. The alternative behaviour would be disastrous: >>> def f(x): return x+1 ... >>> def test(): ... f = 'spam' ... >>> test() >>> f(2) # this doesn't happen Traceback (most recent call last): File "", line 1, in TypeError: 'str' object is not callable -- Steven From steve at holdenweb.com Fri Apr 2 14:57:02 2010 From: steve at holdenweb.com (Steve Holden) Date: Fri, 02 Apr 2010 14:57:02 -0400 Subject: plagiarism, no follow-ups please In-Reply-To: <81mhteFbmvU1@mid.individual.net> References: <81mhteFbmvU1@mid.individual.net> Message-ID: purple wrote: > On 4/2/2010 7:36 AM, Chip Eastham wrote: >> On Apr 2, 6:14 am, A Serious Moment >> cross-posted >> an OCR'd version of a 1980 paper >> by SR Mahaney, mutilating the text >> further to remove its attribution >> and create the false impression of >> authorship by the (im)poster. > > > You report, we decide? Fox News has come to usenet? As always, please do not feed the trolls. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 See PyCon Talks from Atlanta 2010 http://pycon.blip.tv/ Holden Web LLC http://www.holdenweb.com/ UPCOMING EVENTS: http://holdenweb.eventbrite.com/ From john at castleamber.com Fri Apr 2 15:24:51 2010 From: john at castleamber.com (John Bokma) Date: Fri, 02 Apr 2010 13:24:51 -0600 Subject: How to run python without python References: <1270164976.6418.4.camel@spencer-laptop> <488f5290-38f0-4f4e-8e75-f0271458b2b0@q16g2000yqq.googlegroups.com> Message-ID: <87wrwpodx8.fsf@castleamber.com> "danmcleran at yahoo.com" writes: > On Apr 2, 11:23?am, Chris Rebert wrote: >> On Fri, Apr 2, 2010 at 10:09 AM, danmcle... at yahoo.com >> >> wrote: >> > On Apr 1, 5:54?pm, Chris Rebert wrote: >> >> On Thu, Apr 1, 2010 at 4:46 PM, Krister Svanlund >> >> wrote: >> >> > On Fri, Apr 2, 2010 at 1:36 AM, Spencer wrote: >> >> >> Is there a way to developing a script on linux and give it >> >> >> to someone on microsoft, so that they could run it on microsoft >> >> >> without installing python? >> >> >> one can't generate such a standalone executable for a different >> >> operating system from that which one's computer runs. >> >> > that's not entirely true. i just built a standalone exe for win 7 from >> > my win xp machine. >> >> s/operating system/platform >> >> Good luck getting PyInstaller to output for Windows when being run on >> a *nix box. > > you think virtualbox could help? i wonder if one could run linux/ > py2exe virtually on a win machine and get it working. Of course that works, a virtual windows machine is just a windows machine ;-). Also that you can't do a "cross compilation" sounds to me more a limitation of the tool than a true impossibility. -- John Bokma j3b Hacking & Hiking in Mexico - http://johnbokma.com/ http://castleamber.com/ - Perl & Python Development From pmaupin at gmail.com Fri Apr 2 15:34:53 2010 From: pmaupin at gmail.com (Patrick Maupin) Date: Fri, 2 Apr 2010 12:34:53 -0700 (PDT) Subject: off topic but please forgive me me and answer References: <4bb505c5$0$1133$4fafbaef@reader3.news.tin.it> <20100402214110.00a63457@geekmail.INVALID> Message-ID: On Apr 2, 2:41?pm, Andreas Waldenburger wrote: > While everyone else is mocking you: Can you please elaborate on why you > want to know and what kind of problem you're trying to solve with this? > Also, don't you think you should have picked a maths forum for this > kind of question? Methinks the OP is fluent in the way of choosing newsgroups. According to google, he has posted 6855 messages in 213 groups. http://groups.google.com/groups/profile?enc_user=ul3SQhIAAAAYmLD0Oj5Yxp-liP3Vw9uApbyajUBv9M9XLUB2gqkZmQ And I can't speak for anybody else, but I just assumed it was an April Fool's question. I meant to be laughing with the OP, not at him, so sorry if I misunderstood. Regards, Pat From mensanator at aol.com Fri Apr 2 15:35:55 2010 From: mensanator at aol.com (Mensanator) Date: Fri, 2 Apr 2010 12:35:55 -0700 (PDT) Subject: off topic but please forgive me me and answer References: <4bb505c5$0$1133$4fafbaef@reader3.news.tin.it> <32d91d4f-616f-404b-afbb-3b97dc380a67@e7g2000yqf.googlegroups.com> <4bb55a18$0$8827$c3e8da3@news.astraweb.com> Message-ID: <6fe000ff-92a3-427f-9dd2-594005ef366e@z3g2000yqz.googlegroups.com> On Apr 1, 9:44?pm, Steven D'Aprano wrote: > On Thu, 01 Apr 2010 19:49:43 -0500, Tim Chase wrote: > > David Robinow wrote: > >> $ python -c "print 1/2 * 1/2" > >> 0 > > >> ?But that's not what I learned in grade school. > >> (Maybe I should upgrade to 3.1?) > > > That's because you need to promote one of them to a float so you get a > > floating-point result: > > > ? ?>>> 1/2 * 1/2 > > ? ?0 > > ? ?>>> 1/2 * 1/2.0 > > ? ?0.0 > > > Oh...wait ;-) > > Tim, I'm sure you know the answer to this, but for the benefit of the > Original Poster, the problem is that you need to promote *both* divisions > to floating point. Otherwise one of them will give int 0, which gives 0.0 > when multiplied by 0.5. > > >>> 1.0/2 * 1/2.0 > > 0.25 > > If you want an exact result when multiplying arbitrary fractions, you > need to avoid floats and decimals and use Fractions: > > >>> Fraction(1, 2)**2 > > Fraction(1, 4) Where do you get that from? > > -- > Steven- Hide quoted text - > > - Show quoted text - From nagle at animats.com Fri Apr 2 15:36:44 2010 From: nagle at animats.com (John Nagle) Date: Fri, 02 Apr 2010 12:36:44 -0700 Subject: folks, what's wrong with this? In-Reply-To: <4bb5ae61$0$10227$426a34cc@news.free.fr> References: <4bb5ae61$0$10227$426a34cc@news.free.fr> Message-ID: <4bb64279$0$1661$742ec2ed@news.sonic.net> Bruno Desthuilliers wrote: > And now for the most import point: __getattr__ is only called as a > *last* resort. That is, after the attribute lookup mechanism will have > tried *and failed* to find the name in the instance's __dict__. In general, "getattr" is for unusual situations only. If you want to store objects by name, use an ordinary dict. Using "getattr" means you have to worry about clashes with built-in names, the limitations of attribute syntax (BeautifulSoup can be crashed by this), and some Unicode issues with attribute names. So don't do that. John Nagle From ethan at stoneleaf.us Fri Apr 2 15:38:56 2010 From: ethan at stoneleaf.us (Ethan Furman) Date: Fri, 02 Apr 2010 12:38:56 -0700 Subject: C-style static variables in Python? In-Reply-To: <98947d50-6352-466b-aae6-35e7b4c8c5af@33g2000yqj.googlegroups.com> References: <98947d50-6352-466b-aae6-35e7b4c8c5af@33g2000yqj.googlegroups.com> Message-ID: <4BB647D0.5080408@stoneleaf.us> Patrick Maupin wrote: > On Apr 2, 1:21 pm, Ethan Furman wrote: >> For this type of situation, my preference would be: >> >> class spam(object): >> def __call__(self, x, y, z): >> try: >> mongo = self.mongo >> except AttributeError: >> mongo = self.mongo = heavy_lifting_at_runtime() >> return frobnicate(x, y, z, mongo) >> spam = spam() >> >> No extra objects, out-of-place underscores, etc. >> >> ~Ethan~ > > Well, I'm not a big fan of unnecessary try/except, so I would at least > change it to: > > class spam(object): > def __getattr__(self, name): > if name != 'mongo': > raise AttributeError > self.mongo = heavy_lifting_at_runtime() > return self.mongo > def __call__(self, x, y, z): > return frobnicate(x, y, z, self.mongo) > spam = spam() > > Regards, > Pat Sounds like a personal preference issue, rather than a necessary / unnecessary issue -- after all, if you call that function a thousand times, only once is mongo not defined... clearly the exception. ;) ~Ethan~ From pmaupin at gmail.com Fri Apr 2 15:39:16 2010 From: pmaupin at gmail.com (Patrick Maupin) Date: Fri, 2 Apr 2010 12:39:16 -0700 (PDT) Subject: C-style static variables in Python? References: <98947d50-6352-466b-aae6-35e7b4c8c5af@33g2000yqj.googlegroups.com> Message-ID: <89ef884c-eb30-4ca8-a292-d9bc17e8cd4f@z4g2000yqa.googlegroups.com> On Apr 2, 2:38?pm, Ethan Furman wrote: > Patrick Maupin wrote: > > On Apr 2, 1:21 pm, Ethan Furman wrote: > >> For this type of situation, my preference would be: > > >> class spam(object): > >> ? ? ?def __call__(self, x, y, z): > >> ? ? ? ? ?try: > >> ? ? ? ? ? ? ?mongo = self.mongo > >> ? ? ? ? ?except AttributeError: > >> ? ? ? ? ? ? ?mongo = self.mongo = heavy_lifting_at_runtime() > >> ? ? ? ? ?return frobnicate(x, y, z, mongo) > >> spam = spam() > > >> No extra objects, out-of-place underscores, etc. > > >> ~Ethan~ > > > Well, I'm not a big fan of unnecessary try/except, so I would at least > > change it to: > > > class spam(object): > > ? ? ?def __getattr__(self, name): > > ? ? ? ? ?if name != 'mongo': > > ? ? ? ? ? ? ?raise AttributeError > > ? ? ? ? ?self.mongo = heavy_lifting_at_runtime() > > ? ? ? ? ?return self.mongo > > ? ? ?def __call__(self, x, y, z): > > ? ? ? ? ?return frobnicate(x, y, z, self.mongo) > > spam = spam() > > > Regards, > > Pat > > Sounds like a personal preference issue, rather than a necessary / > unnecessary issue -- after all, if you call that function a thousand > times, only once is mongo not defined... clearly the exception. ?;) > > ~Ethan~ Well, I think the whole discussion has basically been about personal preference. OTOH, but if you call the function a few million times, you might find the cost of try/except to be something that you would rather not incur -- it might become a performance issue rather than a personal choice issue. On the other OTHER hand, if you call the function a few billion times, performance weighs more heavily in favor of the closure approach rather than the object approach, since local variable lookup is so much cheaper. Regards, Pat From usenot at geekmail.INVALID Fri Apr 2 15:41:10 2010 From: usenot at geekmail.INVALID (Andreas Waldenburger) Date: Fri, 2 Apr 2010 21:41:10 +0200 Subject: off topic but please forgive me me and answer References: <4bb505c5$0$1133$4fafbaef@reader3.news.tin.it> Message-ID: <20100402214110.00a63457@geekmail.INVALID> On Thu, 01 Apr 2010 22:44:51 +0200 superpollo wrote: > how much is one half times one half? While everyone else is mocking you: Can you please elaborate on why you want to know and what kind of problem you're trying to solve with this? Also, don't you think you should have picked a maths forum for this kind of question? Meanwhile: http://en.wikipedia.org/wiki/Fractions#Multiplying_by_a_fraction And in Italian: http://it.wikipedia.org/wiki/Frazione_(matematica)#Moltiplicazione_e_division /W (Yes, I have nothing to do right now.) -- INVALID? DE! From theller at ctypes.org Fri Apr 2 16:06:52 2010 From: theller at ctypes.org (Thomas Heller) Date: Fri, 02 Apr 2010 22:06:52 +0200 Subject: Splitting a string In-Reply-To: <450895af-d8ec-4312-a31e-569e39aaa319@w17g2000yqj.googlegroups.com> References: <450895af-d8ec-4312-a31e-569e39aaa319@w17g2000yqj.googlegroups.com> Message-ID: Patrick Maupin schrieb: > On Apr 2, 6:24 am, Peter Otten <__pete... at web.de> wrote: >> Thomas Heller wrote: >> > Maybe I'm just lazy, but what is the fastest way to convert a string >> > into a tuple containing character sequences and integer numbers, like >> > this: >> >> > 'si_pos_99_rep_1_0.ita' -> ('si_pos_', 99, '_rep_', 1, '_', 0, '.ita') >> >>> parts = re.compile("([+-]?\d+)").split('si_pos_99_rep_1_0.ita') >> >>> parts[1::2] = map(int, parts[1::2]) >> >>> parts >> >> ['si_pos_', 99, '_rep_', 1, '_', 0, '.ita'] >> >> Peter > > You beat me to it. re.split() seems underappreciated for some > reason. When I first started using it (even though it was faster for > the tasks I was using it for than other things) I was really annoyed > at the empty strings it was providing between matches. It is only > within the past couple of years that I have come to appreciate the > elegant solutions that those empty strings allow for. In short, > re.split() is by far the fastest and most elegant way to use the re > module for a large class of problems. > > So, the only thing I have to add to this solution is that, for this > particular regular expression, if the source string starts with or > ends with digits, you will get empty strings at the beginning or end > of the resultant list, so if this is a problem, you will want to check > for and discard those. Thanks to all for these code snippets. Peter's solution is the winner - most elegant and also the fastest. With an additional list comprehension to remove the possible empty strings at the start and at the end I get 16 us. Interesting is that Xavier's solution (which is similar to some code that I wrote myself) isn't so much slower; it get timings of around 22 us. -- Thanks, Thomas From vthakr.safe at gmail.com Fri Apr 2 16:08:00 2010 From: vthakr.safe at gmail.com (Christopher Roach) Date: Fri, 2 Apr 2010 13:08:00 -0700 (PDT) Subject: Is it possible to store data in a Python file in a way similar to Ruby's __END__ section? Message-ID: <1651230b-7f02-4fce-a3cd-0a2687af0ff8@n34g2000yqb.googlegroups.com> I have a script that I am working on to process a bunch of data. A good portion of the Tk-based GUI is driven by a large set of YAML data and I'd love to store that data inside of the script so that I can send just a single file to my colleague. Ruby has a mechanism for doing this whereby I can load the data by doing a YAML.load(DATA) which loads everything in the file after the __END__ keyword (for a better explanation of this see http://bit.ly/V9w8m). I was wondering if anyone knew of a way to do something similar in Python? I guess it's probably a good idea to point out that I am not trying to start a flame war or compare Ruby to Python in any way, shape, or form. I'm simply wondering if there is something in Python that is roughly equivalent to a feature that I find useful in Ruby. If so, I'll use it, if not, it won't make me change my mind about using Python for my implementation, I'm quite happy with my choice, with or without this feature. Thanks in advance for any help you all can offer. Christopher From no.email at please.post Fri Apr 2 16:12:59 2010 From: no.email at please.post (kj) Date: Fri, 2 Apr 2010 20:12:59 +0000 (UTC) Subject: (a==b) ? 'Yes' : 'No' References: <4bb22b39$0$1638$742ec2ed@news.sonic.net> Message-ID: In Steve Holden writes: >John Nagle wrote: >> Chris Rebert wrote: >>> On Tue, Mar 30, 2010 at 8:40 AM, gentlestone >>> wrote: >>>> Hi, how can I write the popular C/JAVA syntax in Python? >>>> >>>> Java example: >>>> return (a==b) ? 'Yes' : 'No' >>>> >>>> My first idea is: >>>> return ('No','Yes')[bool(a==b)] >>>> >>>> Is there a more elegant/common python expression for this? >>> >>> Yes, Python has ternary operator-like syntax: >>> return ('Yes' if a==b else 'No') >>> >>> Note that this requires a recent version of Python. >> >> Who let the dogs in? That's awful syntax. >> >Yes, that's deliberately awful syntax. Guido designed it that way to >ensure that people didn't aver-use it, thereby reducing the readability >of Python applications. Is that for real??? It's the QWERTY rationale all over again. Swell. "Let's preserve readability by making the syntax so ugly that people won't use it."??? That's just perverse. (It would have been more reassuring if the reason had been simply that Guido has an inexplicable dislike of ternary expressions just like one may have an inexplicable dislike of Broadway musicals.) First, I don't understand why ternary expressions are inherently hard to read, and therefore must be discouraged in the name of overall code readability. Sure, one can write impenetrable ternary expressions, but one can write impenetrable binary expressions or impenetrable anything else, even in Python. That the expression is ternary has nothing to do with it. Second, sticking the test between the two alternatives goes against a vast tradition in programming languages. This tradition inevitably fosters habits and expectations when reading code, so going against it automatically makes code less readable to all who were educated in that tradition. Consider, for example, the readability of the following if statement in some hypothetical language: begin: # this branch will be executed if test() (see below) evaluates # to true x = y + z a = b * x + c i = j - k p = log(q) if test() else: x = -(y + z) a = b * x + 2 * c i = j + k p = -log(q) If you find this hard to read (I do), the quetion is "why?". For me it's because, maybe through years of reading code, I've developed a habit that says: when you run into a fork in the logic, first understand what the decision hinges on. Therefore, my brain will start hunting for that test, and it sucks to have to find it buried somewhere in the middle. (Sure, one could justify this horrible syntax with an argument reminiscent of the one you gave for "A if X else B". It goes like this: long blocks of code should be avoided in the name of readability; this syntax discourages long blocks of code because one doesn't want to skip too far ahead to find that test. Ergo the end result is improved readability. That's just nuts.) Anyway, I don't know of any other language that puts the test between the alternatives. No doubt there's one out there, with emphasis on "out there"... ~K From colo.avs96 at gmail.com Fri Apr 2 16:14:32 2010 From: colo.avs96 at gmail.com (Booter) Date: Fri, 2 Apr 2010 13:14:32 -0700 (PDT) Subject: Getting Local MAC Address Message-ID: Hello all, I am new to python ans was wondering if there was a way to get the mac address from the local NIC? Thanks for your help. Gerad From john at castleamber.com Fri Apr 2 16:20:06 2010 From: john at castleamber.com (John Bokma) Date: Fri, 02 Apr 2010 14:20:06 -0600 Subject: (a==b) ? 'Yes' : 'No' References: <4bb22b39$0$1638$742ec2ed@news.sonic.net> Message-ID: <87ljd5obd5.fsf@castleamber.com> kj writes: > Anyway, I don't know of any other language that puts the test > between the alternatives. No doubt there's one out there, with > emphasis on "out there"... Perl has something that has IMO somewhat the same problem: print "Hello, world!\n" if $some_condition; I prefer most of the time: $some_condition and print "Hello, world!\n"; Or even: $some_condition and print "Hello, world!\n"; Moreover, instead of: $x = 'some value' unless defined $x; I prefer defined $x or $x = 'some value'; I read the latter as: $x must be defined, otherwise some value must be assigned to it, like a precondition. YMMV, -- John Bokma j3b Hacking & Hiking in Mexico - http://johnbokma.com/ http://castleamber.com/ - Perl & Python Development From ethan at stoneleaf.us Fri Apr 2 16:33:48 2010 From: ethan at stoneleaf.us (Ethan Furman) Date: Fri, 02 Apr 2010 13:33:48 -0700 Subject: C-style static variables in Python? In-Reply-To: <89ef884c-eb30-4ca8-a292-d9bc17e8cd4f@z4g2000yqa.googlegroups.com> References: <98947d50-6352-466b-aae6-35e7b4c8c5af@33g2000yqj.googlegroups.com> <89ef884c-eb30-4ca8-a292-d9bc17e8cd4f@z4g2000yqa.googlegroups.com> Message-ID: <4BB654AC.4020101@stoneleaf.us> Patrick Maupin wrote: [snippage] > Well, I think the whole discussion has basically been about personal > preference. OTOH, but if you call the function a few million times, > you might find the cost of try/except to be something that you would > rather not incur -- it might become a performance issue rather than a > personal choice issue. On the other OTHER hand, if you call the > function a few billion times, performance weighs more heavily in favor > of the closure approach rather than the object approach, since local > variable lookup is so much cheaper. Indeed. I was surprised to find your __getattr__ approach faster than the try/except approach (about 20% on my machine). I'll have to think about that for future situations like this. My main point, though, was using __call__, and not some weird _ method. ;) ~Ethan~ From steve at holdenweb.com Fri Apr 2 16:35:58 2010 From: steve at holdenweb.com (Steve Holden) Date: Fri, 02 Apr 2010 16:35:58 -0400 Subject: (a==b) ? 'Yes' : 'No' In-Reply-To: References: <4bb22b39$0$1638$742ec2ed@news.sonic.net> Message-ID: kj wrote: > In Steve Holden writes: > >> John Nagle wrote: >>> Chris Rebert wrote: >>>> On Tue, Mar 30, 2010 at 8:40 AM, gentlestone >>>> wrote: >>>>> Hi, how can I write the popular C/JAVA syntax in Python? >>>>> >>>>> Java example: >>>>> return (a==b) ? 'Yes' : 'No' >>>>> >>>>> My first idea is: >>>>> return ('No','Yes')[bool(a==b)] >>>>> >>>>> Is there a more elegant/common python expression for this? >>>> Yes, Python has ternary operator-like syntax: >>>> return ('Yes' if a==b else 'No') >>>> >>>> Note that this requires a recent version of Python. >>> Who let the dogs in? That's awful syntax. >>> >> Yes, that's deliberately awful syntax. Guido designed it that way to >> ensure that people didn't aver-use it, thereby reducing the readability >> of Python applications. > > Is that for real??? It's the QWERTY rationale all over again. Swell. > I may be misrepresenting Guido here. Unlike Tim Peters I have never claimed to be able to channel him. > "Let's preserve readability by making the syntax so ugly that people > won't use it."??? That's just perverse. (It would have been more > reassuring if the reason had been simply that Guido has an inexplicable > dislike of ternary expressions just like one may have an inexplicable > dislike of Broadway musicals.) > I don't think his dislike of them is inexplicable. They do, when over-used, lead to the most impenetrable code, which as a bonus is frequently buggy. > First, I don't understand why ternary expressions are inherently > hard to read, and therefore must be discouraged in the name of > overall code readability. Sure, one can write impenetrable ternary > expressions, but one can write impenetrable binary expressions or > impenetrable anything else, even in Python. That the expression > is ternary has nothing to do with it. > I think it does - the scope of the expressions is inherently longer when three terms are involved rather than just tow. > Second, sticking the test between the two alternatives goes against > a vast tradition in programming languages. This tradition inevitably > fosters habits and expectations when reading code, so going against > it automatically makes code less readable to all who were educated > in that tradition. Consider, for example, the readability of the > following if statement in some hypothetical language: > > begin: > # this branch will be executed if test() (see below) evaluates > # to true > x = y + z > a = b * x + c > i = j - k > p = log(q) > if test() else: > x = -(y + z) > a = b * x + 2 * c > i = j + k > p = -log(q) > > If you find this hard to read (I do), the quetion is "why?". For > me it's because, maybe through years of reading code, I've developed > a habit that says: when you run into a fork in the logic, first > understand what the decision hinges on. Therefore, my brain will > start hunting for that test, and it sucks to have to find it buried > somewhere in the middle. (Sure, one could justify this horrible > syntax with an argument reminiscent of the one you gave for "A if > X else B". It goes like this: long blocks of code should be avoided > in the name of readability; this syntax discourages long blocks of > code because one doesn't want to skip too far ahead to find that > test. Ergo the end result is improved readability. That's just > nuts.) > It's precisely to avoid that kind of lunacy that the chosen form was adopted. Conditional expressions aren't *meant* to be complex enough to leave any doubt about their meaning. If you require such complexity that's perfectly OK - just use an "if" statement. > Anyway, I don't know of any other language that puts the test > between the alternatives. No doubt there's one out there, with > emphasis on "out there"... > I understand you don't like it. The message handing down the decision is at http://mail.python.org/pipermail/python-dev/2005-September/056846.html and consideration of many applicable points in the standard library is at http://mail.python.org/pipermail/python-dev/2005-September/056803.html Disagree with the decision as you might, you can't argue that it was made with insufficient consideration of the possible alternatives or the merits of the solution. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 See PyCon Talks from Atlanta 2010 http://pycon.blip.tv/ Holden Web LLC http://www.holdenweb.com/ UPCOMING EVENTS: http://holdenweb.eventbrite.com/ From pmaupin at gmail.com Fri Apr 2 16:42:53 2010 From: pmaupin at gmail.com (Patrick Maupin) Date: Fri, 2 Apr 2010 13:42:53 -0700 (PDT) Subject: C-style static variables in Python? References: <98947d50-6352-466b-aae6-35e7b4c8c5af@33g2000yqj.googlegroups.com> <89ef884c-eb30-4ca8-a292-d9bc17e8cd4f@z4g2000yqa.googlegroups.com> Message-ID: <2d7feb67-e8de-4e95-89fc-d29e80b6c7cb@q15g2000yqj.googlegroups.com> On Apr 2, 3:33?pm, Ethan Furman wrote: > My main point, though, was using __call__, and not some weird _ method. ?;) Yes, __call__ is good. In general, not naming things that don't need to be named is good (but if you have too many of them to keep track of, then, obviously, they need to be named, hence named tuples). But I didn't need to address that, since you already did :-) From martin at v.loewis.de Fri Apr 2 16:44:10 2010 From: martin at v.loewis.de (Martin v. Loewis) Date: Fri, 02 Apr 2010 22:44:10 +0200 Subject: Is it possible to store data in a Python file in a way similar to Ruby's __END__ section? In-Reply-To: <1651230b-7f02-4fce-a3cd-0a2687af0ff8@n34g2000yqb.googlegroups.com> References: <1651230b-7f02-4fce-a3cd-0a2687af0ff8@n34g2000yqb.googlegroups.com> Message-ID: Christopher Roach wrote: > I have a script that I am working on to process a bunch of data. A > good portion of the Tk-based GUI is driven by a large set of YAML data > and I'd love to store that data inside of the script so that I can > send just a single file to my colleague. Ruby has a mechanism for > doing this whereby I can load the data by doing a YAML.load(DATA) > which loads everything in the file after the __END__ keyword (for a > better explanation of this see http://bit.ly/V9w8m). I was wondering > if anyone knew of a way to do something similar in Python? The common approach is to write DATA="""\ yaml data here """ If you want to process the data in the same file, you can't really put them at the end of the file - in fact, putting them at the beginning is more common. Regards, Martin From pmaupin at gmail.com Fri Apr 2 16:48:11 2010 From: pmaupin at gmail.com (Patrick Maupin) Date: Fri, 2 Apr 2010 13:48:11 -0700 (PDT) Subject: (a==b) ? 'Yes' : 'No' References: <4bb22b39$0$1638$742ec2ed@news.sonic.net> Message-ID: On Apr 2, 3:12?pm, kj wrote: > Is that for real??? ?It's the QWERTY rationale all over again. ?Swell. Well, bearing in mind that everybody seems to have an agenda, so you can't (or shouldn't, anyway) take all your news from a single source, it may be that the common wisdom about the QWERTY thing is incorrect: http://reason.com/archives/1996/06/01/typing-errors I have to confess that I haven't done any real deep research on the subject, but yet again, we find there is more than one side to a story. Regards, Pat From apt.shansen at gmail.invalid Fri Apr 2 16:52:25 2010 From: apt.shansen at gmail.invalid (Stephen Hansen) Date: Fri, 2 Apr 2010 13:52:25 -0700 Subject: Is it possible to store data in a Python file in a way similar to Ruby's __END__ section? References: <1651230b-7f02-4fce-a3cd-0a2687af0ff8@n34g2000yqb.googlegroups.com> Message-ID: <201004021352253244-aptshansen@gmailinvalid> On 2010-04-02 13:08:00 -0700, Christopher Roach said: > I have a script that I am working on to process a bunch of data. A > good portion of the Tk-based GUI is driven by a large set of YAML data > and I'd love to store that data inside of the script so that I can > send just a single file to my colleague. Ruby has a mechanism for > doing this whereby I can load the data by doing a YAML.load(DATA) > which loads everything in the file after the __END__ keyword (for a > better explanation of this see http://bit.ly/V9w8m). I was wondering > if anyone knew of a way to do something similar in Python? If its just like a YAML file or such, the idiomatic thing to do is just use a triple-quoted string, I think. Such as: DATA=""" My stuff and stuff and more stuff and other stuff""" If you're wanting to include binary stuff like images, that gets more complicated. I've seen it done a couple different ways, but usually storing as above but base64 encoding the strings first. Anything more, and its usually time to start packaging the thing wiht py2exe or similar things :) Now, one concern you may have is order-- you may not want this stuff on top of your script, but instead on the bottom so its sort of 'out of the way'. For that, I'd do like: import YAML def random_thing(arg): return arg + 1 def main(): config = YAML.load(DATA) # Code ends DATA=""" blah blah blah""" # Bootstrap if __name__ == "__main__": main() -- --S ... p.s: change the ".invalid" to ".com" in email address to reply privately. From danmcleran at yahoo.com Fri Apr 2 16:52:42 2010 From: danmcleran at yahoo.com (danmcleran at yahoo.com) Date: Fri, 2 Apr 2010 13:52:42 -0700 (PDT) Subject: Getting Local MAC Address References: Message-ID: On Apr 2, 2:14?pm, Booter wrote: > Hello all, > > I am new to python ans was wondering if there was a way to get the mac > address from the local NIC? > > Thanks for your help. > > Gerad for windows parse p.stdout.read(): import subprocess p = subprocess.Popen('ipconfig', shell = True, stdout = subprocess.PIPE) p.wait() print p.stdout.read() From ethan at stoneleaf.us Fri Apr 2 16:54:44 2010 From: ethan at stoneleaf.us (Ethan Furman) Date: Fri, 02 Apr 2010 13:54:44 -0700 Subject: (a==b) ? 'Yes' : 'No' In-Reply-To: References: <4bb22b39$0$1638$742ec2ed@news.sonic.net> Message-ID: <4BB65994.2090809@stoneleaf.us> kj wrote: > In Steve Holden writes: > >> John Nagle wrote: >>> Chris Rebert wrote: >>>> On Tue, Mar 30, 2010 at 8:40 AM, gentlestone >>>> wrote: >>>>> Hi, how can I write the popular C/JAVA syntax in Python? >>>>> >>>>> Java example: >>>>> return (a==b) ? 'Yes' : 'No' >>>>> >>>>> My first idea is: >>>>> return ('No','Yes')[bool(a==b)] >>>>> >>>>> Is there a more elegant/common python expression for this? >>>> Yes, Python has ternary operator-like syntax: >>>> return ('Yes' if a==b else 'No') >>>> >>>> Note that this requires a recent version of Python. >>> Who let the dogs in? That's awful syntax. >>> >> Yes, that's deliberately awful syntax. Guido designed it that way to >> ensure that people didn't aver-use it, thereby reducing the readability >> of Python applications. > > Is that for real??? It's the QWERTY rationale all over again. Swell. The rationale I remember is that it's intended primarily where the condition is usually true, with the false only being once in a while. [snip] > Second, sticking the test between the two alternatives goes against > a vast tradition in programming languages. This tradition inevitably > fosters habits and expectations when reading code, so going against > it automatically makes code less readable to all who were educated > in that tradition. So you're saying that new languages can't change anything already well established? So much for break-through innovations. And what about the programmers? It is good to learn to think in different ways. At any rate, I far prefer it over C's syntax. ~Ethan~ From danmcleran at yahoo.com Fri Apr 2 16:55:54 2010 From: danmcleran at yahoo.com (danmcleran at yahoo.com) Date: Fri, 2 Apr 2010 13:55:54 -0700 (PDT) Subject: Getting Local MAC Address References: Message-ID: On Apr 2, 2:52?pm, "danmcle... at yahoo.com" wrote: > On Apr 2, 2:14?pm, Booter wrote: > > > Hello all, > > > I am new to python ans was wondering if there was a way to get the mac > > address from the local NIC? > > > Thanks for your help. > > > Gerad > > for windows parse p.stdout.read(): > > import subprocess > > p = subprocess.Popen('ipconfig', shell = True, stdout = > subprocess.PIPE) > > p.wait() > > print p.stdout.read() sorry, posted too soon. looks like this is for ip address only. From danmcleran at yahoo.com Fri Apr 2 16:58:35 2010 From: danmcleran at yahoo.com (danmcleran at yahoo.com) Date: Fri, 2 Apr 2010 13:58:35 -0700 (PDT) Subject: Getting Local MAC Address References: Message-ID: On Apr 2, 2:52?pm, "danmcle... at yahoo.com" wrote: > On Apr 2, 2:14?pm, Booter wrote: > > > Hello all, > > > I am new to python ans was wondering if there was a way to get the mac > > address from the local NIC? > > > Thanks for your help. > > > Gerad > > for windows parse p.stdout.read(): > > import subprocess > > p = subprocess.Popen('ipconfig', shell = True, stdout = > subprocess.PIPE) > > p.wait() > > print p.stdout.read() try this instead: import subprocess p = subprocess.Popen('ipconfig /all', shell = True, stdout = subprocess.PIPE) p.wait() print p.stdout.read() From irmen-NOSPAM- at xs4all.nl Fri Apr 2 16:59:41 2010 From: irmen-NOSPAM- at xs4all.nl (Irmen de Jong) Date: Fri, 02 Apr 2010 22:59:41 +0200 Subject: Getting Local MAC Address In-Reply-To: References: Message-ID: <4bb65a3f$0$22920$e4fe514c@news.xs4all.nl> On 2-4-2010 22:55, danmcleran at yahoo.com wrote: > On Apr 2, 2:52 pm, "danmcle... at yahoo.com" > wrote: >> On Apr 2, 2:14 pm, Booter wrote: >> >>> Hello all, >> >>> I am new to python ans was wondering if there was a way to get the mac >>> address from the local NIC? >> >>> Thanks for your help. >> >>> Gerad >> >> for windows parse p.stdout.read(): >> >> import subprocess >> >> p = subprocess.Popen('ipconfig', shell = True, stdout = >> subprocess.PIPE) >> >> p.wait() >> >> print p.stdout.read() > > sorry, posted too soon. looks like this is for ip address only. Actually you can get more info including the MAC address when you pass the /all switch. -irmen From __peter__ at web.de Fri Apr 2 17:32:58 2010 From: __peter__ at web.de (Peter Otten) Date: Fri, 02 Apr 2010 23:32:58 +0200 Subject: Splitting a string References: <450895af-d8ec-4312-a31e-569e39aaa319@w17g2000yqj.googlegroups.com> Message-ID: Thomas Heller wrote: > Thanks to all for these code snippets. Peter's solution is the winner - > most elegant and also the fastest. With an additional list comprehension > to remove the possible empty strings at the start and at the end I get > 16 us. Interesting is that Xavier's solution (which is similar to > some code that I wrote myself) isn't so much slower; it get timings of > around 22 us. Deleting the first or last item is probably faster than looping over the whole list. If there aren't any empty strings the overhead is constant. _split = re.compile(r"(\d+)").split def split(s): if not s: return () parts = _split(s) parts[1::2] = map(int, parts[1::2]) if parts[-1] == "": del parts[-1] if parts[0] == "": del parts[0] return tuple(parts) Peter From torriem at gmail.com Fri Apr 2 17:48:31 2010 From: torriem at gmail.com (Michael Torrie) Date: Fri, 02 Apr 2010 15:48:31 -0600 Subject: Getting Local MAC Address In-Reply-To: <394791.60497.qm@web33802.mail.mud.yahoo.com> References: <4BB65FD1.4070809@gmail.com> <394791.60497.qm@web33802.mail.mud.yahoo.com> Message-ID: <4BB6662F.8040103@gmail.com> On 04/02/2010 03:30 PM, Dan McLeran wrote: > i'm running python 2.6 on win xp sp3 and i get: Your code isn't portable to non-Windows OS's. On my Mac and on my Linux workstations it simply doesn't work. Using '/usr/sbin/ifconfig' as the executable name in Popen does work, however. The OP didn't state his platform, so we shouldn't assume that a windows-only solution will work for him may. Since this list covers the use of many kinds of operating systems, it is foolish to make assumptions. This was my point. From torriem at gmail.com Fri Apr 2 17:51:26 2010 From: torriem at gmail.com (Michael Torrie) Date: Fri, 02 Apr 2010 15:51:26 -0600 Subject: Getting Local MAC Address In-Reply-To: References: Message-ID: <4BB666DE.5020404@gmail.com> On 04/02/2010 02:14 PM, Booter wrote: > I am new to python ans was wondering if there was a way to get the mac > address from the local NIC? As Dan has indicated, you have to Popen an external command to get this information. Every OS has different commands and syntaxes for this. You'll have to have a different Popen for each operating system. Also you must take into account that most computers have more than one ethernet interface these days (real and virtual). So you'll likely end up with between 2 and 5 different MAC addresses. And some of those are fake as well, like the MAC addresses used by VMware's virtual networking interfaces. What operating system are you targeting? Windows? Linux? Mac? To really answer your question you must supply more information. From davea at ieee.org Fri Apr 2 18:11:32 2010 From: davea at ieee.org (Dave Angel) Date: Fri, 02 Apr 2010 17:11:32 -0500 Subject: off topic but please forgive me me and answer In-Reply-To: <6fe000ff-92a3-427f-9dd2-594005ef366e@z3g2000yqz.googlegroups.com> References: <4bb505c5$0$1133$4fafbaef@reader3.news.tin.it> <32d91d4f-616f-404b-afbb-3b97dc380a67@e7g2000yqf.googlegroups.com> <4bb55a18$0$8827$c3e8da3@news.astraweb.com> <6fe000ff-92a3-427f-9dd2-594005ef366e@z3g2000yqz.googlegroups.com> Message-ID: <4BB66B94.9030001@ieee.org> Mensanator wrote: > On Apr 1, 9:44 pm, Steven D'Aprano cybersource.com.au> wrote: > >> >>>>> 1/2.0 >>>>> >> 0.25 >> >> If you want an exact result when multiplying arbitrary fractions, you >> need to avoid floats and decimals and use Fractions: >> >> >>>>> Fraction(1, 2)**2 >>>>> >> Fraction(1, 4) >> > > Where do you get that from? > > In Python2.6, from fractions import Fraction And Fraction is now a class which supports fractional arithmetic. From steve at holdenweb.com Fri Apr 2 18:18:36 2010 From: steve at holdenweb.com (Steve Holden) Date: Fri, 02 Apr 2010 18:18:36 -0400 Subject: Getting Local MAC Address In-Reply-To: References: Message-ID: Booter wrote: > Hello all, > > I am new to python ans was wondering if there was a way to get the mac > address from the local NIC? > > Thanks for your help. > >>> import uuid >>> uuid.getnode() 246090452741227L >>> This is supposed to return the MAC address, but I am not sure it does. The documentation says: """ getnode( ) Get the hardware address as a 48-bit positive integer. The first time this runs, it may launch a separate program, which could be quite slow. If all attempts to obtain the hardware address fail, we choose a random 48-bit number with its eighth bit set to 1 as recommended in RFC 4122. "Hardware address" means the MAC address of a network interface, and on a machine with multiple network interfaces the MAC address of any one of them may be returned. """ So the return value isn't *guaranteed* to be an ethernet address, and I'm not sure whether that code gets any regular testing. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 See PyCon Talks from Atlanta 2010 http://pycon.blip.tv/ Holden Web LLC http://www.holdenweb.com/ UPCOMING EVENTS: http://holdenweb.eventbrite.com/ From pmaupin at gmail.com Fri Apr 2 18:53:07 2010 From: pmaupin at gmail.com (Patrick Maupin) Date: Fri, 2 Apr 2010 15:53:07 -0700 (PDT) Subject: Splitting a string References: <450895af-d8ec-4312-a31e-569e39aaa319@w17g2000yqj.googlegroups.com> Message-ID: <737b6e81-71ef-430d-b5e7-dffdf1569fd7@g30g2000yqc.googlegroups.com> On Apr 2, 4:32?pm, Peter Otten <__pete... at web.de> wrote: > _split = re.compile(r"(\d+)").split > def split(s): > ? ? if not s: > ? ? ? ? return () > ? ? parts = _split(s) > ? ? parts[1::2] = map(int, parts[1::2]) > ? ? if parts[-1] == "": > ? ? ? ? del parts[-1] > ? ? if parts[0] == "": > ? ? ? ? del parts[0] > ? ? return tuple(parts) > That's certainly faster than a list comprehension (at least on long lists), but it might be a little obscure why the "if not s:" is needed, so unless Thomas has a really long result list, he might want to just keep the list comprehension, which is (IMO) very readable. Alternatively, this is halfway between the previous example and the list comprehension: _split = re.compile(r"(\d+)").split def split(s): parts = _split(s) parts[1::2] = map(int, parts[1::2]) for index in (-1, 0): if parts and parts[index] == "": del parts[index] return tuple(parts) BTW, I just remembered that, although I have often used the fact that split returns alternating non-match/match/.../match/non-match in the past, the last time I did this particular task (of splitting out digits from a string), I didn't make use of that fact. But I wasn't expecting very many splits for this case. FWIW, here's a class I wrote that does this to a string for the express purpose of making sorts work better: http://code.google.com/p/pyeda/source/browse/trunk/kipy/kipy/utility/istring.py Regards, Pat From torriem at gmail.com Fri Apr 2 18:56:26 2010 From: torriem at gmail.com (Michael Torrie) Date: Fri, 02 Apr 2010 16:56:26 -0600 Subject: Getting Local MAC Address In-Reply-To: <617432.41000.qm@web33805.mail.mud.yahoo.com> References: <4BB65FD1.4070809@gmail.com> <394791.60497.qm@web33802.mail.mud.yahoo.com> <4BB6662F.8040103@gmail.com> <617432.41000.qm@web33805.mail.mud.yahoo.com> Message-ID: <4BB6761A.1030305@gmail.com> On 04/02/2010 04:01 PM, Dan McLeran wrote: > which is why my OP stated the solution was for windows: > > "for windows parse > p.stdout.read():" Gotcha. Definitely missed that! From no.email at please.post Fri Apr 2 18:59:00 2010 From: no.email at please.post (kj) Date: Fri, 2 Apr 2010 22:59:00 +0000 (UTC) Subject: C-style static variables in Python? References: Message-ID: In Duncan Booth writes: >class Spam(object): > mongo = None > def __call__(self, x, y, z): > if self.mongo is None: > self.mongo = heavy_lifting_at_runtime() > return frobnicate(x, y, z, self.mongo) >spam = Spam() >ham = spam(1, 2, 3) I really like this. Thanks. >That's natural and readable. >From reading this thread, and the "(a==b) ? 'Yes' : 'No'" one, the inescapable conclusion is that "readability" (like beauty) is very much in the eye of the beholder, or, in this case, in the eye of Guido. ~K From steve at REMOVE-THIS-cybersource.com.au Fri Apr 2 19:07:53 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 02 Apr 2010 23:07:53 GMT Subject: off topic but please forgive me me and answer References: <4bb505c5$0$1133$4fafbaef@reader3.news.tin.it> <32d91d4f-616f-404b-afbb-3b97dc380a67@e7g2000yqf.googlegroups.com> <4bb55a18$0$8827$c3e8da3@news.astraweb.com> <6fe000ff-92a3-427f-9dd2-594005ef366e@z3g2000yqz.googlegroups.com> Message-ID: <4bb678c6$0$8827$c3e8da3@news.astraweb.com> On Fri, 02 Apr 2010 12:35:55 -0700, Mensanator wrote: >> If you want an exact result when multiplying arbitrary fractions, you >> need to avoid floats and decimals and use Fractions: >> >> >>> Fraction(1, 2)**2 >> >> Fraction(1, 4) > > Where do you get that from? Where do I get what from? Fraction? Oops, sorry about that. In Python2.6: >>> from fractions import Fraction In older Pythons, there was a demo module Demo/classes/Rat.py but it may not be installed on your system. See http://bugs.python.org/issue1682 If you meant, where did I get the statement about exact results from, both float and Decimal are fixed precision numbers. float precision is fixed by the operating system and/or hardware; Decimal precision can be arbitrarily chosen by the caller, but having made that choice, calculations are rounded to that precision. Only Fraction gives exact results for any arbitrary rational number. -- Steven From iwanttobeabadger at googlemail.com Fri Apr 2 19:22:58 2010 From: iwanttobeabadger at googlemail.com (Nathan Harmston) Date: Sat, 3 Apr 2010 00:22:58 +0100 Subject: Generating text from a regular expression In-Reply-To: References: <829a8515-0c35-449e-abb9-2321092f2598@l25g2000yqd.googlegroups.com> Message-ID: Thanks everyone, the invRegexInf is perfect. Thanks again, Nathan On 1 April 2010 10:17, Gabriel Genellina wrote: > En Wed, 31 Mar 2010 12:23:48 -0300, Paul McGuire > escribi?: >> >> On Mar 31, 5:49 am, Nathan Harmston >> wrote: >>> >>> I have a slightly complicated/medium sized regular expression and I >>> want to generate all possible words that it can match (to compare >>> performance of regex against an acora based matcher). >> >> The pyparsing wiki Examples page includes this regex inverter: >> http://pyparsing.wikispaces.com/file/view/invRegex.py >> >>> From the module header: >> >> # Supports: >> # - {n} and {m,n} repetition, but not unbounded + or * repetition >> # - ? optional elements >> # - [] character ranges >> # - () grouping >> # - | alternation > > I took the liberty of modifying your invRegex.py example, adding support > for infinite repeaters. It depends on two other modules: > > mergeinf.py (from http://code.activestate.com/recipes/577041) provides the > infinite merge operation. > > enumre.py provides the basic functions (merge, prod, repeat, closure) > necessary to enumerate the language generated by a given regular > expression, even if it contains unbounded repeaters like *,+. ?The key is > to generate shorter strings before longer ones, so in 'a*|b*' it doesn't > get stuck generating infinite a's before any b. > > By example, "(a|bc)*d" corresponds to this code: > > ? ? ?prod( > ? ? ? ?closure( > ? ? ? ? ?merge( > ? ? ? ? ? ?'a', > ? ? ? ? ? ? prod('b','c'))), > ? ? ? ?'d') > > which returns an infinite generator starting with: > > d > ad > aad > bcd > aaad > abcd > bcad > aaaad > aabcd > abcad > bcaad > bcbcd > aaaaad > aaabcd > aabcad > ... > > > I got the idea from > http://userweb.cs.utexas.edu/users/misra/Notes.dir/RegExp.pdf > > Finally, invRegexInf.py is based on your original regex parser. I only > modified the generation part, taking advantage of the above > infrastructure; the parser itself remains almost the same. It essentially > saves oneself the very tedious work of converting a regular expression > into the equivalent sequence of function calls as shown above. (I hope I > got it right: I like pyparsing a lot and use it whenever I feel it's > appropriate, but not as often as to remember the details...) > > -- > Gabriel Genellina > -- > http://mail.python.org/mailman/listinfo/python-list > > From mensanator at aol.com Fri Apr 2 19:48:12 2010 From: mensanator at aol.com (Mensanator) Date: Fri, 2 Apr 2010 16:48:12 -0700 (PDT) Subject: off topic but please forgive me me and answer References: <4bb505c5$0$1133$4fafbaef@reader3.news.tin.it> <32d91d4f-616f-404b-afbb-3b97dc380a67@e7g2000yqf.googlegroups.com> <4bb55a18$0$8827$c3e8da3@news.astraweb.com> <6fe000ff-92a3-427f-9dd2-594005ef366e@z3g2000yqz.googlegroups.com> <4bb678c6$0$8827$c3e8da3@news.astraweb.com> Message-ID: <13ed9e98-5a0c-4bd4-a173-029cdaafd726@u22g2000yqf.googlegroups.com> On Apr 2, 6:07?pm, Steven D'Aprano wrote: > On Fri, 02 Apr 2010 12:35:55 -0700, Mensanator wrote: > >> If you want an exact result when multiplying arbitrary fractions, you > >> need to avoid floats and decimals and use Fractions: > > >> >>> Fraction(1, 2)**2 > > >> Fraction(1, 4) > > > Where do you get that from? > > Where do I get what from? Fraction? Oops, sorry about that. > > In Python2.6: > > >>> from fractions import Fraction Ok, thanks. I've been using gmpy to do rational arithmetic: >>> import gmpy >>> gmpy.mpq(1,2)**2 mpq(1,4) But I don't have a lot of call for it. > > In older Pythons, there was a demo module Demo/classes/Rat.py but it may > not be installed on your system. Seehttp://bugs.python.org/issue1682 > > If you meant, where did I get the statement about exact results from, > both float and Decimal are fixed precision numbers. float precision is > fixed by the operating system and/or hardware; Decimal precision can be > arbitrarily chosen by the caller, but having made that choice, > calculations are rounded to that precision. Only Fraction gives exact > results for any arbitrary rational number. Yes, rationals are handy sometimes. > > -- > Steven From mensanator at aol.com Fri Apr 2 19:50:50 2010 From: mensanator at aol.com (Mensanator) Date: Fri, 2 Apr 2010 16:50:50 -0700 (PDT) Subject: off topic but please forgive me me and answer References: <4bb505c5$0$1133$4fafbaef@reader3.news.tin.it> <20100402214110.00a63457@geekmail.INVALID> Message-ID: <788245c6-14a7-42df-bb12-f59e9f1f03d0@z7g2000yqb.googlegroups.com> On Apr 2, 2:34?pm, Patrick Maupin wrote: > On Apr 2, 2:41?pm, Andreas Waldenburger > wrote: > > > While everyone else is mocking you: Can you please elaborate on why you > > want to know and what kind of problem you're trying to solve with this? > > Also, don't you think you should have picked a maths forum for this > > kind of question? > > Methinks the OP is fluent in the way of choosing newsgroups. > According to google, he has posted 6855 messages in 213 groups. Does that really mean anything? Hell, I have 12765 messages posted to 332 groups, but I only use 10 regularly. > > http://groups.google.com/groups/profile?enc_user=ul3SQhIAAAAYmLD0Oj5Y... > > And I can't speak for anybody else, but I just assumed it was an April > Fool's question. ?I meant to be laughing with the OP, not at him, so > sorry if I misunderstood. > > Regards, > Pat From steve at REMOVE-THIS-cybersource.com.au Fri Apr 2 19:57:02 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 02 Apr 2010 23:57:02 GMT Subject: C-style static variables in Python? References: <98947d50-6352-466b-aae6-35e7b4c8c5af@33g2000yqj.googlegroups.com> <89ef884c-eb30-4ca8-a292-d9bc17e8cd4f@z4g2000yqa.googlegroups.com> Message-ID: <4bb6844e$0$8827$c3e8da3@news.astraweb.com> On Fri, 02 Apr 2010 12:39:16 -0700, Patrick Maupin wrote: > On Apr 2, 2:38?pm, Ethan Furman wrote: [...] >> Sounds like a personal preference issue, rather than a necessary / >> unnecessary issue -- after all, if you call that function a thousand >> times, only once is mongo not defined... clearly the exception. ?;) >> >> ~Ethan~ > > Well, I think the whole discussion has basically been about personal > preference. OTOH, but if you call the function a few million times, you > might find the cost of try/except to be something that you would rather > not incur -- it might become a performance issue rather than a personal > choice issue. The cost of a try...except is *very* low -- about the same as a pass statement: >>> from timeit import Timer >>> t1 = Timer("pass", "") >>> t2 = Timer("try:\n pass\nexcept Exception:\n pass", "") >>> min(t2.repeat())/min(t1.repeat()) 1.9227982449955801 Actually catching the exception, on the other hand, is quite expensive: >>> t1 = Timer("len('')", "") >>> t2 = Timer("try:\n len(0)\nexcept Exception:\n pass", "") >>> min(t2.repeat())/min(t1.repeat()) 10.598482743564809 The heuristic I use is, if I expect the try block to raise an exception more than about one time in ten, I change to an explicit test. In this case, since the exception should only be raised once, and then never again, I would use a try...except block. -- Steven From pmaupin at gmail.com Fri Apr 2 20:25:09 2010 From: pmaupin at gmail.com (Patrick Maupin) Date: Fri, 2 Apr 2010 17:25:09 -0700 (PDT) Subject: C-style static variables in Python? References: <98947d50-6352-466b-aae6-35e7b4c8c5af@33g2000yqj.googlegroups.com> <89ef884c-eb30-4ca8-a292-d9bc17e8cd4f@z4g2000yqa.googlegroups.com> <4bb6844e$0$8827$c3e8da3@news.astraweb.com> Message-ID: <98f753e6-0c88-42ef-baf6-bbec8ef69bd6@g10g2000yqh.googlegroups.com> On Apr 2, 6:57?pm, Steven D'Aprano wrote: > On Fri, 02 Apr 2010 12:39:16 -0700, Patrick Maupin wrote: > > On Apr 2, 2:38?pm, Ethan Furman wrote: > [...] > >> Sounds like a personal preference issue, rather than a necessary / > >> unnecessary issue -- after all, if you call that function a thousand > >> times, only once is mongo not defined... clearly the exception. ?;) > > >> ~Ethan~ > > > Well, I think the whole discussion has basically been about personal > > preference. ?OTOH, but if you call the function a few million times, you > > might find the cost of try/except to be something that you would rather > > not incur -- it might become a performance issue rather than a personal > > choice issue. > > The cost of a try...except is *very* low -- about the same as a pass > statement: Agreed. In the example above, if frobnicate() is a null function, the try/except adds about 5% to execution time on my machine. If I were really worried about execution time, I would use a closure *for this particular example* as I mentioned elsewhere. However, the cost of the try/except is not zero, and when I have something I prefer looking at (the __getattr__ doesn't clutter up the main-line execution with conditionals for stuff that only gets used once at initialization) that is always known to be cheaper in execution, that's what I use. I suppose some people might not like looking at the __getattr__, but this is a memoization technique I use quite often, so I find it idiomatic. Regards, Pat From afitting at hotmail.com Fri Apr 2 20:26:12 2010 From: afitting at hotmail.com (mrdrew) Date: Fri, 2 Apr 2010 17:26:12 -0700 (PDT) Subject: psycopg2 / psycopg2.ProgrammingError: syntax error at or near "E'mytable'" Message-ID: Hey all, Right now I'm completely unable to pass parameters to queries under any circumstances. I've got a fairly trivial query as a test... c.execute('SELECT * FROM %(table_name)s LIMIT 1', {'table_name':"mytable"}) It fails, giving the error message... Traceback (most recent call last): File "test.py", line 7, in c.execute('SELECT * FROM %(table_name)s LIMIT 1', {'table_name':"mytable"}) psycopg2.ProgrammingError: syntax error at or near "E'mytable'" LINE 1: SELECT * FROM E'mytable' LIMIT 1 This may be similar to the problem that ASh had (http:// groups.google.com/group/comp.lang.python/browse_thread/thread/ 7463ded0971425f8/538e60ba0ccf2ad3?#538e60ba0ccf2ad3) I'd really appreciate any ideas. At the moment, I'm stuck concatenating strings and hoping for the best. From pmaupin at gmail.com Fri Apr 2 20:32:04 2010 From: pmaupin at gmail.com (Patrick Maupin) Date: Fri, 2 Apr 2010 17:32:04 -0700 (PDT) Subject: off topic but please forgive me me and answer References: <4bb505c5$0$1133$4fafbaef@reader3.news.tin.it> <20100402214110.00a63457@geekmail.INVALID> <788245c6-14a7-42df-bb12-f59e9f1f03d0@z7g2000yqb.googlegroups.com> Message-ID: On Apr 2, 6:50?pm, Mensanator wrote: > On Apr 2, 2:34?pm, Patrick Maupin wrote: > > > Methinks the OP is fluent in the way of choosing newsgroups. > > According to google, he has posted 6855 messages in 213 groups. > > Does that really mean anything? Hell, I have 12765 messages > posted to 332 groups, but I only use 10 regularly. Well, I have been very wrong in my assumptions before, but yes, I do assume it means something: - I assume that the OP knows of the existence of more than one newsgroup. - I assume the OP knows how to locate different newsgroups, either via search or some directory like yahoo, and is able to think about which one he wants to post to and why. - I assume that he is comfortable with the process of posting. In fact, looking at the stats, about half as comfortable as mensanator, and over 18 times as comfortable as me ;-) Of course, I could be all wet in my assumptions, and it may just be that the OP has a cat constantly walking back and forth across his keyboard... Regards, Pat From steve at REMOVE-THIS-cybersource.com.au Fri Apr 2 20:53:16 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 03 Apr 2010 00:53:16 GMT Subject: (a==b) ? 'Yes' : 'No' References: <4bb22b39$0$1638$742ec2ed@news.sonic.net> Message-ID: <4bb6917c$0$8827$c3e8da3@news.astraweb.com> On Fri, 02 Apr 2010 20:12:59 +0000, kj wrote: > In Steve Holden > writes: [...] >>Yes, that's deliberately awful syntax. Guido designed it that way to >>ensure that people didn't aver-use it, thereby reducing the readability >>of Python applications. > > Is that for real??? It's the QWERTY rationale all over again. Swell. Not according to the PEP. No fewer than 16 alternatives were put to a vote, and with no clear winner (but many obvious losers) Guido made the final decision. http://www.python.org/dev/peps/pep-0308/ Although the results of the voting are given, unaccountably no final tally was given. Possibly because nobody could agree on how to tally the votes. Using a simple counting procedure (I give 3 votes for a rank1 vote, 2 votes for a rank2 and 1 for a rank3, signed according to whether it was an Accept or Reject vote) I find the top four candidates were: C. (if C: x else: y) 27% D. C ? x : y 20% B. if C then x else y 13% A. x if C else y 11% with everything else an order of magnitude smaller (6% or less). If you choose a different voting scheme, no doubt you will get different results. Since no candidate syntax got a majority of the vote, it came down to the only vote that really mattered: Guido's. Ankh-Morpork had dallied with many forms of government and had ended up with that form of democracy known as One Man, One Vote. The Patrician was the Man; he had the Vote. -- (T. Pratchett, "Mort") Guido did say "Note that all these are intentionally ugly" but this was followed by a smiley and was obviously tongue-in-cheek. http://mail.python.org/pipermail/python-dev/2005-September/056846.html > "Let's preserve readability by making the syntax so ugly that people > won't use it."??? That's just perverse. (It would have been more > reassuring if the reason had been simply that Guido has an inexplicable > dislike of ternary expressions just like one may have an inexplicable > dislike of Broadway musicals.) "Inexplicable"? They're musicals, and they're on Broadway. Surely that's two good reasons to dislike them *wink* > Second, sticking the test between the two alternatives goes against a > vast tradition in programming languages. As I've pointed out before, it is natural syntax in English. Not necessarily the most common, but common enough to be completely unexceptional: "I'll be there in ten minutes, if I can find a parking space close by, otherwise you should start without me." -- Steven From python at mrabarnett.plus.com Fri Apr 2 21:27:31 2010 From: python at mrabarnett.plus.com (MRAB) Date: Sat, 03 Apr 2010 02:27:31 +0100 Subject: psycopg2 / psycopg2.ProgrammingError: syntax error at or near "E'mytable'" In-Reply-To: References: Message-ID: <4BB69983.6030904@mrabarnett.plus.com> mrdrew wrote: > Hey all, > > Right now I'm completely unable to pass parameters to queries under > any circumstances. I've got a fairly trivial query as a test... > > c.execute('SELECT * FROM %(table_name)s LIMIT 1', > {'table_name':"mytable"}) > > It fails, giving the error message... > > Traceback (most recent call last): > File "test.py", line 7, in > c.execute('SELECT * FROM %(table_name)s LIMIT 1', > {'table_name':"mytable"}) > psycopg2.ProgrammingError: syntax error at or near "E'mytable'" > LINE 1: SELECT * FROM E'mytable' LIMIT 1 > > This may be similar to the problem that ASh had (http:// > groups.google.com/group/comp.lang.python/browse_thread/thread/ > 7463ded0971425f8/538e60ba0ccf2ad3?#538e60ba0ccf2ad3) > > I'd really appreciate any ideas. At the moment, I'm stuck > concatenating strings and hoping for the best. I think that you're confusing Python's string formatting with SQL placeholders. The "%(table_name)s" works only with Python's '%' operator. You should use only the "%s" form (or possibly "?", I'm not sure which!) in the template string and pass the parameters in a tuple (maybe a list will also work) when calling .execute(). From mensanator at aol.com Fri Apr 2 21:29:40 2010 From: mensanator at aol.com (Mensanator) Date: Fri, 2 Apr 2010 18:29:40 -0700 (PDT) Subject: off topic but please forgive me me and answer References: <4bb505c5$0$1133$4fafbaef@reader3.news.tin.it> <20100402214110.00a63457@geekmail.INVALID> <788245c6-14a7-42df-bb12-f59e9f1f03d0@z7g2000yqb.googlegroups.com> Message-ID: <7e6244e2-43e8-41e6-8e84-777a1524fb84@k19g2000yqn.googlegroups.com> On Apr 2, 7:32?pm, Patrick Maupin wrote: > On Apr 2, 6:50?pm, Mensanator wrote: > > > On Apr 2, 2:34?pm, Patrick Maupin wrote: > > > > Methinks the OP is fluent in the way of choosing newsgroups. > > > According to google, he has posted 6855 messages in 213 groups. > > > Does that really mean anything? Hell, I have 12765 messages > > posted to 332 groups, but I only use 10 regularly. > > Well, I have been very wrong in my assumptions before, but yes, I do > assume it means something: Yes, you are, in fact, all wet. > > - I assume that the OP knows of the existence of more than one > newsgroup. "More than one", that's fair. 213, unlikely. > > - I assume the OP knows how to locate different newsgroups, either via > search or some directory like yahoo, and is able to think about which > one he wants to post to and why. And most of those probably involved no thought at all, probably due to cross-posting from a relatively small number of sources (certainly in my case). So, no, this stat proves nothing about the OP's ability to find newsgroups or think about their appropriateness. > > - I assume that he is comfortable with the process of posting. ?In > fact, looking at the stats, about half as comfortable as mensanator, > and over 18 times as comfortable as me ;-) Well, _I've_ been here on Usenet for 10 years. But despite the stats, I know little about most to the groups I've "posted to". > > Of course, I could be all wet in my assumptions, and it may just be > that the OP has a cat constantly walking back and forth across his > keyboard... Don't you know how Usenet works? > > Regards, > Pat From tjreedy at udel.edu Fri Apr 2 21:46:39 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 02 Apr 2010 21:46:39 -0400 Subject: C-style static variables in Python? In-Reply-To: References: Message-ID: On 4/2/2010 6:59 PM, kj wrote: > In Duncan Booth writes: > >> class Spam(object): >> mongo = None >> def __call__(self, x, y, z): >> if self.mongo is None: >> self.mongo = heavy_lifting_at_runtime() >> return frobnicate(x, y, z, self.mongo) Unless one wants the intialization of mongo delayed in case spam is never called, it can go in __init__ instead. >> spam = Spam() > >> ham = spam(1, 2, 3) > > I really like this. Thanks. > >> That's natural and readable. > >> From reading this thread, and the "(a==b) ? 'Yes' : 'No'" one, the > inescapable conclusion is that "readability" (like beauty) is very > much in the eye of the beholder, or, in this case, in the eye of > Guido. > > ~K From tjreedy at udel.edu Fri Apr 2 21:48:22 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 02 Apr 2010 21:48:22 -0400 Subject: C-style static variables in Python? In-Reply-To: References: Message-ID: On 4/2/2010 1:28 PM, Paul McGuire wrote: > On Apr 1, 5:34 pm, kj wrote: >> When coding C I have often found static local variables useful for >> doing once-only run-time initializations. For example: >> > > Here is a decorator to make a function self-aware, giving it a "this" > variable that points to itself, which you could then initialize from > outside with static flags or values: > > from functools import wraps > > def self_aware(fn): > @wraps(fn) > def fn_(*args): > return fn(*args) > fn_.__globals__["this"] = fn_ > return fn_ In 3.1, at least, the wrapper is not needed. def self_aware(fn): fn.__globals__["this"] = fn return fn Acts the same > @self_aware > def foo(): > this.counter += 1 > print this.counter > > foo.counter = 0 Explicit and separate initialization is a pain. This should be in a closure or class. > foo() > foo() > foo() > Prints: > 1 > 2 > 3 However, either way, the __globals__ attribute *is* the globals dict, not a copy, so one has >>> this Wrapping a second function would overwrite the global binding. Terry Jan Reedy From python.list at tim.thechases.com Fri Apr 2 21:57:41 2010 From: python.list at tim.thechases.com (Tim Chase) Date: Fri, 02 Apr 2010 20:57:41 -0500 Subject: psycopg2 / psycopg2.ProgrammingError: syntax error at or near "E'mytable'" In-Reply-To: <4BB69983.6030904@mrabarnett.plus.com> References: <4BB69983.6030904@mrabarnett.plus.com> Message-ID: <4BB6A095.5080802@tim.thechases.com> MRAB wrote: > I think that you're confusing Python's string formatting with > SQL placeholders. > > The "%(table_name)s" works only with Python's '%' operator. > You should use only the "%s" form (or possibly "?", I'm not > sure which!) It varies depending on your DB driver. Check out the .paramstyle property of your DB driver: >>> import sqlite3 >>> sqlite3.paramstyle 'qmark' (sqlite uses "?" as the placeholder). Annoying at times, but at least documented and able to be automated which is more than I can say for non-Python DB drivers. > in the template string and pass the parameters in a tuple > (maybe a list will also work) when calling .execute(). Additionally, the OP is passing in a *table-name*, not a parameter value. Most DB interfaces only allow things like # Okay: cur.execute("select * from tbl where field=?", (value,)) not # not okay cur.execute("select * from ? where field=42", (tblname,)) For this, you really have to (1) use Python string-formatting instead of DB parameters and (2) THOROUGHLY vet that the table-name isn't something malicious -- either through controlling that it never comes from the user, or enforcing a fairly strict limit on what table-names can be used if they do come from the user. Regardless of parameter placeholder style. -tkc From pmaupin at gmail.com Fri Apr 2 22:06:07 2010 From: pmaupin at gmail.com (Patrick Maupin) Date: Fri, 2 Apr 2010 19:06:07 -0700 (PDT) Subject: off topic but please forgive me me and answer References: <4bb505c5$0$1133$4fafbaef@reader3.news.tin.it> <20100402214110.00a63457@geekmail.INVALID> <788245c6-14a7-42df-bb12-f59e9f1f03d0@z7g2000yqb.googlegroups.com> <7e6244e2-43e8-41e6-8e84-777a1524fb84@k19g2000yqn.googlegroups.com> Message-ID: <64ca49f2-722a-473f-ab79-23a1b30eedbf@r1g2000yqj.googlegroups.com> On Apr 2, 8:29?pm, Mensanator wrote: > Don't you know how Usenet works? No, but my cat does. From steve at holdenweb.com Fri Apr 2 22:29:34 2010 From: steve at holdenweb.com (Steve Holden) Date: Fri, 02 Apr 2010 22:29:34 -0400 Subject: psycopg2 / psycopg2.ProgrammingError: syntax error at or near "E'mytable'" In-Reply-To: References: Message-ID: mrdrew wrote: > Hey all, > > Right now I'm completely unable to pass parameters to queries under > any circumstances. I've got a fairly trivial query as a test... > > c.execute('SELECT * FROM %(table_name)s LIMIT 1', > {'table_name':"mytable"}) > > It fails, giving the error message... > > Traceback (most recent call last): > File "test.py", line 7, in > c.execute('SELECT * FROM %(table_name)s LIMIT 1', > {'table_name':"mytable"}) > psycopg2.ProgrammingError: syntax error at or near "E'mytable'" > LINE 1: SELECT * FROM E'mytable' LIMIT 1 > > This may be similar to the problem that ASh had (http:// > groups.google.com/group/comp.lang.python/browse_thread/thread/ > 7463ded0971425f8/538e60ba0ccf2ad3?#538e60ba0ccf2ad3) > > I'd really appreciate any ideas. At the moment, I'm stuck > concatenating strings and hoping for the best. You've already been told about the syntactic errors you have made with the psycopg2 paramstyle (use %s with a tuple, not %(name)s with a dict). You should also understand that the purpose of parameterization is twofold: firstly, to provide efficiency by allowing the database back-end to avoid duplication of up-front query compilation work when only the data differs; secondly to avoid any possibility of SQL injection attacks by ensuring that data are properly escaped. The first purpose relies on the tables being fixed at the time of compilation, so you are probably going to have to use string substitution to build at least that part of the query. Most database drivers won't allow substitution of table names. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 See PyCon Talks from Atlanta 2010 http://pycon.blip.tv/ Holden Web LLC http://www.holdenweb.com/ UPCOMING EVENTS: http://holdenweb.eventbrite.com/ From ewomy at yahoo.com Fri Apr 2 22:40:50 2010 From: ewomy at yahoo.com (kai_nerda) Date: Sat, 03 Apr 2010 02:40:50 -0000 Subject: WinXP, Python3.1.2, dir-listing to XML - problem with unicode file names Message-ID: Hi, OS = Windows XP (German language) Python = 3.1.2 I need to write a directory listing into a XML file. And after hours of trying and searching i have no clue. My main problem is that the file and folder names can have characters of different languages like German, Turkish, Russian, maybe else. Because Python 3.1 is better with unicode, I decided to use that instead of 2.6 For testing I have created the following files: http://img340.imageshack.us/img340/3461/files.png (google for the words russia, turkish, deutsch, france to find websites with special characters and copy & paste) And this is the code I have now: ############################################ # -*- coding: iso-8859-1 -*- # inspired by: # http://www.dpawson.co.uk/java/dirlist.py # (for Python ~2.4) import sys print ('filesystemencoding: ' + sys.getfilesystemencoding()) print ('defaultencoding: ' + sys.getdefaultencoding()) from pprint import pprint import os.path from stat import * from xml.sax.saxutils import XMLGenerator def recurse_dir(path, writer): for cdir, subdirs, files in os.walk(path): pprint (cdir) writer.startElement('dir', { 'name': cdir }) for f in files: uf = f.encode('utf-8') pprint (uf) attribs = {'name': f} attribs['size'] = str(os.stat(os.path.join(cdir,f))[ST_SIZE]) pprint (attribs) writer.startElement('file', attribs) writer.endElement('file') for subdir in subdirs: recurse_dir(os.path.join(cdir, subdir), writer) writer.endElement('directory') break if __name__ == '__main__': directory = 'c:\\_TEST\\' out = open('C:\\_TEST.xml','w') writer = XMLGenerator(out, 'utf-8') writer.startDocument() recurse_dir(directory, writer) out.close() ############################################ And this is the output: ----------------------------- filesystemencoding: mbcs defaultencoding: utf-8 'c:\\_TEST\\' b'1 English.txt' {'name': '1 English.txt', 'size': '0'} b'2 German \xc3\xa4\xc3\xb6\xc3\xbc\xc3\x9f.txt' {'name': '2 German ????.txt', 'size': '0'} b'3 France \xc3\xa1\xc3\xa0\xc3\xa2\xc3\xba\xc3\xb9\xc3\xbb.txt' {'name': '3 France ??????.txt', 'size': '0'} b'4 Russia \xd0\xa0\xd0\xbe\xd1\x81\xd1\x81\xd1\x96\xd0\xb9\xd1\x81\xd0\xba\xd0\xb0\xd1\x8f \xd0\x98\xd0\xbc\xd0\xbf\xd0\xb5\xd1\x80\xd1\x96\xd1\x8f.txt' Traceback (most recent call last): File "test.py", line 36, in recurse_dir(directory, writer) File "test.py", line 22, in recurse_dir pprint (attribs) File "F:\Dev\Python31\lib\pprint.py", line 55, in pprint printer.pprint(object) File "F:\Dev\Python31\lib\pprint.py", line 132, in pprint self._format(object, self._stream, 0, 0, {}, 0) File "F:\Dev\Python31\lib\pprint.py", line 238, in _format write(rep) File "F:\Dev\Python31\lib\encodings\cp850.py", line 19, in encode return codecs.charmap_encode(input,self.errors,encoding_map)[0] UnicodeEncodeError: 'charmap' codec can't encode characters in position 19-28: character maps to ----------------------------- I also tried the line: attribs = {'name': uf} with this result: ----------------------------- filesystemencoding: mbcs defaultencoding: utf-8 'c:\\_TEST\\' b'1 English.txt' {'name': b'1 English.txt', 'size': '0'} Traceback (most recent call last): File "test.py", line 36, in recurse_dir(directory, writer) File "test.py", line 23, in recurse_dir writer.startElement('file', attribs) File "F:\Dev\Python31\lib\xml\sax\saxutils.py", line 127, in startElement self._write(' %s=%s' % (name, quoteattr(value))) File "F:\Dev\Python31\lib\xml\sax\saxutils.py", line 68, in quoteattr data = escape(data, entities) File "F:\Dev\Python31\lib\xml\sax\saxutils.py", line 34, in escape data = data.replace("&", "&") TypeError: expected an object with the buffer interface ----------------------------- Maybe this 'data = data.replace("&", "&")' in saxutils is wrong? Maybe there should be a version for "byte datatype"? Thank you! From ethan at stoneleaf.us Fri Apr 2 22:42:29 2010 From: ethan at stoneleaf.us (Ethan Furman) Date: Fri, 02 Apr 2010 19:42:29 -0700 Subject: C-style static variables in Python? In-Reply-To: References: Message-ID: <4BB6AB15.601@stoneleaf.us> Terry Reedy wrote: >> In Duncan >> Booth writes: >> >>> class Spam(object): >>> mongo = None >>> def __call__(self, x, y, z): >>> if self.mongo is None: >>> self.mongo = heavy_lifting_at_runtime() >>> return frobnicate(x, y, z, self.mongo) > > > Unless one wants the intialization of mongo delayed in case spam is > never called, it can go in __init__ instead. As a matter of fact, I have an object that is usually not called during it's modules use, so I put in __getattr__. Sped the modules load time back up to pert near instantaneous. :) ~Ethan~ From ethan at stoneleaf.us Fri Apr 2 22:48:59 2010 From: ethan at stoneleaf.us (Ethan Furman) Date: Fri, 02 Apr 2010 19:48:59 -0700 Subject: C-style static variables in Python? In-Reply-To: <4bb6844e$0$8827$c3e8da3@news.astraweb.com> References: <98947d50-6352-466b-aae6-35e7b4c8c5af@33g2000yqj.googlegroups.com> <89ef884c-eb30-4ca8-a292-d9bc17e8cd4f@z4g2000yqa.googlegroups.com> <4bb6844e$0$8827$c3e8da3@news.astraweb.com> Message-ID: <4BB6AC9B.3030501@stoneleaf.us> Steven D'Aprano wrote: > On Fri, 02 Apr 2010 12:39:16 -0700, Patrick Maupin wrote: > > >>On Apr 2, 2:38 pm, Ethan Furman wrote: > > [...] > >>>Sounds like a personal preference issue, rather than a necessary / >>>unnecessary issue -- after all, if you call that function a thousand >>>times, only once is mongo not defined... clearly the exception. ;) >>> >>>~Ethan~ >> >>Well, I think the whole discussion has basically been about personal >>preference. OTOH, but if you call the function a few million times, you >>might find the cost of try/except to be something that you would rather >>not incur -- it might become a performance issue rather than a personal >>choice issue. > > > > The cost of a try...except is *very* low -- about the same as a pass > statement: > > >>>>from timeit import Timer >>>>t1 = Timer("pass", "") >>>>t2 = Timer("try:\n pass\nexcept Exception:\n pass", "") >>>>min(t2.repeat())/min(t1.repeat()) > > 1.9227982449955801 > > > Actually catching the exception, on the other hand, is quite expensive: > > >>>>t1 = Timer("len('')", "") >>>>t2 = Timer("try:\n len(0)\nexcept Exception:\n pass", "") >>>>min(t2.repeat())/min(t1.repeat()) > > 10.598482743564809 > > > The heuristic I use is, if I expect the try block to raise an exception > more than about one time in ten, I change to an explicit test. In this > case, since the exception should only be raised once, and then never > again, I would use a try...except block. That was my reasoning as well, but when I timed it for one million runs (so 1 instantiation, 999,999 simple calls), the __getattr__ time was .5 seconds, the try...execpt block was .6; at ten million it was 5 and 6. At those rates, personal preference takes over, at least for me. ~Ethan~ From apt.shansen at gmail.invalid Fri Apr 2 23:11:21 2010 From: apt.shansen at gmail.invalid (Stephen Hansen) Date: Fri, 2 Apr 2010 20:11:21 -0700 Subject: C-style static variables in Python? References: Message-ID: <201004022011213167-aptshansen@gmailinvalid> On 2010-04-02 19:42:29 -0700, Ethan Furman said: > Terry Reedy wrote: >>> In Duncan >>> Booth writes: >>> >>>> class Spam(object): >>>> mongo = None >>>> def __call__(self, x, y, z): >>>> if self.mongo is None: >>>> self.mongo = heavy_lifting_at_runtime() >>>> return frobnicate(x, y, z, self.mongo) >> >> >> Unless one wants the intialization of mongo delayed in case spam is >> never called, it can go in __init__ instead. > > As a matter of fact, I have an object that is usually not called during > it's modules use, so I put in __getattr__. Sped the modules load time > back up to pert near instantaneous. :) > > ~Ethan~ I prefer: class Spam(object): def __init__(self): self._mondo = None def _get_mondo(self): if self._mondo is None: self._mondo = heavy_lifting_at_runtime() return self._mondo mondo = property(_get_mondo) def __call__(self, x, y, z): return frobnicate(x,y,z, self.mondo) I don't know if properties are really faster or slower then a __getattr__, but I find them a lot cleaner if I want to delay some calculation until needed like that. -- --S ... p.s: change the ".invalid" to ".com" in email address to reply privately. From ethan at stoneleaf.us Fri Apr 2 23:12:21 2010 From: ethan at stoneleaf.us (Ethan Furman) Date: Fri, 02 Apr 2010 20:12:21 -0700 Subject: Traits implementation for Python 3 Message-ID: <4BB6B215.60001@stoneleaf.us> Well, it's been said than imitation is the sincerest form of flattery, so be flattered, Michele! In order to gain a better understanding of the whole metaclass issue, I decided to make my own implementation, targeting Python 3. I figured I could leave out a bunch of the complexity required to support Python 2. The more I learn of 3, the more I love it. Many improvements in simplicity and elegance. At any rate, what I have is below. My (very limited) initial tests are working fine. super() appears to work as is. Feedback appreciated! ~Ethan~ 8<----------------------------------------------------------------- """Traits -- used instead of multiple inheritance, inspired my Michele Simionato's Simple Traits experiment Python Version: 3.x Intended use: To combine a single base class, as many traits as needed/desired, glue code to combine together succussfully. While traits are kept in classes, they should be functions only: no state information should be kept. If different traits from different classes having the same name are combined into one one class, that class must specify which one it wants, or an error will be raised at class creation time. If __magic_methods__ are part of the traits, their names must be specified in the trait classes __magic_traits__ list attribute; like-wise, if traits have required attributes that must be supplied by the composed class/other traits, their names must be in the __traits_required__ list attribute. Name resolution order: Least - Base class Traits Most - Current (composed) class""" class Trait(type): def __init__(yo, *args, **kwargs): super().__init__(*args) def __new__(metacls, cls_name, cls_bases, cls_dict, traits=tuple()): if len(cls_bases) > 1: raise TypeError("multiple bases not allowed with Traits") result_class = type.__new__(metacls, cls_name, cls_bases, cls_dict) conflicts = False for trait in result_class.__trait_conflicts__: if getattr(result_class, trait, None) is None: if not conflicts: print() conflicts = True print("conflict found: %r is in %s" % (trait,result_class.__trait_conflicts__[trait])) if conflicts: print() raise TypeError("conflicts must be resolved") delattr(result_class, '__trait_conflicts__') missing_required = False for trait in result_class.__required_traits__: if getattr(result_class, trait, None) is None: if not missing_required: print() missing_required = True print("missing requirement: %r from %s" % (trait,result_class.__required_traits__[trait])) if missing_required: print() raise TypeError("requirements not met") delattr(result_class, '__required_traits__') return result_class @classmethod def __prepare__(metacls, name, bases, traits=tuple()): class _Dict(dict): "Normal dict with traits attribute" class _Traits: "container for trait bundles" def __repr__(yo): return "(%s)" % ", ".join([str(getattr(yo, trait)) for trait in dir(yo) if not trait.startswith('__') or not trait.endswith('__')]) if not traits: raise TypeError("no traits specified... what's the point?") elif type(traits) != tuple: traits = (traits, ) class_dict = _Dict() # for direct . access here setattr(class_dict, 'traits', _Traits()) # to survive proxification class_dict['traits'] = class_dict.traits setattr(class_dict, '__trait_conflicts__', dict()) class_dict['__trait_conflicts__']=class_dict.__trait_conflicts__ setattr(class_dict, '__magic_traits__', set()) class_dict['__magic_traits__'] = class_dict.__magic_traits__ setattr(class_dict, '__required_traits__', dict()) class_dict['__required_traits__']=class_dict.__required_traits__ for trait_bundle in traits: setattr(class_dict.traits, trait_bundle.__name__, trait_bundle) traits_dict = {} for trait_bundle in traits: metacls._integrate_traits(class_dict, traits_dict, trait_bundle) metacls._check_conflicts(class_dict, traits_dict) return class_dict @staticmethod def _check_conflicts(class_dict, traits_dict): for trait, cls_list in traits_dict.items(): if len(cls_list) == 1: class_dict[trait] = getattr(cls_list[0], trait) else: first_trait = getattr(cls_list[0], trait) for next_class in cls_list[1:]: next_trait = getattr(next_class, trait) if first_trait is not next_trait: trouble = True class_dict.__trait_conflicts__[trait] = cls_list break else: class_dict[trait] = first_trait @staticmethod def _integrate_traits(class_dict, traits_dict, trait_bundle): magic_traits=getattr(trait_bundle, '__magic_traits__', tuple()) for trait in magic_traits: class_dict.__magic_traits__.add(trait) if trait not in traits_dict: traits_dict[trait] = [trait_bundle] else: traits_dict[trait].append(trait_bundle) required = getattr(trait_bundle, '__required_traits__', tuple()) for trait in required: #class_dict.__required_traits__.add(trait) if trait not in class_dict.__required_traits__: class_dict.__required_traits__[trait] = [trait_bundle] else: # may have to fix following line... class_dict.__required_traits__[trait].\ append(trait_bundle) for trait in [t for t in dir(trait_bundle) if not t.startswith('__') or not t.endswith('__')]: if trait not in traits_dict: traits_dict[trait] = [trait_bundle] else: traits_dict[trait].append(trait_bundle) # test stuff class TBundle1(): def repeat(yo, text, count): return "%s " % text * count class BaseClass(): def repeat(yo, text, count): return "----%s----" % text * count def whatsit(yo, arg1): return "Got a %s!!" % arg1 class DerivedClass(BaseClass, metaclass=Trait, traits=TBundle1): def repeat(yo, text, count): print('whatever...') def whatsit(yo, arg1): print("calling baseclass's whatsit...") print(super().whatsit(arg1)) 8< ------------------------------------------------------------------------ My apologies for the formatting. With the exception of the one line above that may need to be recombined, it should compile (um, interpret? ;) correctly as-is. From showell30 at yahoo.com Fri Apr 2 23:18:59 2010 From: showell30 at yahoo.com (Steve Howell) Date: Fri, 2 Apr 2010 20:18:59 -0700 (PDT) Subject: (a==b) ? 'Yes' : 'No' References: <4bb22b39$0$1638$742ec2ed@news.sonic.net> <4bb6917c$0$8827$c3e8da3@news.astraweb.com> Message-ID: <844d8970-e814-49cc-b9d4-ea88f760e078@r27g2000yqn.googlegroups.com> On Apr 2, 5:53?pm, Steven D'Aprano wrote: > > As I've pointed out before, it is natural syntax in English. Not > necessarily the most common, but common enough to be completely > unexceptional: > > "I'll be there in ten minutes, if I can find a parking space close by, > otherwise you should start without me." > To Steven's example, the ternary statement is a nice idiom when it emphasizes the most common results: wait_time = 10 if parking_space_close_by else expected_wait_time_in_congested_area() Or: qoutient = m / n if n else None In languages like Ruby/Perl the inverted if statement is also a useful idiom to emphasize concisely that code is exceptional in nature: def quotient(m, n) # guard code return None if n == 0 # happy path return m / n end Or: raise 'Armegeddon' if locusts_flying() useful_intelligible_happy_path_code_here() From pmaupin at gmail.com Fri Apr 2 23:24:46 2010 From: pmaupin at gmail.com (Patrick Maupin) Date: Fri, 2 Apr 2010 20:24:46 -0700 (PDT) Subject: C-style static variables in Python? References: <201004022011213167-aptshansen@gmailinvalid> Message-ID: On Apr 2, 10:11?pm, Stephen Hansen wrote: > > I don't know if properties are really faster or slower then a > __getattr__, but I find them a lot cleaner if I want to delay some > calculation until needed like that. Well, the relative speed of properties vs. __getattr__ can become irrelevant in at least two ways: 1) If the __getattr__ only calculates the value one time and then stuffs it into the instance dictionary, now you are really comparing the relative speed of properties vs. lookup of an attribute in the instance dict. If you're at all concerned about speed, I think there is a clear winner here. 2) There is a single __getattr__ function, vs. one property for every attribute that needs a property. In cases where you can somehow easily compute the attribute names as well as the attribute values, __getattr__ can be a *lot* less code than defining dozens of properties. But you're absolutely right that, in many cases, property is the best way to go for readability (especially if the property is read-only and you're using a recent enough python to use decorators). Regards, Pat From kse.listed.co1 at gmail.com Sat Apr 3 02:14:22 2010 From: kse.listed.co1 at gmail.com (Naeem) Date: Fri, 2 Apr 2010 23:14:22 -0700 (PDT) Subject: "jobs in alaska" "jobs in alaska for foreigners" "jobs in alaska oil" "jobs in alaska for women" "alaska jobs" "alaska jobs north slope" "alaska jobs pipeline" "alaska jobs for foreigners" ON http://jobsinalaska-usa.blogspot.com/ Message-ID: <1687c690-2568-4896-940e-ed994d19dda6@8g2000yqz.googlegroups.com> "jobs in alaska" "jobs in alaska for foreigners" "jobs in alaska oil" "jobs in alaska for women" "alaska jobs" "alaska jobs north slope" "alaska jobs pipeline" "alaska jobs for foreigners" ON http://jobsinalaska-usa.blogspot.com/ "jobs in alaska" "jobs in alaska for foreigners" "jobs in alaska oil" "jobs in alaska for women" "alaska jobs" "alaska jobs north slope" "alaska jobs pipeline" "alaska jobs for foreigners" ON http://jobsinalaska-usa.blogspot.com/ "jobs in alaska" "jobs in alaska for foreigners" "jobs in alaska oil" "jobs in alaska for women" "alaska jobs" "alaska jobs north slope" "alaska jobs pipeline" "alaska jobs for foreigners" ON http://jobsinalaska-usa.blogspot.com/ "jobs in alaska" "jobs in alaska for foreigners" "jobs in alaska oil" "jobs in alaska for women" "alaska jobs" "alaska jobs north slope" "alaska jobs pipeline" "alaska jobs for foreigners" ON http://jobsinalaska-usa.blogspot.com/ "jobs in alaska" "jobs in alaska for foreigners" "jobs in alaska oil" "jobs in alaska for women" "alaska jobs" "alaska jobs north slope" "alaska jobs pipeline" "alaska jobs for foreigners" ON http://jobsinalaska-usa.blogspot.com/ "jobs in alaska" "jobs in alaska for foreigners" "jobs in alaska oil" "jobs in alaska for women" "alaska jobs" "alaska jobs north slope" "alaska jobs pipeline" "alaska jobs for foreigners" ON http://jobsinalaska-usa.blogspot.com/ "jobs in alaska" "jobs in alaska for foreigners" "jobs in alaska oil" "jobs in alaska for women" "alaska jobs" "alaska jobs north slope" "alaska jobs pipeline" "alaska jobs for foreigners" ON http://jobsinalaska-usa.blogspot.com/ "jobs in alaska" "jobs in alaska for foreigners" "jobs in alaska oil" "jobs in alaska for women" "alaska jobs" "alaska jobs north slope" "alaska jobs pipeline" "alaska jobs for foreigners" ON http://jobsinalaska-usa.blogspot.com/ "jobs in alaska" "jobs in alaska for foreigners" "jobs in alaska oil" "jobs in alaska for women" "alaska jobs" "alaska jobs north slope" "alaska jobs pipeline" "alaska jobs for foreigners" ON http://jobsinalaska-usa.blogspot.com/ "jobs in alaska" "jobs in alaska for foreigners" "jobs in alaska oil" "jobs in alaska for women" "alaska jobs" "alaska jobs north slope" "alaska jobs pipeline" "alaska jobs for foreigners" ON http://jobsinalaska-usa.blogspot.com/ "jobs in alaska" "jobs in alaska for foreigners" "jobs in alaska oil" "jobs in alaska for women" "alaska jobs" "alaska jobs north slope" "alaska jobs pipeline" "alaska jobs for foreigners" ON http://jobsinalaska-usa.blogspot.com/ "jobs in alaska" "jobs in alaska for foreigners" "jobs in alaska oil" "jobs in alaska for women" "alaska jobs" "alaska jobs north slope" "alaska jobs pipeline" "alaska jobs for foreigners" ON http://jobsinalaska-usa.blogspot.com/ "jobs in alaska" "jobs in alaska for foreigners" "jobs in alaska oil" "jobs in alaska for women" "alaska jobs" "alaska jobs north slope" "alaska jobs pipeline" "alaska jobs for foreigners" ON http://jobsinalaska-usa.blogspot.com/ "jobs in alaska" "jobs in alaska for foreigners" "jobs in alaska oil" "jobs in alaska for women" "alaska jobs" "alaska jobs north slope" "alaska jobs pipeline" "alaska jobs for foreigners" ON http://jobsinalaska-usa.blogspot.com/ "jobs in alaska" "jobs in alaska for foreigners" "jobs in alaska oil" "jobs in alaska for women" "alaska jobs" "alaska jobs north slope" "alaska jobs pipeline" "alaska jobs for foreigners" ON http://jobsinalaska-usa.blogspot.com/ "jobs in alaska" "jobs in alaska for foreigners" "jobs in alaska oil" "jobs in alaska for women" "alaska jobs" "alaska jobs north slope" "alaska jobs pipeline" "alaska jobs for foreigners" ON http://jobsinalaska-usa.blogspot.com/ "jobs in alaska" "jobs in alaska for foreigners" "jobs in alaska oil" "jobs in alaska for women" "alaska jobs" "alaska jobs north slope" "alaska jobs pipeline" "alaska jobs for foreigners" ON http://jobsinalaska-usa.blogspot.com/ "jobs in alaska" "jobs in alaska for foreigners" "jobs in alaska oil" "jobs in alaska for women" "alaska jobs" "alaska jobs north slope" "alaska jobs pipeline" "alaska jobs for foreigners" ON http://jobsinalaska-usa.blogspot.com/ "jobs in alaska" "jobs in alaska for foreigners" "jobs in alaska oil" "jobs in alaska for women" "alaska jobs" "alaska jobs north slope" "alaska jobs pipeline" "alaska jobs for foreigners" ON http://jobsinalaska-usa.blogspot.com/ "jobs in alaska" "jobs in alaska for foreigners" "jobs in alaska oil" "jobs in alaska for women" "alaska jobs" "alaska jobs north slope" "alaska jobs pipeline" "alaska jobs for foreigners" ON http://jobsinalaska-usa.blogspot.com/ "jobs in alaska" "jobs in alaska for foreigners" "jobs in alaska oil" "jobs in alaska for women" "alaska jobs" "alaska jobs north slope" "alaska jobs pipeline" "alaska jobs for foreigners" ON http://jobsinalaska-usa.blogspot.com/ "jobs in alaska" "jobs in alaska for foreigners" "jobs in alaska oil" "jobs in alaska for women" "alaska jobs" "alaska jobs north slope" "alaska jobs pipeline" "alaska jobs for foreigners" ON http://jobsinalaska-usa.blogspot.com/ "jobs in alaska" "jobs in alaska for foreigners" "jobs in alaska oil" "jobs in alaska for women" "alaska jobs" "alaska jobs north slope" "alaska jobs pipeline" "alaska jobs for foreigners" ON http://jobsinalaska-usa.blogspot.com/ "jobs in alaska" "jobs in alaska for foreigners" "jobs in alaska oil" "jobs in alaska for women" "alaska jobs" "alaska jobs north slope" "alaska jobs pipeline" "alaska jobs for foreigners" ON http://jobsinalaska-usa.blogspot.com/ "jobs in alaska" "jobs in alaska for foreigners" "jobs in alaska oil" "jobs in alaska for women" "alaska jobs" "alaska jobs north slope" "alaska jobs pipeline" "alaska jobs for foreigners" ON http://jobsinalaska-usa.blogspot.com/ "jobs in alaska" "jobs in alaska for foreigners" "jobs in alaska oil" "jobs in alaska for women" "alaska jobs" "alaska jobs north slope" "alaska jobs pipeline" "alaska jobs for foreigners" ON http://jobsinalaska-usa.blogspot.com/ "jobs in alaska" "jobs in alaska for foreigners" "jobs in alaska oil" "jobs in alaska for women" "alaska jobs" "alaska jobs north slope" "alaska jobs pipeline" "alaska jobs for foreigners" ON http://jobsinalaska-usa.blogspot.com/ "jobs in alaska" "jobs in alaska for foreigners" "jobs in alaska oil" "jobs in alaska for women" "alaska jobs" "alaska jobs north slope" "alaska jobs pipeline" "alaska jobs for foreigners" ON http://jobsinalaska-usa.blogspot.com/ "jobs in alaska" "jobs in alaska for foreigners" "jobs in alaska oil" "jobs in alaska for women" "alaska jobs" "alaska jobs north slope" "alaska jobs pipeline" "alaska jobs for foreigners" ON http://jobsinalaska-usa.blogspot.com/ "jobs in alaska" "jobs in alaska for foreigners" "jobs in alaska oil" "jobs in alaska for women" "alaska jobs" "alaska jobs north slope" "alaska jobs pipeline" "alaska jobs for foreigners" ON http://jobsinalaska-usa.blogspot.com/ "jobs in alaska" "jobs in alaska for foreigners" "jobs in alaska oil" "jobs in alaska for women" "alaska jobs" "alaska jobs north slope" "alaska jobs pipeline" "alaska jobs for foreigners" ON http://jobsinalaska-usa.blogspot.com/ "jobs in alaska" "jobs in alaska for foreigners" "jobs in alaska oil" "jobs in alaska for women" "alaska jobs" "alaska jobs north slope" "alaska jobs pipeline" "alaska jobs for foreigners" ON http://jobsinalaska-usa.blogspot.com/ "jobs in alaska" "jobs in alaska for foreigners" "jobs in alaska oil" "jobs in alaska for women" "alaska jobs" "alaska jobs north slope" "alaska jobs pipeline" "alaska jobs for foreigners" ON http://jobsinalaska-usa.blogspot.com/ From steve at REMOVE-THIS-cybersource.com.au Sat Apr 3 02:17:37 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 03 Apr 2010 06:17:37 GMT Subject: C-style static variables in Python? References: <98947d50-6352-466b-aae6-35e7b4c8c5af@33g2000yqj.googlegroups.com> <89ef884c-eb30-4ca8-a292-d9bc17e8cd4f@z4g2000yqa.googlegroups.com> <4bb6844e$0$8827$c3e8da3@news.astraweb.com> Message-ID: <4bb6dd81$0$8827$c3e8da3@news.astraweb.com> On Fri, 02 Apr 2010 19:48:59 -0700, Ethan Furman wrote: >> The heuristic I use is, if I expect the try block to raise an exception >> more than about one time in ten, I change to an explicit test. In this >> case, since the exception should only be raised once, and then never >> again, I would use a try...except block. > > That was my reasoning as well, but when I timed it for one million runs > (so 1 instantiation, 999,999 simple calls), the __getattr__ time was .5 > seconds, the try...execpt block was .6; at ten million it was 5 and 6. Care to share your timing code? Not that I don't trust your results, but timings are very sensitive to the exact thing you do, and I'd like to see what that is. -- Steven From frank at chagford.com Sat Apr 3 02:25:26 2010 From: frank at chagford.com (Frank Millman) Date: Sat, 3 Apr 2010 08:25:26 +0200 Subject: Getting Local MAC Address References: Message-ID: "Booter" wrote in message news:ec6d247c-a6b0-4f33-a36b-1d33eace642f at k19g2000yqn.googlegroups.com... > Hello all, > > I am new to python ans was wondering if there was a way to get the mac > address from the local NIC? > > Thanks for your help. > > Gerad This is what I use - ------------------------ def get_mac_address(): if sys.platform == 'win32': for line in os.popen("ipconfig /all"): if line.lstrip().startswith('Physical Address'): mac = line.split(':')[1].strip().replace('-',':') break else: # mac = os.popen("/sbin/ifconfig|grep Ether|awk {'print $5'}").read()[:-1] for line in os.popen("/sbin/ifconfig"): if 'Ether' in line: mac = line.split()[4] break return mac ------------------------ I only target windows and linux. I don't know if it works for all platforms. I wrote this a long time ago. I think it would now be preferable to use subprocess() instead of os.popen(). Note the commented-out line in the linux block. This is an alternative method I cribbed from somewhere. Not as readable, but probably faster. HTH Frank Millman From ethan at stoneleaf.us Sat Apr 3 02:44:32 2010 From: ethan at stoneleaf.us (Ethan Furman) Date: Fri, 02 Apr 2010 23:44:32 -0700 Subject: C-style static variables in Python? In-Reply-To: <4bb6dd81$0$8827$c3e8da3@news.astraweb.com> References: <98947d50-6352-466b-aae6-35e7b4c8c5af@33g2000yqj.googlegroups.com> <89ef884c-eb30-4ca8-a292-d9bc17e8cd4f@z4g2000yqa.googlegroups.com> <4bb6844e$0$8827$c3e8da3@news.astraweb.com> <4bb6dd81$0$8827$c3e8da3@news.astraweb.com> Message-ID: <4BB6E3D0.709@stoneleaf.us> Steven D'Aprano wrote: > On Fri, 02 Apr 2010 19:48:59 -0700, Ethan Furman wrote: > > >>>The heuristic I use is, if I expect the try block to raise an exception >>>more than about one time in ten, I change to an explicit test. In this >>>case, since the exception should only be raised once, and then never >>>again, I would use a try...except block. >> >>That was my reasoning as well, but when I timed it for one million runs >>(so 1 instantiation, 999,999 simple calls), the __getattr__ time was .5 >>seconds, the try...execpt block was .6; at ten million it was 5 and 6. > > > Care to share your timing code? Not that I don't trust your results, but > timings are very sensitive to the exact thing you do, and I'd like to see > what that is. Happy to do so -- if I made a mistake I'd like to know about it and learn. It'll have to wait two days 'til I get back to work, though... I'll post it asap. ~Ethan~ From __peter__ at web.de Sat Apr 3 05:17:36 2010 From: __peter__ at web.de (Peter Otten) Date: Sat, 03 Apr 2010 11:17:36 +0200 Subject: Splitting a string References: <450895af-d8ec-4312-a31e-569e39aaa319@w17g2000yqj.googlegroups.com> <737b6e81-71ef-430d-b5e7-dffdf1569fd7@g30g2000yqc.googlegroups.com> Message-ID: Patrick Maupin wrote: > On Apr 2, 4:32 pm, Peter Otten <__pete... at web.de> wrote: > >> _split = re.compile(r"(\d+)").split >> def split(s): >> if not s: >> return () >> parts = _split(s) >> parts[1::2] = map(int, parts[1::2]) # because s is non-empty parts contains at least one # item != "", and parts[x] below cannot fail with an # IndexError >> if parts[-1] == "": >> del parts[-1] >> if parts[0] == "": >> del parts[0] >> return tuple(parts) >> > > That's certainly faster than a list comprehension (at least on long > lists), but it might be a little obscure why the "if not s:" is > needed, The function is small; with a test suite covering the corner cases and perhaps a comment* nothing should go wrong. (*) you can certainly improve on my attempt > so unless Thomas has a really long result list, he might want > to just keep the list comprehension, which is (IMO) very readable. Generally speaking performing tests of which you know they can't fail can confuse the reader just as much as tests with unobvious interdependencies. > Alternatively, this is halfway between the previous example and the > list comprehension: > > _split = re.compile(r"(\d+)").split > def split(s): > parts = _split(s) > parts[1::2] = map(int, parts[1::2]) > for index in (-1, 0): > if parts and parts[index] == "": > del parts[index] > return tuple(parts) I don't think that this is similar to the list comprehension approach because it only tests the first and the last item instead of the whole list. Both variants should therefore perform equally well for all but the empty string argument. If that is a theoretical case you are free to choose the more readable variant. Peter From lie.1296 at gmail.com Sat Apr 3 06:10:19 2010 From: lie.1296 at gmail.com (Lie Ryan) Date: Sat, 03 Apr 2010 21:10:19 +1100 Subject: How to run python without python In-Reply-To: <87wrwpodx8.fsf@castleamber.com> References: <1270164976.6418.4.camel@spencer-laptop> <488f5290-38f0-4f4e-8e75-f0271458b2b0@q16g2000yqq.googlegroups.com> <87wrwpodx8.fsf@castleamber.com> Message-ID: <4bb7143f@dnews.tpgi.com.au> On 04/03/10 06:24, John Bokma wrote: >> >> you think virtualbox could help? i wonder if one could run linux/ >> py2exe virtually on a win machine and get it working. > > Of course that works, a virtual windows machine is just a windows > machine ;-). > > Also that you can't do a "cross compilation" sounds to me more a > limitation of the tool than a true impossibility. Much like me writing French... From alain at dpt-info.u-strasbg.fr Sat Apr 3 06:30:32 2010 From: alain at dpt-info.u-strasbg.fr (Alain Ketterlin) Date: Sat, 03 Apr 2010 12:30:32 +0200 Subject: Incorrect scope of list comprehension variables Message-ID: <87hbnsg75j.fsf@dpt-info.u-strasbg.fr> Hi all, I've just spent a few hours debugging code similar to this: d = dict() for r in [1,2,3]: d[r] = [r for r in [4,5,6]] print d THe problem is that the "r" in d[r] somehow captures the value of the "r" in the list comprehension, and somehow kills the loop interator. The (unexpected) result is {6: [4, 5, 6]}. Changing r to s inside the list leads to the correct (imo) result. Is this expected? Is this a known problem? Is it solved in newer versions? This is python 2.6.4, on a stock ubuntu 9.10 x86-64 linux box. Let me know if more detail is needed. Thanks in advance. -- Alain. From clp2 at rebertia.com Sat Apr 3 06:53:57 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Sat, 3 Apr 2010 03:53:57 -0700 Subject: Incorrect scope of list comprehension variables In-Reply-To: <87hbnsg75j.fsf@dpt-info.u-strasbg.fr> References: <87hbnsg75j.fsf@dpt-info.u-strasbg.fr> Message-ID: On Sat, Apr 3, 2010 at 3:30 AM, Alain Ketterlin wrote: > I've just spent a few hours debugging code similar to this: > > d = dict() > for r in [1,2,3]: > ? ?d[r] = [r for r in [4,5,6]] > print d > > THe problem is that the "r" in d[r] somehow captures the value of the > "r" in the list comprehension, and somehow kills the loop interator. The > (unexpected) result is {6: [4, 5, 6]}. Changing r to s inside the list > leads to the correct (imo) result. > > Is this expected? Is this a known problem? Is it solved in newer > versions? Quoting http://docs.python.org/reference/expressions.html#id19 : Footnotes [1] In Python 2.3 and later releases, a list comprehension ?leaks? the control variables of each 'for' it contains into the containing scope. However, this behavior is deprecated, and relying on it will not work in Python 3.0 Cheers, Chris -- http://blog.rebertia.com From steve at REMOVE-THIS-cybersource.com.au Sat Apr 3 08:43:37 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 03 Apr 2010 12:43:37 GMT Subject: Incorrect scope of list comprehension variables References: <87hbnsg75j.fsf@dpt-info.u-strasbg.fr> Message-ID: <4bb737f8$0$8827$c3e8da3@news.astraweb.com> On Sat, 03 Apr 2010 12:30:32 +0200, Alain Ketterlin wrote: > Hi all, > > I've just spent a few hours debugging code similar to this: > > d = dict() > for r in [1,2,3]: > d[r] = [r for r in [4,5,6]] > print d This isn't directly relevant to your problem, but why use a list comprehension in the first place? [r for r in [4,5,6]] is just [4,5,6], only slower. I presume that is just a stand-in for a more useful list comp, but I mention it because I have seen people do exactly that, in real code, without knowing any better. (I may have even done so myself, once or twice.) > THe problem is that the "r" in d[r] somehow captures the value of the > "r" in the list comprehension, and somehow kills the loop interator. The > (unexpected) result is {6: [4, 5, 6]}. Actually, no it doesn't kill the loop at all. You have misinterpreted what you have seen: >>> d = dict() >>> for r in [1,2,3]: ... print r ... d[r] = [r for r in [4,5,6]] ... print d ... 1 {6: [4, 5, 6]} 2 {6: [4, 5, 6]} 3 {6: [4, 5, 6]} > Changing r to s inside the list > leads to the correct (imo) result. > > Is this expected? Is this a known problem? Is it solved in newer > versions? Yes, yes and yes. It is expected, because list comprehensions leak the variable into the enclosing scope. Yes, it is a problem, as you have found, although frankly it is easy enough to make sure your list comp variable has a unique name. And yes, it is fixed in Python 3.1. -- Steven From cournape at gmail.com Sat Apr 3 08:57:34 2010 From: cournape at gmail.com (David Cournapeau) Date: Sat, 3 Apr 2010 21:57:34 +0900 Subject: How to run python without python In-Reply-To: References: <1270164976.6418.4.camel@spencer-laptop> Message-ID: On Sat, Apr 3, 2010 at 2:23 AM, Chris Rebert wrote: > On Fri, Apr 2, 2010 at 10:09 AM, danmcleran at yahoo.com > wrote: >> On Apr 1, 5:54?pm, Chris Rebert wrote: >>> On Thu, Apr 1, 2010 at 4:46 PM, Krister Svanlund >>> wrote: >>> > On Fri, Apr 2, 2010 at 1:36 AM, Spencer wrote: >>> >> Is there a way to developing a script on linux and give it >>> >> to someone on microsoft, so that they could run it on microsoft >>> >> without installing python? > >>> one can't generate such a standalone executable for a different >>> operating system from that which one's computer runs. >> >> that's not entirely true. i just built a standalone exe for win 7 from >> my win xp machine. > > s/operating system/platform > > Good luck getting PyInstaller to output for Windows when being run on > a *nix box. Doesn't py2exe works under wine ? I have had great success building windows installers on linux through wine (although not with py2exe), cheers, David From utente at esempio.net Sat Apr 3 09:00:59 2010 From: utente at esempio.net (superpollo) Date: Sat, 03 Apr 2010 15:00:59 +0200 Subject: off topic but please forgive me me and answer In-Reply-To: References: <4bb505c5$0$1133$4fafbaef@reader3.news.tin.it> <20100402214110.00a63457@geekmail.INVALID> Message-ID: <4bb73c0b$0$1125$4fafbaef@reader3.news.tin.it> Patrick Maupin ha scritto: > On Apr 2, 2:41 pm, Andreas Waldenburger > wrote: > >> While everyone else is mocking you: Can you please elaborate on why you >> want to know and what kind of problem you're trying to solve with this? >> Also, don't you think you should have picked a maths forum for this >> kind of question? > > Methinks the OP is fluent in the way of choosing newsgroups. > According to google, he has posted 6855 messages in 213 groups. > > http://groups.google.com/groups/profile?enc_user=ul3SQhIAAAAYmLD0Oj5Yxp-liP3Vw9uApbyajUBv9M9XLUB2gqkZmQ > > And I can't speak for anybody else, but I just assumed it was an April > Fool's question. I meant to be laughing with the OP, not at him, so > sorry if I misunderstood. no no you understood prfectly *but* the thing is i am a regular in an italian language math ng which is haunted by a crackpot who insists that 1/2 * 1/2 cannot be 1/4, "because multiplication means getting bigger", so i took a semi-serious stance and made a few posts as a statistical tentative to "convince" said crackpot that the world is not going crazy (but maybe he is) thanks ps: note that my nickname is not unique, and there are a few people whith the same one... and i didn't ever post using googlegroups From mensanator at aol.com Sat Apr 3 09:37:00 2010 From: mensanator at aol.com (Mensanator) Date: Sat, 3 Apr 2010 06:37:00 -0700 (PDT) Subject: off topic but please forgive me me and answer References: <4bb505c5$0$1133$4fafbaef@reader3.news.tin.it> <20100402214110.00a63457@geekmail.INVALID> <4bb73c0b$0$1125$4fafbaef@reader3.news.tin.it> Message-ID: <671519eb-fcb0-446d-962a-87475df673e4@q23g2000yqd.googlegroups.com> On Apr 3, 8:00?am, superpollo wrote: > Patrick Maupin ha scritto: > > > > > > > On Apr 2, 2:41 pm, Andreas Waldenburger > > wrote: > > >> While everyone else is mocking you: Can you please elaborate on why you > >> want to know and what kind of problem you're trying to solve with this? > >> Also, don't you think you should have picked a maths forum for this > >> kind of question? > > > Methinks the OP is fluent in the way of choosing newsgroups. > > According to google, he has posted 6855 messages in 213 groups. > > >http://groups.google.com/groups/profile?enc_user=ul3SQhIAAAAYmLD0Oj5Y... > > > And I can't speak for anybody else, but I just assumed it was an April > > Fool's question. ?I meant to be laughing with the OP, not at him, so > > sorry if I misunderstood. > > no no you understood prfectly *but* the thing is i am a regular in an > italian language math ng which is haunted by a crackpot who insists that > 1/2 * 1/2 cannot be 1/4, "because multiplication means getting bigger", > so i took a semi-serious stance and made a few posts as a statistical > tentative to "convince" said crackpot that the world is not going crazy > (but maybe he is) I seriously doubt your crackpot friend actually believes that. Probably more troll than crackpot. Showing him articles and programs that prove your premise will accomplish nothing. However, if you personally wanted information on programming with rational numbers, you came to the right place. > > thanks > > ps: note that my nickname is not unique, and there are a few people > whith the same one... and i didn't ever post using googlegroups What does it mean, "super chicken? From steve at holdenweb.com Sat Apr 3 09:38:11 2010 From: steve at holdenweb.com (Steve Holden) Date: Sat, 03 Apr 2010 09:38:11 -0400 Subject: off topic but please forgive me me and answer In-Reply-To: <4bb73c0b$0$1125$4fafbaef@reader3.news.tin.it> References: <4bb505c5$0$1133$4fafbaef@reader3.news.tin.it> <20100402214110.00a63457@geekmail.INVALID> <4bb73c0b$0$1125$4fafbaef@reader3.news.tin.it> Message-ID: superpollo wrote: > Patrick Maupin ha scritto: >> On Apr 2, 2:41 pm, Andreas Waldenburger >> wrote: >> >>> While everyone else is mocking you: Can you please elaborate on why you >>> want to know and what kind of problem you're trying to solve with this? >>> Also, don't you think you should have picked a maths forum for this >>> kind of question? >> >> Methinks the OP is fluent in the way of choosing newsgroups. >> According to google, he has posted 6855 messages in 213 groups. >> >> http://groups.google.com/groups/profile?enc_user=ul3SQhIAAAAYmLD0Oj5Yxp-liP3Vw9uApbyajUBv9M9XLUB2gqkZmQ >> >> >> And I can't speak for anybody else, but I just assumed it was an April >> Fool's question. I meant to be laughing with the OP, not at him, so >> sorry if I misunderstood. > > no no you understood prfectly *but* the thing is i am a regular in an > italian language math ng which is haunted by a crackpot who insists that > 1/2 * 1/2 cannot be 1/4, "because multiplication means getting bigger", > so i took a semi-serious stance and made a few posts as a statistical > tentative to "convince" said crackpot that the world is not going crazy > (but maybe he is) > > thanks > > ps: note that my nickname is not unique, and there are a few people > whith the same one... and i didn't ever post using googlegroups If you think you will persuade a crackpot to drop his lunacy by logical argument you are clearly an optimist of the first water. But since I like a challenge (and bearing in mind this is OT so I don't claim to be an expert) you might try first of all persuading him to agree to the commutativity of multiplication (i.e. x * y == y * x for any x and y). If he agrees to that, then get him to agree that x * 1 == x for any x. If he agrees to that, then set x = 1/2 and see if he'll agree that 1/2 * 1 == 1/2. If he does, then surely he must also agree that 1 * 1/2 == 1/2, i.e. multiplication can indeed "make things smaller". Good luck, though. Crackpots aren't generally responsive to appeals to rational thinking. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 See PyCon Talks from Atlanta 2010 http://pycon.blip.tv/ Holden Web LLC http://www.holdenweb.com/ UPCOMING EVENTS: http://holdenweb.eventbrite.com/ From utente at esempio.net Sat Apr 3 10:26:24 2010 From: utente at esempio.net (superpollo) Date: Sat, 03 Apr 2010 16:26:24 +0200 Subject: off topic but please forgive me me and answer In-Reply-To: References: <4bb505c5$0$1133$4fafbaef@reader3.news.tin.it> <20100402214110.00a63457@geekmail.INVALID> <4bb73c0b$0$1125$4fafbaef@reader3.news.tin.it> Message-ID: <4bb75011$0$1134$4fafbaef@reader3.news.tin.it> Steve Holden ha scritto: > superpollo wrote: >> Patrick Maupin ha scritto: >>> On Apr 2, 2:41 pm, Andreas Waldenburger >>> wrote: >>> >>>> While everyone else is mocking you: Can you please elaborate on why you >>>> want to know and what kind of problem you're trying to solve with this? >>>> Also, don't you think you should have picked a maths forum for this >>>> kind of question? >>> Methinks the OP is fluent in the way of choosing newsgroups. >>> According to google, he has posted 6855 messages in 213 groups. >>> >>> http://groups.google.com/groups/profile?enc_user=ul3SQhIAAAAYmLD0Oj5Yxp-liP3Vw9uApbyajUBv9M9XLUB2gqkZmQ >>> >>> >>> And I can't speak for anybody else, but I just assumed it was an April >>> Fool's question. I meant to be laughing with the OP, not at him, so >>> sorry if I misunderstood. >> no no you understood prfectly *but* the thing is i am a regular in an >> italian language math ng which is haunted by a crackpot who insists that >> 1/2 * 1/2 cannot be 1/4, "because multiplication means getting bigger", >> so i took a semi-serious stance and made a few posts as a statistical >> tentative to "convince" said crackpot that the world is not going crazy >> (but maybe he is) >> >> thanks >> >> ps: note that my nickname is not unique, and there are a few people >> whith the same one... and i didn't ever post using googlegroups > > If you think you will persuade a crackpot to drop his lunacy by logical > argument you are clearly an optimist of the first water. But since I > like a challenge (and bearing in mind this is OT so I don't claim to be > an expert) you might try first of all persuading him to agree to the > commutativity of multiplication (i.e. x * y == y * x for any x and y). > > If he agrees to that, then get him to agree that x * 1 == x for any x. > > If he agrees to that he does not, since "you cannot multiply something, and not getting some more of it" ... he is stuck with the latin etimology of "multiply" ("multiplicare" means "increase quantity", like in the fish and bread miracle) From utente at esempio.net Sat Apr 3 10:28:21 2010 From: utente at esempio.net (superpollo) Date: Sat, 03 Apr 2010 16:28:21 +0200 Subject: off topic but please forgive me me and answer In-Reply-To: <671519eb-fcb0-446d-962a-87475df673e4@q23g2000yqd.googlegroups.com> References: <4bb505c5$0$1133$4fafbaef@reader3.news.tin.it> <20100402214110.00a63457@geekmail.INVALID> <4bb73c0b$0$1125$4fafbaef@reader3.news.tin.it> <671519eb-fcb0-446d-962a-87475df673e4@q23g2000yqd.googlegroups.com> Message-ID: <4bb75085$0$1134$4fafbaef@reader3.news.tin.it> Mensanator ha scritto: > On Apr 3, 8:00 am, superpollo wrote: >> Patrick Maupin ha scritto: >> >> >> >> >> >>> On Apr 2, 2:41 pm, Andreas Waldenburger >>> wrote: >>>> While everyone else is mocking you: Can you please elaborate on why you >>>> want to know and what kind of problem you're trying to solve with this? >>>> Also, don't you think you should have picked a maths forum for this >>>> kind of question? >>> Methinks the OP is fluent in the way of choosing newsgroups. >>> According to google, he has posted 6855 messages in 213 groups. >>> http://groups.google.com/groups/profile?enc_user=ul3SQhIAAAAYmLD0Oj5Y... >>> And I can't speak for anybody else, but I just assumed it was an April >>> Fool's question. I meant to be laughing with the OP, not at him, so >>> sorry if I misunderstood. >> no no you understood prfectly *but* the thing is i am a regular in an >> italian language math ng which is haunted by a crackpot who insists that >> 1/2 * 1/2 cannot be 1/4, "because multiplication means getting bigger", >> so i took a semi-serious stance and made a few posts as a statistical >> tentative to "convince" said crackpot that the world is not going crazy >> (but maybe he is) > > I seriously doubt your crackpot friend actually believes that. > Probably more troll than crackpot. Showing him articles and > programs that prove your premise will accomplish nothing. probably so, but you cannot imagine the traffic he generates... > However, if you personally wanted information on programming > with rational numbers, you came to the right place. > >> thanks >> >> ps: note that my nickname is not unique, and there are a few people >> whith the same one... and i didn't ever post using googlegroups > > What does it mean, "super chicken? yea! http://www.renegadechickens.com/chickens/Toons/superchicken.gif From mrabarnett at mrabarnett.plus.com Sat Apr 3 10:38:32 2010 From: mrabarnett at mrabarnett.plus.com (Matthew Barnett) Date: Sat, 03 Apr 2010 15:38:32 +0100 Subject: off topic but please forgive me me and answer In-Reply-To: <4bb75011$0$1134$4fafbaef@reader3.news.tin.it> References: <4bb505c5$0$1133$4fafbaef@reader3.news.tin.it> <20100402214110.00a63457@geekmail.INVALID> <4bb73c0b$0$1125$4fafbaef@reader3.news.tin.it> <4bb75011$0$1134$4fafbaef@reader3.news.tin.it> Message-ID: <4BB752E8.8010406@mrabarnett.plus.com> superpollo wrote: > Steve Holden ha scritto: >> superpollo wrote: >>> Patrick Maupin ha scritto: >>>> On Apr 2, 2:41 pm, Andreas Waldenburger >>>> wrote: >>>> >>>>> While everyone else is mocking you: Can you please elaborate on why >>>>> you >>>>> want to know and what kind of problem you're trying to solve with >>>>> this? >>>>> Also, don't you think you should have picked a maths forum for this >>>>> kind of question? >>>> Methinks the OP is fluent in the way of choosing newsgroups. >>>> According to google, he has posted 6855 messages in 213 groups. >>>> >>>> http://groups.google.com/groups/profile?enc_user=ul3SQhIAAAAYmLD0Oj5Yxp-liP3Vw9uApbyajUBv9M9XLUB2gqkZmQ >>>> >>>> >>>> >>>> And I can't speak for anybody else, but I just assumed it was an April >>>> Fool's question. I meant to be laughing with the OP, not at him, so >>>> sorry if I misunderstood. >>> no no you understood prfectly *but* the thing is i am a regular in an >>> italian language math ng which is haunted by a crackpot who insists that >>> 1/2 * 1/2 cannot be 1/4, "because multiplication means getting bigger", >>> so i took a semi-serious stance and made a few posts as a statistical >>> tentative to "convince" said crackpot that the world is not going crazy >>> (but maybe he is) >>> >>> thanks >>> >>> ps: note that my nickname is not unique, and there are a few people >>> whith the same one... and i didn't ever post using googlegroups >> >> If you think you will persuade a crackpot to drop his lunacy by logical >> argument you are clearly an optimist of the first water. But since I >> like a challenge (and bearing in mind this is OT so I don't claim to be >> an expert) you might try first of all persuading him to agree to the >> commutativity of multiplication (i.e. x * y == y * x for any x and y). >> >> If he agrees to that, then get him to agree that x * 1 == x for any x. >> >> If he agrees to that > > he does not, since "you cannot multiply something, and not getting some > more of it" ... he is stuck with the latin etimology of "multiply" > ("multiplicare" means "increase quantity", like in the fish and bread > miracle) > Do he also think that division always makes it smaller? What about division by a half? From steve at holdenweb.com Sat Apr 3 10:43:25 2010 From: steve at holdenweb.com (Steve Holden) Date: Sat, 03 Apr 2010 10:43:25 -0400 Subject: off topic but please forgive me me and answer In-Reply-To: <4bb75011$0$1134$4fafbaef@reader3.news.tin.it> References: <4bb505c5$0$1133$4fafbaef@reader3.news.tin.it> <20100402214110.00a63457@geekmail.INVALID> <4bb73c0b$0$1125$4fafbaef@reader3.news.tin.it> <4bb75011$0$1134$4fafbaef@reader3.news.tin.it> Message-ID: superpollo wrote: > Steve Holden ha scritto: [...] >> If he agrees to that, then get him to agree that x * 1 == x for any x. >> >> If he agrees to that > > he does not, since "you cannot multiply something, and not getting some > more of it" ... he is stuck with the latin etimology of "multiply" > ("multiplicare" means "increase quantity", like in the fish and bread > miracle) > Ah, so he's talking semantics, not mathematics. Absolutely no point expecting agreement on a common sense basis, then. Particularly when he takes such a narrow-minded view. In short, he has his head up his ass. Would he agree that two halves make a whole? If so, he appears to deny the commutativity of multiplication. Such people are amusing for the first ten minutes, but I am sure he has managed to bore everyone to death by now. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 See PyCon Talks from Atlanta 2010 http://pycon.blip.tv/ Holden Web LLC http://www.holdenweb.com/ UPCOMING EVENTS: http://holdenweb.eventbrite.com/ From martin.hellwig at dcuktec.org Sat Apr 3 10:43:41 2010 From: martin.hellwig at dcuktec.org (Martin P. Hellwig) Date: Sat, 03 Apr 2010 15:43:41 +0100 Subject: off topic but please forgive me me and answer In-Reply-To: References: <4bb505c5$0$1133$4fafbaef@reader3.news.tin.it> <20100402214110.00a63457@geekmail.INVALID> <4bb73c0b$0$1125$4fafbaef@reader3.news.tin.it> Message-ID: On 04/03/10 14:38, Steve Holden wrote: > > If you think you will persuade a crackpot to drop his lunacy by logical > argument you are clearly an optimist of the first water. But since I > like a challenge (and bearing in mind this is OT so I don't claim to be > an expert) you might try first of all persuading him to agree to the > commutativity of multiplication (i.e. x * y == y * x for any x and y). > > If he agrees to that, then get him to agree that x * 1 == x for any x. > > If he agrees to that, then set x = 1/2 and see if he'll agree that 1/2 * > 1 == 1/2. > > If he does, then surely he must also agree that 1 * 1/2 == 1/2, i.e. > multiplication can indeed "make things smaller". > > Good luck, though. Crackpots aren't generally responsive to appeals to > rational thinking. > I am replying to this post not because I disagree but because it postalogically fits the best (I am by no means an expert either). IMHO, the crackpot in this regard is actually partially right, multiplication does mean that the number must get bigger, however for fractions you multiply four numbers, two numerators and two denominators. The resulting numerator and denominator by this multiplication get indeed bigger. -- mph From steve at REMOVE-THIS-cybersource.com.au Sat Apr 3 11:17:05 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 03 Apr 2010 15:17:05 GMT Subject: off topic but please forgive me me and answer References: <4bb505c5$0$1133$4fafbaef@reader3.news.tin.it> <20100402214110.00a63457@geekmail.INVALID> <4bb73c0b$0$1125$4fafbaef@reader3.news.tin.it> Message-ID: <4bb75bea$0$27790$c3e8da3@news.astraweb.com> On Sat, 03 Apr 2010 15:43:41 +0100, Martin P. Hellwig wrote: > I am replying to this post not because I disagree but because it > postalogically fits the best (I am by no means an expert either). > > IMHO, the crackpot in this regard is actually partially right, > multiplication does mean that the number must get bigger, however for > fractions you multiply four numbers, two numerators and two > denominators. The resulting numerator and denominator by this > multiplication get indeed bigger. But you're not multiplying four numbers, you're multiplying two numbers. One-half is not "two numbers", that would be a tuple or a list or possibly a coordinate pair. One-half is a single number, the number which if you double it gives one. Fortunately multiplication is consistent. Multiplying the two numbers 0.5 and 0.5 is exactly the same as multiplying 1*1 and 2*2 then dividing to get a single number. It's not the same as multiplying 1*1 and 2*2 to get two numbers, 1 and 4. You say that multiplication means that the number "must get bigger". 5*1 = 5 5*0 = 0 5*-2 = -10 I hope you won't try to argue that 5, 0 and -10 are all bigger than 5. There really is no point trying to dignify superpollo's friend's assertion on the basis of some technicality. His argument is no different from the argument that says that pythons are snakes, and therefore python can't be a programming language and this newsgroup can't possibly exist. Words can have multiple meanings, and meanings can shift. Multiply may be derived from a word which, once upon a time, meant to get bigger, but that's not what multiply means. I don't like to dismiss somebody I've never met, but on the basis of what superpollo says, yes, he's a crackpot. Either that or about age four. When I was four I strongly believed that "one hundred" and "a hundred" were different numbers. I argued (not very convincingly, but with great vehemence) to my teacher and my parents that you counted up to ninety-nine, then a hundred, a hundred and one, a hundred and two, ... a hundred and ninety-nine, *one* hundred. -- Steven From pmaupin at gmail.com Sat Apr 3 11:46:57 2010 From: pmaupin at gmail.com (Patrick Maupin) Date: Sat, 3 Apr 2010 08:46:57 -0700 (PDT) Subject: off topic but please forgive me me and answer References: <4bb505c5$0$1133$4fafbaef@reader3.news.tin.it> <20100402214110.00a63457@geekmail.INVALID> <4bb73c0b$0$1125$4fafbaef@reader3.news.tin.it> Message-ID: On Apr 3, 9:43?am, "Martin P. Hellwig" > IMHO, the crackpot in this regard is actually partially right, > multiplication does mean that the number must get bigger, however for > fractions you multiply four numbers, two numerators and two > denominators. The resulting numerator and denominator by this > multiplication get indeed bigger. That argument is great! Just make sure that you've managed to leave before the class has to learn about irrational numbers that don't *have* numerators and denominators ;-) From pmaupin at gmail.com Sat Apr 3 11:49:45 2010 From: pmaupin at gmail.com (Patrick Maupin) Date: Sat, 3 Apr 2010 08:49:45 -0700 (PDT) Subject: off topic but please forgive me me and answer References: <4bb505c5$0$1133$4fafbaef@reader3.news.tin.it> <20100402214110.00a63457@geekmail.INVALID> <4bb73c0b$0$1125$4fafbaef@reader3.news.tin.it> Message-ID: On Apr 3, 8:00?am, superpollo wrote: > > sorry if I misunderstood. > > no no you understood prfectly *but* the thing is i am a regular in an > italian language math ng which is haunted by a crackpot who insists that > 1/2 * 1/2 cannot be 1/4, "because multiplication means getting bigger", > so i took a semi-serious stance and made a few posts as a statistical > tentative to "convince" said crackpot that the world is not going crazy > (but maybe he is) If I read correctly (using my non-existent Italian, and heavily relying on my tiny bit of Spanish and a lot of google translate), it appears that you are what I would call a high-school math/science teacher, who takes students to competitions? Regards, Pat From utente at esempio.net Sat Apr 3 11:56:59 2010 From: utente at esempio.net (superpollo) Date: Sat, 03 Apr 2010 17:56:59 +0200 Subject: off topic but please forgive me me and answer In-Reply-To: References: <4bb505c5$0$1133$4fafbaef@reader3.news.tin.it> <20100402214110.00a63457@geekmail.INVALID> <4bb73c0b$0$1125$4fafbaef@reader3.news.tin.it> Message-ID: <4bb7654b$0$1127$4fafbaef@reader3.news.tin.it> Patrick Maupin ha scritto: > On Apr 3, 8:00 am, superpollo wrote: >>> sorry if I misunderstood. >> no no you understood prfectly *but* the thing is i am a regular in an >> italian language math ng which is haunted by a crackpot who insists that >> 1/2 * 1/2 cannot be 1/4, "because multiplication means getting bigger", >> so i took a semi-serious stance and made a few posts as a statistical >> tentative to "convince" said crackpot that the world is not going crazy >> (but maybe he is) > > If I read correctly (using my non-existent Italian, and heavily > relying on my tiny bit of Spanish and a lot of google translate), it > appears that you are what I would call a high-school math/science > teacher, who takes students to competitions? right -- almost! i don't take them to competitions (i am not an official trainer) but sometimes give some general advice to students who would be inclined to compete, if they ask me. bye From martin.hellwig at dcuktec.org Sat Apr 3 11:57:38 2010 From: martin.hellwig at dcuktec.org (Martin P. Hellwig) Date: Sat, 03 Apr 2010 16:57:38 +0100 Subject: off topic but please forgive me me and answer In-Reply-To: <4bb75bea$0$27790$c3e8da3@news.astraweb.com> References: <4bb505c5$0$1133$4fafbaef@reader3.news.tin.it> <20100402214110.00a63457@geekmail.INVALID> <4bb73c0b$0$1125$4fafbaef@reader3.news.tin.it> <4bb75bea$0$27790$c3e8da3@news.astraweb.com> Message-ID: On 04/03/10 16:17, Steven D'Aprano wrote: > On Sat, 03 Apr 2010 15:43:41 +0100, Martin P. Hellwig wrote: > >> I am replying to this post not because I disagree but because it >> postalogically fits the best (I am by no means an expert either). >> >> IMHO, the crackpot in this regard is actually partially right, >> multiplication does mean that the number must get bigger, however for >> fractions you multiply four numbers, two numerators and two >> denominators. The resulting numerator and denominator by this >> multiplication get indeed bigger. > > But you're not multiplying four numbers, you're multiplying two numbers. > One-half is not "two numbers", that would be a tuple or a list or > possibly a coordinate pair. One-half is a single number, the number which > if you double it gives one. > I disagree with you there, but I only disagree with you on the definition of the syntax, not with the logic nor the explanation. I am not going to argue about syntax, since I don't think I would make a great argument (being the devil's advocate) and also because I believe when argued correctly, agreeing on disagreement of syntax allows even the greatest untruth be true and false at the same time. Excuse me please I need to feed Schroedinger's cat :-) -- mph From pmaupin at gmail.com Sat Apr 3 12:01:20 2010 From: pmaupin at gmail.com (Patrick Maupin) Date: Sat, 3 Apr 2010 09:01:20 -0700 (PDT) Subject: Splitting a string References: <450895af-d8ec-4312-a31e-569e39aaa319@w17g2000yqj.googlegroups.com> <737b6e81-71ef-430d-b5e7-dffdf1569fd7@g30g2000yqc.googlegroups.com> Message-ID: On Apr 3, 4:17?am, Peter Otten <__pete... at web.de> wrote: > Patrick Maupin wrote: > > On Apr 2, 4:32 pm, Peter Otten <__pete... at web.de> wrote: > > >> _split = re.compile(r"(\d+)").split > >> def split(s): > >> ? ? if not s: > >> ? ? ? ? return () > >> ? ? parts = _split(s) > >> ? ? parts[1::2] = map(int, parts[1::2]) > > ? ? ? ?# because s is non-empty parts contains at least one > ? ? ? ?# item != "", and parts[x] below cannot fail with an > ? ? ? ?# IndexError > > >> ? ? if parts[-1] == "": > >> ? ? ? ? del parts[-1] > >> ? ? if parts[0] == "": > >> ? ? ? ? del parts[0] > >> ? ? return tuple(parts) > > > That's certainly faster than a list comprehension (at least on long > > lists), but it might be a little obscure why the "if not s:" is > > needed, > > The function is small; with a test suite covering the corner cases and > perhaps a comment* nothing should go wrong. > > (*) you can certainly improve on my attempt > > > so unless Thomas has a really long result list, he might want > > to just keep the list comprehension, which is (IMO) very readable. > > Generally speaking performing tests of which you know they can't fail can > confuse the reader just as much as tests with unobvious interdependencies. Yes, I see your point. The list comprehension will only treat the ends differently, and will always pass the middle, so someone could be confused about why the comprehension is there in the first place. I guess I'm used to doing this same thing on lists that *could* have empty strings in the middle (with more complicated regular expressions with multiple match cases), so I didn't consider that. > > Alternatively, this is halfway between the previous example and the > > list comprehension: > > > _split = re.compile(r"(\d+)").split > > def split(s): > > ? ? parts = _split(s) > > ? ? parts[1::2] = map(int, parts[1::2]) > > ? ? for index in (-1, 0): > > ? ? ? ? if parts and parts[index] == "": > > ? ? ? ? ? ? del parts[index] > > ? ? return tuple(parts) > > I don't think that this is similar to the list comprehension approach > because it only tests the first and the last item instead of the whole list. > Both variants should therefore perform equally well for all but the empty > string argument. If that is a theoretical case you are free to choose the > more readable variant. I agree that "halfway" was not a very precise way of describing the differences. Like your solution, this only tests the outer elements. Like the list comprehension, no short-circuit test before doing the re.split is required. Also like the list comprehension, the act of doing the same operation on multiple elements is refactored such that operation is only coded once. BUT... All of this is just a user preference, and is extremely minor compared to the observation that re.split() and extended string slicing can be combined to give a very elegant solution to the problem! Regards, Pat From mcanjo at gmail.com Sat Apr 3 12:09:52 2010 From: mcanjo at gmail.com (mcanjo) Date: Sat, 3 Apr 2010 09:09:52 -0700 (PDT) Subject: passing command line arguments to executable Message-ID: <4a636ae6-d68a-4b34-8e3f-9c11aa352793@g11g2000yqe.googlegroups.com> I have an executable (I don't have access to the source code) that processes some data. I double click on the icon and a Command prompt window pops up. The program asks me for the input file, I hit enter, and then it asks me for and output filename, I hit enter a second time and it goes off and does its thing and when it is finished running the Command Prompt goes away and I have my new output file in the same directory as my executable and input file. I would like to be able to batch process a group of files. I thought about using "os.spawnv()" in a loop and at each iteration of the loop passing in the file in and out names but that didn't work. Does anyone have any ideas? From pmaupin at gmail.com Sat Apr 3 12:15:26 2010 From: pmaupin at gmail.com (Patrick Maupin) Date: Sat, 3 Apr 2010 09:15:26 -0700 (PDT) Subject: passing command line arguments to executable References: <4a636ae6-d68a-4b34-8e3f-9c11aa352793@g11g2000yqe.googlegroups.com> Message-ID: <5d3a56da-aab2-4715-b288-1c9de47c9ece@k13g2000yqe.googlegroups.com> On Apr 3, 11:09?am, mcanjo wrote: > I have an executable (I don't have access to the source code) that > processes some data. I double click on the icon and a Command prompt > window pops up. The program asks me for the input file, I hit enter, > and then it asks me for and output filename, I hit enter a second time > and it goes off and does its thing and when it is finished running the > Command Prompt goes away and I have my new output file in the same > directory as my executable and input file. I would like to be able to > batch process a group of files. I thought about using "os.spawnv()" in > a loop and at each iteration of the loop passing in the file in and > out names but that didn't work. Does anyone have any ideas? You need to look at the subprocess module, and use pipes. Regards, Pat From simon at brunningonline.net Sat Apr 3 12:22:31 2010 From: simon at brunningonline.net (Simon Brunning) Date: Sat, 3 Apr 2010 17:22:31 +0100 Subject: passing command line arguments to executable In-Reply-To: <4a636ae6-d68a-4b34-8e3f-9c11aa352793@g11g2000yqe.googlegroups.com> References: <4a636ae6-d68a-4b34-8e3f-9c11aa352793@g11g2000yqe.googlegroups.com> Message-ID: On 3 April 2010 17:09, mcanjo wrote: > I have an executable (I don't have access to the source code) that > processes some data. I double click on the icon and a Command prompt > window pops up. The program asks me for the input file, I hit enter, > and then it asks me for and output filename, I hit enter a second time > and it goes off and does its thing and when it is finished running the > Command Prompt goes away and I have my new output file in the same > directory as my executable and input file. I would like to be able to > batch process a group of files. I thought about using "os.spawnv()" in > a loop and at each iteration of the loop passing in the file in and > out names but that didn't work. Does anyone have any ideas? Have a look at the subprocess module. -- Cheers, Simon B. From mensanator at aol.com Sat Apr 3 12:35:34 2010 From: mensanator at aol.com (Mensanator) Date: Sat, 3 Apr 2010 09:35:34 -0700 (PDT) Subject: off topic but please forgive me me and answer References: <4bb505c5$0$1133$4fafbaef@reader3.news.tin.it> <20100402214110.00a63457@geekmail.INVALID> <4bb73c0b$0$1125$4fafbaef@reader3.news.tin.it> <4bb75bea$0$27790$c3e8da3@news.astraweb.com> Message-ID: <63c2fbfa-cb74-4db3-adae-e79ce35dc9de@j21g2000yqh.googlegroups.com> On Apr 3, 10:17?am, Steven D'Aprano wrote: > On Sat, 03 Apr 2010 15:43:41 +0100, Martin P. Hellwig wrote: > > I am replying to this post not because I disagree but because it > > postalogically ?fits the best (I am by no means an expert either). > > > IMHO, the crackpot in this regard is actually partially right, > > multiplication does mean that the number must get bigger, however for > > fractions you multiply four numbers, two numerators and two > > denominators. The resulting numerator and denominator by this > > multiplication get indeed bigger. > > But you're not multiplying four numbers, You are if you're using Rationals. > you're multiplying two numbers. Because they're expressed as Decimals. > One-half is not "two numbers", Sometimes it is. > that would be a tuple Like this? >>> gmpy.mpq('0.5') mpq(1,2) > or a list or > possibly a coordinate pair. One-half is a single number, When dealing with crackpots, it does not help to use the wrong arguments. When multiplying gmpy.mpq(2,3) by gmpy.mpq(2,3), the numerator and denominator have both indeed gotten bigger. The trick is that when combined, the overall result is smaller. > the number which > if you double it gives one. > > Fortunately multiplication is consistent. Multiplying the two numbers 0.5 > and 0.5 is exactly the same as multiplying 1*1 and 2*2 then dividing to > get a single number. It's not the same as multiplying 1*1 and 2*2 to get > two numbers, 1 and 4. > > You say that multiplication means that the number "must get bigger". Yes, not in every case, but in many cases it does. You need to point out that it is wrong EVEN IN THE CASES WHERE IT'S TRUE. It is a Non Sequitur - it does not follow that a number must be bigger if the numerator and denominator have each gotten larger. > > 5*1 = 5 > 5*0 = 0 > 5*-2 = -10 > > I hope you won't try to argue that 5, 0 and -10 are all bigger than 5. Yes, but these special cases don't help. It needs to be pointed out that the argument is wrong even in cases like 2/3 * 2/3. > > There really is no point trying to dignify superpollo's friend's > assertion on the basis of some technicality. His argument is no different > from the argument that says that pythons are snakes, and therefore python > can't be a programming language and this newsgroup can't possibly exist. > Words can have multiple meanings, and meanings can shift. Multiply may be > derived from a word which, once upon a time, meant to get bigger, but > that's not what multiply means. I don't like to dismiss somebody I've > never met, but on the basis of what superpollo says, yes, he's a crackpot. > > Either that or about age four. When I was four I strongly believed that > "one hundred" and "a hundred" were different numbers. I argued (not very > convincingly, but with great vehemence) to my teacher and my parents that > you counted up to ninety-nine, then a hundred, a hundred and one, a > hundred and two, ... a hundred and ninety-nine, *one* hundred. > > -- > Steven From radhakrishna12 at gmail.com Sat Apr 3 12:37:45 2010 From: radhakrishna12 at gmail.com (Radhakrishna Bhat) Date: Sat, 3 Apr 2010 22:07:45 +0530 Subject: Get a method instance through 'getattr' but not superclass's method In-Reply-To: References: Message-ID: thanks. It is working for simple classes. But now i am trying for complex objects. myclassinstance.__class__.dict__ returns Looping through the same returned dictproxy gives attributes of superclass. What am i doing wrong? On Fri, Mar 12, 2010 at 12:15 AM, Gabriel Genellina wrote: > En Thu, 11 Mar 2010 01:47:30 -0300, Radhakrishna Bhat > escribi?: > > > I am using getattr to get a method instance from a class. But it also >> returns methods from the superclass. How to detect if an attribute is from >> superclass? >> > > You may look it up directly in the class dictionary (__dict__) > > -- > Gabriel Genellina > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From emile at fenx.com Sat Apr 3 12:59:12 2010 From: emile at fenx.com (Emile van Sebille) Date: Sat, 03 Apr 2010 09:59:12 -0700 Subject: off topic but please forgive me me and answer In-Reply-To: References: <4bb505c5$0$1133$4fafbaef@reader3.news.tin.it> <20100402214110.00a63457@geekmail.INVALID> <4bb73c0b$0$1125$4fafbaef@reader3.news.tin.it> Message-ID: On 4/3/2010 8:46 AM Patrick Maupin said... > On Apr 3, 9:43 am, "Martin P. Hellwig"> IMHO, the crackpot in this > regard is actually partially right, >> multiplication does mean that the number must get bigger, however for >> fractions you multiply four numbers, two numerators and two >> denominators. The resulting numerator and denominator by this >> multiplication get indeed bigger. > > That argument is great! Just make sure that you've managed to leave > before the class has to learn about irrational numbers that don't > *have* numerators and denominators ;-) Ahh, but no ones arguing that irrational numbers don't get bigger -- even before you multiply them! Emile From steve at holdenweb.com Sat Apr 3 13:13:38 2010 From: steve at holdenweb.com (Steve Holden) Date: Sat, 03 Apr 2010 13:13:38 -0400 Subject: off topic but please forgive me me and answer In-Reply-To: <63c2fbfa-cb74-4db3-adae-e79ce35dc9de@j21g2000yqh.googlegroups.com> References: <4bb505c5$0$1133$4fafbaef@reader3.news.tin.it> <20100402214110.00a63457@geekmail.INVALID> <4bb73c0b$0$1125$4fafbaef@reader3.news.tin.it> <4bb75bea$0$27790$c3e8da3@news.astraweb.com> <63c2fbfa-cb74-4db3-adae-e79ce35dc9de@j21g2000yqh.googlegroups.com> Message-ID: Mensanator wrote: [...] > When dealing with crackpots, it does not help to use the > wrong arguments. [...] Correct. Unfortunately, it doesn't help to use the right ones either. In fact, that could almost be a definition of "crackpot" (and alas now we approach territory where we risk offending the religious, so I will cease and desist). regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 See PyCon Talks from Atlanta 2010 http://pycon.blip.tv/ Holden Web LLC http://www.holdenweb.com/ UPCOMING EVENTS: http://holdenweb.eventbrite.com/ From pmaupin at gmail.com Sat Apr 3 13:15:38 2010 From: pmaupin at gmail.com (Patrick Maupin) Date: Sat, 3 Apr 2010 10:15:38 -0700 (PDT) Subject: off topic but please forgive me me and answer References: <4bb505c5$0$1133$4fafbaef@reader3.news.tin.it> <20100402214110.00a63457@geekmail.INVALID> <4bb73c0b$0$1125$4fafbaef@reader3.news.tin.it> Message-ID: On Apr 3, 11:59?am, Emile van Sebille wrote: > On 4/3/2010 8:46 AM Patrick Maupin said... > > > On Apr 3, 9:43 am, "Martin P. Hellwig"> ?IMHO, the crackpot in this > > regard is actually partially right, > >> multiplication does mean that the number must get bigger, however for > >> fractions you multiply four numbers, two numerators and two > >> denominators. The resulting numerator and denominator by this > >> multiplication get indeed bigger. > > > That argument is great! ?Just make sure that you've managed to leave > > before the class has to learn about irrational numbers that don't > > *have* numerators and denominators ;-) > > Ahh, but no ones arguing that irrational numbers don't get bigger -- > even before you multiply them! True, but being an optimist, just as (-1 * -1 == +1) (which admittedly, I had a hard time trying to explain to my father years ago), and just as (not not True == True) and just as multiplying two imaginary numbers can have a real result, I was hoping that it would also be the case that having a discussion with an irrational person about irrational numbers could have a rational result. Of course, that hope was incredibly naive of me, since most operations with irrational numbers which do not involve either closely related irrational numbers or zero will also result in irrational numbers. I think induction will show that this property (that an irrational number can make any result that it is involved in irrational) can also be applied to irrational people and discussions. ;-) Regards, Pat From mcanjo at gmail.com Sat Apr 3 13:20:44 2010 From: mcanjo at gmail.com (mcanjo) Date: Sat, 3 Apr 2010 10:20:44 -0700 (PDT) Subject: passing command line arguments to executable References: <4a636ae6-d68a-4b34-8e3f-9c11aa352793@g11g2000yqe.googlegroups.com> <5d3a56da-aab2-4715-b288-1c9de47c9ece@k13g2000yqe.googlegroups.com> Message-ID: <404ca155-866e-45d0-b496-a37e9fb9155a@10g2000yqq.googlegroups.com> On Apr 3, 11:15?am, Patrick Maupin wrote: > On Apr 3, 11:09?am, mcanjo wrote: > > > I have an executable (I don't have access to the source code) that > > processes some data. I double click on the icon and a Command prompt > > window pops up. The program asks me for the input file, I hit enter, > > and then it asks me for and output filename, I hit enter a second time > > and it goes off and does its thing and when it is finished running the > > Command Prompt goes away and I have my new output file in the same > > directory as my executable and input file. I would like to be able to > > batch process a group of files. I thought about using "os.spawnv()" in > > a loop and at each iteration of the loop passing in the file in and > > out names but that didn't work. Does anyone have any ideas? > > You need to look at the subprocess module, and use pipes. > > Regards, > Pat I tried doing the following code: from subprocess import Popen from subprocess import PIPE, STDOUT exefile = Popen('pmm.exe', stdout = PIPE, stdin = PIPE, stderr = STDOUT) exefile.communicate('MarchScreen.pmm\nMarchScreen.out')[0] and the Command Prompt opened and closed, no exceptions were generated but the program didn't run. Am I doing something wrong? From pmaupin at gmail.com Sat Apr 3 13:29:49 2010 From: pmaupin at gmail.com (Patrick Maupin) Date: Sat, 3 Apr 2010 10:29:49 -0700 (PDT) Subject: passing command line arguments to executable References: <4a636ae6-d68a-4b34-8e3f-9c11aa352793@g11g2000yqe.googlegroups.com> <5d3a56da-aab2-4715-b288-1c9de47c9ece@k13g2000yqe.googlegroups.com> <404ca155-866e-45d0-b496-a37e9fb9155a@10g2000yqq.googlegroups.com> Message-ID: On Apr 3, 12:20?pm, mcanjo wrote: > On Apr 3, 11:15?am, Patrick Maupin wrote: > > > > > On Apr 3, 11:09?am, mcanjo wrote: > > > > I have an executable (I don't have access to the source code) that > > > processes some data. I double click on the icon and a Command prompt > > > window pops up. The program asks me for the input file, I hit enter, > > > and then it asks me for and output filename, I hit enter a second time > > > and it goes off and does its thing and when it is finished running the > > > Command Prompt goes away and I have my new output file in the same > > > directory as my executable and input file. I would like to be able to > > > batch process a group of files. I thought about using "os.spawnv()" in > > > a loop and at each iteration of the loop passing in the file in and > > > out names but that didn't work. Does anyone have any ideas? > > > You need to look at the subprocess module, and use pipes. > > > Regards, > > Pat > > I tried doing the following code: > > from subprocess import Popen > from subprocess import PIPE, STDOUT > exefile = Popen('pmm.exe', stdout = PIPE, stdin = PIPE, stderr = > STDOUT) > exefile.communicate('MarchScreen.pmm\nMarchScreen.out')[0] > > and the Command Prompt opened and closed, no exceptions were generated > but the program didn't run. Am I doing something wrong? I don't use communicate because I've never gotten it to do what I want. I also don't use Windows. I have a linux solution that allows me to feed stuf into a pipe, but I don't think it will work under Windows because it uses os functions to block on empty pipes that Windows doesn't support. You might read PEP 3145 -- it addresses some of the issues, and there is some code to help, I think: http://www.python.org/dev/peps/pep-3145/ Regards, Pat From python at mrabarnett.plus.com Sat Apr 3 13:39:17 2010 From: python at mrabarnett.plus.com (MRAB) Date: Sat, 03 Apr 2010 18:39:17 +0100 Subject: off topic but please forgive me me and answer In-Reply-To: References: <4bb505c5$0$1133$4fafbaef@reader3.news.tin.it> <20100402214110.00a63457@geekmail.INVALID> <4bb73c0b$0$1125$4fafbaef@reader3.news.tin.it> Message-ID: <4BB77D45.6090504@mrabarnett.plus.com> Patrick Maupin wrote: > On Apr 3, 11:59 am, Emile van Sebille wrote: >> On 4/3/2010 8:46 AM Patrick Maupin said... >> >>> On Apr 3, 9:43 am, "Martin P. Hellwig"> IMHO, the crackpot in this >>> regard is actually partially right, >>>> multiplication does mean that the number must get bigger, however for >>>> fractions you multiply four numbers, two numerators and two >>>> denominators. The resulting numerator and denominator by this >>>> multiplication get indeed bigger. >>> That argument is great! Just make sure that you've managed to leave >>> before the class has to learn about irrational numbers that don't >>> *have* numerators and denominators ;-) >> Ahh, but no ones arguing that irrational numbers don't get bigger -- >> even before you multiply them! > > True, but being an optimist, just as (-1 * -1 == +1) (which > admittedly, I had a hard time trying to explain to my father years > ago), and just as (not not True == True) and just as multiplying two > imaginary numbers can have a real result, I was hoping that it would > also be the case that having a discussion with an irrational person > about irrational numbers could have a rational result. Of course, > that hope was incredibly naive of me, since most operations with > irrational numbers which do not involve either closely related > irrational numbers or zero will also result in irrational numbers. I > think induction will show that this property (that an irrational > number can make any result that it is involved in irrational) can also > be applied to irrational people and discussions. ;-) > The square root of 2 is irrational, but if you multiply it by itself then the result isn't irrational, so not all operations involving irrational numbers will result in an irrational result (unless that's what you mean by "closely related irrational numbers"). From john at castleamber.com Sat Apr 3 13:44:42 2010 From: john at castleamber.com (John Bokma) Date: Sat, 03 Apr 2010 11:44:42 -0600 Subject: (a==b) ? 'Yes' : 'No' References: <4bb22b39$0$1638$742ec2ed@news.sonic.net> <4bb6917c$0$8827$c3e8da3@news.astraweb.com> <844d8970-e814-49cc-b9d4-ea88f760e078@r27g2000yqn.googlegroups.com> Message-ID: <87tyrsjur9.fsf@castleamber.com> Steve Howell writes: > In languages like Ruby/Perl the inverted if statement is also a useful > idiom to emphasize concisely that code is exceptional in nature: > > def quotient(m, n) > # guard code > return None if n == 0 > > # happy path > return m / n > end Still, in Perl I prefer: sub quotient { my ( $m, $n ) = @_; $n != 0 or return; return $m / $n; } but I guess it depends a lot on what you're used to read. -- John Bokma j3b Hacking & Hiking in Mexico - http://johnbokma.com/ http://castleamber.com/ - Perl & Python Development From pmaupin at gmail.com Sat Apr 3 13:56:37 2010 From: pmaupin at gmail.com (Patrick Maupin) Date: Sat, 3 Apr 2010 10:56:37 -0700 (PDT) Subject: off topic but please forgive me me and answer References: <4bb505c5$0$1133$4fafbaef@reader3.news.tin.it> <20100402214110.00a63457@geekmail.INVALID> <4bb73c0b$0$1125$4fafbaef@reader3.news.tin.it> Message-ID: <08b9d5b5-5825-4d21-a68a-06a2d6183ee7@k19g2000yqn.googlegroups.com> On Apr 3, 12:39?pm, MRAB wrote: > Patrick Maupin wrote: > > On Apr 3, 11:59 am, Emile van Sebille wrote: > >> On 4/3/2010 8:46 AM Patrick Maupin said... > > >>> On Apr 3, 9:43 am, "Martin P. Hellwig"> ?IMHO, the crackpot in this > >>> regard is actually partially right, > >>>> multiplication does mean that the number must get bigger, however for > >>>> fractions you multiply four numbers, two numerators and two > >>>> denominators. The resulting numerator and denominator by this > >>>> multiplication get indeed bigger. > >>> That argument is great! ?Just make sure that you've managed to leave > >>> before the class has to learn about irrational numbers that don't > >>> *have* numerators and denominators ;-) > >> Ahh, but no ones arguing that irrational numbers don't get bigger -- > >> even before you multiply them! > > > True, but being an optimist, just as (-1 * -1 == +1) (which > > admittedly, I had a hard time trying to explain to my father years > > ago), and just as (not not True == True) and just as multiplying two > > imaginary numbers can have a real result, I was hoping that it would > > also be the case that having a discussion with an irrational person > > about irrational numbers could have a rational result. ?Of course, > > that hope was incredibly naive of me, since most operations with > > irrational numbers which do not involve either closely related > > irrational numbers or zero will also result in irrational numbers. ?I > > think induction will show that this property (that an irrational > > number can make any result that it is involved in irrational) can also > > be applied to irrational people and discussions. ?;-) > > The square root of 2 is irrational, but if you multiply it by itself > then the result isn't irrational, so not all operations involving > irrational numbers will result in an irrational result (unless that's > what you mean by "closely related irrational numbers"). Yes, I think I am closely related to myself. But in addition to that particular disclaimer, I qualified the statement with "most" and I also mentioned that zero is special. I stand by the assertion that if you take a random assortment of non-zero numbers, some irrational, some rational, and a random assortment of numeric operators, that most operations involving an irrational number will have an irrational result. Regards, Pat From saimapk81 at gmail.com Sat Apr 3 14:07:02 2010 From: saimapk81 at gmail.com (saima81) Date: Sat, 3 Apr 2010 11:07:02 -0700 (PDT) Subject: "JOBS IN CANADA" "CANADA JOBS" "JOBS IN CANADA FOR FOREIGNERS" "ACCOUNTS JOBS IN CANADA" "FINANCE JOBS IN CANADA" MEDICAL JOBS IN CANADA" "ENGINEERING JOBS IN CANADA" "SPORTS JOBS IN CANADA" http://jobsincanada-net.blogspot.com/ Message-ID: "JOBS IN CANADA" "CANADA JOBS" "JOBS IN CANADA FOR FOREIGNERS" "ACCOUNTS JOBS IN CANADA" "FINANCE JOBS IN CANADA" MEDICAL JOBS IN CANADA" "ENGINEERING JOBS IN CANADA" "SPORTS JOBS IN CANADA" http://jobsincanada-net.blogspot.com/ "JOBS IN CANADA" "CANADA JOBS" "JOBS IN CANADA FOR FOREIGNERS" "ACCOUNTS JOBS IN CANADA" "FINANCE JOBS IN CANADA" MEDICAL JOBS IN CANADA" "ENGINEERING JOBS IN CANADA" "SPORTS JOBS IN CANADA" http://jobsincanada-net.blogspot.com/ "JOBS IN CANADA" "CANADA JOBS" "JOBS IN CANADA FOR FOREIGNERS" "ACCOUNTS JOBS IN CANADA" "FINANCE JOBS IN CANADA" MEDICAL JOBS IN CANADA" "ENGINEERING JOBS IN CANADA" "SPORTS JOBS IN CANADA" http://jobsincanada-net.blogspot.com/ "JOBS IN CANADA" "CANADA JOBS" "JOBS IN CANADA FOR FOREIGNERS" "ACCOUNTS JOBS IN CANADA" "FINANCE JOBS IN CANADA" MEDICAL JOBS IN CANADA" "ENGINEERING JOBS IN CANADA" "SPORTS JOBS IN CANADA" http://jobsincanada-net.blogspot.com/ "JOBS IN CANADA" "CANADA JOBS" "JOBS IN CANADA FOR FOREIGNERS" "ACCOUNTS JOBS IN CANADA" "FINANCE JOBS IN CANADA" MEDICAL JOBS IN CANADA" "ENGINEERING JOBS IN CANADA" "SPORTS JOBS IN CANADA" http://jobsincanada-net.blogspot.com/ "JOBS IN CANADA" "CANADA JOBS" "JOBS IN CANADA FOR FOREIGNERS" "ACCOUNTS JOBS IN CANADA" "FINANCE JOBS IN CANADA" MEDICAL JOBS IN CANADA" "ENGINEERING JOBS IN CANADA" "SPORTS JOBS IN CANADA" http://jobsincanada-net.blogspot.com/ "JOBS IN CANADA" "CANADA JOBS" "JOBS IN CANADA FOR FOREIGNERS" "ACCOUNTS JOBS IN CANADA" "FINANCE JOBS IN CANADA" MEDICAL JOBS IN CANADA" "ENGINEERING JOBS IN CANADA" "SPORTS JOBS IN CANADA" http://jobsincanada-net.blogspot.com/ "JOBS IN CANADA" "CANADA JOBS" "JOBS IN CANADA FOR FOREIGNERS" "ACCOUNTS JOBS IN CANADA" "FINANCE JOBS IN CANADA" MEDICAL JOBS IN CANADA" "ENGINEERING JOBS IN CANADA" "SPORTS JOBS IN CANADA" http://jobsincanada-net.blogspot.com/ "JOBS IN CANADA" "CANADA JOBS" "JOBS IN CANADA FOR FOREIGNERS" "ACCOUNTS JOBS IN CANADA" "FINANCE JOBS IN CANADA" MEDICAL JOBS IN CANADA" "ENGINEERING JOBS IN CANADA" "SPORTS JOBS IN CANADA" http://jobsincanada-net.blogspot.com/ "JOBS IN CANADA" "CANADA JOBS" "JOBS IN CANADA FOR FOREIGNERS" "ACCOUNTS JOBS IN CANADA" "FINANCE JOBS IN CANADA" MEDICAL JOBS IN CANADA" "ENGINEERING JOBS IN CANADA" "SPORTS JOBS IN CANADA" http://jobsincanada-net.blogspot.com/ "JOBS IN CANADA" "CANADA JOBS" "JOBS IN CANADA FOR FOREIGNERS" "ACCOUNTS JOBS IN CANADA" "FINANCE JOBS IN CANADA" MEDICAL JOBS IN CANADA" "ENGINEERING JOBS IN CANADA" "SPORTS JOBS IN CANADA" http://jobsincanada-net.blogspot.com/ "JOBS IN CANADA" "CANADA JOBS" "JOBS IN CANADA FOR FOREIGNERS" "ACCOUNTS JOBS IN CANADA" "FINANCE JOBS IN CANADA" MEDICAL JOBS IN CANADA" "ENGINEERING JOBS IN CANADA" "SPORTS JOBS IN CANADA" http://jobsincanada-net.blogspot.com/ "JOBS IN CANADA" "CANADA JOBS" "JOBS IN CANADA FOR FOREIGNERS" "ACCOUNTS JOBS IN CANADA" "FINANCE JOBS IN CANADA" MEDICAL JOBS IN CANADA" "ENGINEERING JOBS IN CANADA" "SPORTS JOBS IN CANADA" http://jobsincanada-net.blogspot.com/ "JOBS IN CANADA" "CANADA JOBS" "JOBS IN CANADA FOR FOREIGNERS" "ACCOUNTS JOBS IN CANADA" "FINANCE JOBS IN CANADA" MEDICAL JOBS IN CANADA" "ENGINEERING JOBS IN CANADA" "SPORTS JOBS IN CANADA" http://jobsincanada-net.blogspot.com/ "JOBS IN CANADA" "CANADA JOBS" "JOBS IN CANADA FOR FOREIGNERS" "ACCOUNTS JOBS IN CANADA" "FINANCE JOBS IN CANADA" MEDICAL JOBS IN CANADA" "ENGINEERING JOBS IN CANADA" "SPORTS JOBS IN CANADA" http://jobsincanada-net.blogspot.com/ "JOBS IN CANADA" "CANADA JOBS" "JOBS IN CANADA FOR FOREIGNERS" "ACCOUNTS JOBS IN CANADA" "FINANCE JOBS IN CANADA" MEDICAL JOBS IN CANADA" "ENGINEERING JOBS IN CANADA" "SPORTS JOBS IN CANADA" http://jobsincanada-net.blogspot.com/ "JOBS IN CANADA" "CANADA JOBS" "JOBS IN CANADA FOR FOREIGNERS" "ACCOUNTS JOBS IN CANADA" "FINANCE JOBS IN CANADA" MEDICAL JOBS IN CANADA" "ENGINEERING JOBS IN CANADA" "SPORTS JOBS IN CANADA" http://jobsincanada-net.blogspot.com/ "JOBS IN CANADA" "CANADA JOBS" "JOBS IN CANADA FOR FOREIGNERS" "ACCOUNTS JOBS IN CANADA" "FINANCE JOBS IN CANADA" MEDICAL JOBS IN CANADA" "ENGINEERING JOBS IN CANADA" "SPORTS JOBS IN CANADA" http://jobsincanada-net.blogspot.com/ "JOBS IN CANADA" "CANADA JOBS" "JOBS IN CANADA FOR FOREIGNERS" "ACCOUNTS JOBS IN CANADA" "FINANCE JOBS IN CANADA" MEDICAL JOBS IN CANADA" "ENGINEERING JOBS IN CANADA" "SPORTS JOBS IN CANADA" http://jobsincanada-net.blogspot.com/ "JOBS IN CANADA" "CANADA JOBS" "JOBS IN CANADA FOR FOREIGNERS" "ACCOUNTS JOBS IN CANADA" "FINANCE JOBS IN CANADA" MEDICAL JOBS IN CANADA" "ENGINEERING JOBS IN CANADA" "SPORTS JOBS IN CANADA" http://jobsincanada-net.blogspot.com/ "JOBS IN CANADA" "CANADA JOBS" "JOBS IN CANADA FOR FOREIGNERS" "ACCOUNTS JOBS IN CANADA" "FINANCE JOBS IN CANADA" MEDICAL JOBS IN CANADA" "ENGINEERING JOBS IN CANADA" "SPORTS JOBS IN CANADA" http://jobsincanada-net.blogspot.com/ "JOBS IN CANADA" "CANADA JOBS" "JOBS IN CANADA FOR FOREIGNERS" "ACCOUNTS JOBS IN CANADA" "FINANCE JOBS IN CANADA" MEDICAL JOBS IN CANADA" "ENGINEERING JOBS IN CANADA" "SPORTS JOBS IN CANADA" http://jobsincanada-net.blogspot.com/ "JOBS IN CANADA" "CANADA JOBS" "JOBS IN CANADA FOR FOREIGNERS" "ACCOUNTS JOBS IN CANADA" "FINANCE JOBS IN CANADA" MEDICAL JOBS IN CANADA" "ENGINEERING JOBS IN CANADA" "SPORTS JOBS IN CANADA" http://jobsincanada-net.blogspot.com/ "JOBS IN CANADA" "CANADA JOBS" "JOBS IN CANADA FOR FOREIGNERS" "ACCOUNTS JOBS IN CANADA" "FINANCE JOBS IN CANADA" MEDICAL JOBS IN CANADA" "ENGINEERING JOBS IN CANADA" "SPORTS JOBS IN CANADA" http://jobsincanada-net.blogspot.com/ "JOBS IN CANADA" "CANADA JOBS" "JOBS IN CANADA FOR FOREIGNERS" "ACCOUNTS JOBS IN CANADA" "FINANCE JOBS IN CANADA" MEDICAL JOBS IN CANADA" "ENGINEERING JOBS IN CANADA" "SPORTS JOBS IN CANADA" http://jobsincanada-net.blogspot.com/ "JOBS IN CANADA" "CANADA JOBS" "JOBS IN CANADA FOR FOREIGNERS" "ACCOUNTS JOBS IN CANADA" "FINANCE JOBS IN CANADA" MEDICAL JOBS IN CANADA" "ENGINEERING JOBS IN CANADA" "SPORTS JOBS IN CANADA" http://jobsincanada-net.blogspot.com/ "JOBS IN CANADA" "CANADA JOBS" "JOBS IN CANADA FOR FOREIGNERS" "ACCOUNTS JOBS IN CANADA" "FINANCE JOBS IN CANADA" MEDICAL JOBS IN CANADA" "ENGINEERING JOBS IN CANADA" "SPORTS JOBS IN CANADA" http://jobsincanada-net.blogspot.com/ "JOBS IN CANADA" "CANADA JOBS" "JOBS IN CANADA FOR FOREIGNERS" "ACCOUNTS JOBS IN CANADA" "FINANCE JOBS IN CANADA" MEDICAL JOBS IN CANADA" "ENGINEERING JOBS IN CANADA" "SPORTS JOBS IN CANADA" http://jobsincanada-net.blogspot.com/ "JOBS IN CANADA" "CANADA JOBS" "JOBS IN CANADA FOR FOREIGNERS" "ACCOUNTS JOBS IN CANADA" "FINANCE JOBS IN CANADA" MEDICAL JOBS IN CANADA" "ENGINEERING JOBS IN CANADA" "SPORTS JOBS IN CANADA" http://jobsincanada-net.blogspot.com/ "JOBS IN CANADA" "CANADA JOBS" "JOBS IN CANADA FOR FOREIGNERS" "ACCOUNTS JOBS IN CANADA" "FINANCE JOBS IN CANADA" MEDICAL JOBS IN CANADA" "ENGINEERING JOBS IN CANADA" "SPORTS JOBS IN CANADA" http://jobsincanada-net.blogspot.com/ "JOBS IN CANADA" "CANADA JOBS" "JOBS IN CANADA FOR FOREIGNERS" "ACCOUNTS JOBS IN CANADA" "FINANCE JOBS IN CANADA" MEDICAL JOBS IN CANADA" "ENGINEERING JOBS IN CANADA" "SPORTS JOBS IN CANADA" http://jobsincanada-net.blogspot.com/ "JOBS IN CANADA" "CANADA JOBS" "JOBS IN CANADA FOR FOREIGNERS" "ACCOUNTS JOBS IN CANADA" "FINANCE JOBS IN CANADA" MEDICAL JOBS IN CANADA" "ENGINEERING JOBS IN CANADA" "SPORTS JOBS IN CANADA" http://jobsincanada-net.blogspot.com/ "JOBS IN CANADA" "CANADA JOBS" "JOBS IN CANADA FOR FOREIGNERS" "ACCOUNTS JOBS IN CANADA" "FINANCE JOBS IN CANADA" MEDICAL JOBS IN CANADA" "ENGINEERING JOBS IN CANADA" "SPORTS JOBS IN CANADA" http://jobsincanada-net.blogspot.com/ "JOBS IN CANADA" "CANADA JOBS" "JOBS IN CANADA FOR FOREIGNERS" "ACCOUNTS JOBS IN CANADA" "FINANCE JOBS IN CANADA" MEDICAL JOBS IN CANADA" "ENGINEERING JOBS IN CANADA" "SPORTS JOBS IN CANADA" http://jobsincanada-net.blogspot.com/ "JOBS IN CANADA" "CANADA JOBS" "JOBS IN CANADA FOR FOREIGNERS" "ACCOUNTS JOBS IN CANADA" "FINANCE JOBS IN CANADA" MEDICAL JOBS IN CANADA" "ENGINEERING JOBS IN CANADA" "SPORTS JOBS IN CANADA" http://jobsincanada-net.blogspot.com/ "JOBS IN CANADA" "CANADA JOBS" "JOBS IN CANADA FOR FOREIGNERS" "ACCOUNTS JOBS IN CANADA" "FINANCE JOBS IN CANADA" MEDICAL JOBS IN CANADA" "ENGINEERING JOBS IN CANADA" "SPORTS JOBS IN CANADA" http://jobsincanada-net.blogspot.com/ "JOBS IN CANADA" "CANADA JOBS" "JOBS IN CANADA FOR FOREIGNERS" "ACCOUNTS JOBS IN CANADA" "FINANCE JOBS IN CANADA" MEDICAL JOBS IN CANADA" "ENGINEERING JOBS IN CANADA" "SPORTS JOBS IN CANADA" http://jobsincanada-net.blogspot.com/ "JOBS IN CANADA" "CANADA JOBS" "JOBS IN CANADA FOR FOREIGNERS" "ACCOUNTS JOBS IN CANADA" "FINANCE JOBS IN CANADA" MEDICAL JOBS IN CANADA" "ENGINEERING JOBS IN CANADA" "SPORTS JOBS IN CANADA" http://jobsincanada-net.blogspot.com/ "JOBS IN CANADA" "CANADA JOBS" "JOBS IN CANADA FOR FOREIGNERS" "ACCOUNTS JOBS IN CANADA" "FINANCE JOBS IN CANADA" MEDICAL JOBS IN CANADA" "ENGINEERING JOBS IN CANADA" "SPORTS JOBS IN CANADA" http://jobsincanada-net.blogspot.com/ "JOBS IN CANADA" "CANADA JOBS" "JOBS IN CANADA FOR FOREIGNERS" "ACCOUNTS JOBS IN CANADA" "FINANCE JOBS IN CANADA" MEDICAL JOBS IN CANADA" "ENGINEERING JOBS IN CANADA" "SPORTS JOBS IN CANADA" http://jobsincanada-net.blogspot.com/ From python at bdurham.com Sat Apr 3 14:52:20 2010 From: python at bdurham.com (python at bdurham.com) Date: Sat, 03 Apr 2010 14:52:20 -0400 Subject: Good Intermediate Tutorials In-Reply-To: References: <4bb56d74$1@dnews.tpgi.com.au> Message-ID: <1270320740.14862.1368150401@webmail.messagingengine.com> Pick an arbitrary point in time, and begin reading this mailing list's archives. I guarantee you will learn alot. Malcolm -------------- next part -------------- An HTML attachment was scrubbed... URL: From apt.shansen at gmail.invalid Sat Apr 3 15:03:59 2010 From: apt.shansen at gmail.invalid (Stephen Hansen) Date: Sat, 3 Apr 2010 12:03:59 -0700 Subject: C-style static variables in Python? References: <201004022011213167-aptshansen@gmailinvalid> Message-ID: <2010040312035930177-aptshansen@gmailinvalid> On 2010-04-02 20:24:46 -0700, Patrick Maupin said: > On Apr 2, 10:11?pm, Stephen Hansen wrote: >> >> I don't know if properties are really faster or slower then a >> __getattr__, but I find them a lot cleaner if I want to delay some >> calculation until needed like that. > > Well, the relative speed of properties vs. __getattr__ can become > irrelevant in at least two ways: > > 1) If the __getattr__ only calculates the value one time and then > stuffs it into the instance dictionary, now you are really comparing > the relative speed of properties vs. lookup of an attribute in the > instance dict. If you're at all concerned about speed, I think there > is a clear winner here. I concede it would probably be notably faster, but there's a big difference between "at all concerned about speed" and "optimizing a profiled bottleneck". The speed difference between direct attribute lookup and properties may be notable, but that doesn't make a clear winner here. Now that I have (with either method) optimized the expensive value-calculation operation such that it only happens on-demand and once, I now have to weigh further optimization. Is the difference in speed between a standard attribute lookup and a property fetch worth losing the clarity the property brings over the __getattr__ solution, especially considering the __getattr__ creates a fuzzy 'sometimes this code is responsible, othertimes the dict is' situation that someone may down the road miss in maintenance? For me, usually not-- unless profiling pushes me to reconsider. But everyone makes these calls differently. > 2) There is a single __getattr__ function, vs. one property for every > attribute that needs a property. In cases where you can somehow > easily compute the attribute names as well as the attribute values, > __getattr__ can be a *lot* less code than defining dozens of > properties. I don't really mind a lot of properties, if they're simple. Then again, I often prefer regular ol' attributes where possible :) However, if I'm doing a dispatching sort of mechanism, or a situation where the "name" isn't something static, set in stone or pre-defined-- then certainly, __getattr__ is a fine solution. I don't mind it where its the clearest way to accomplish a goal. -- --S ... p.s: change the ".invalid" to ".com" in email address to reply privately. From usenot at geekmail.INVALID Sat Apr 3 15:21:04 2010 From: usenot at geekmail.INVALID (Andreas Waldenburger) Date: Sat, 3 Apr 2010 21:21:04 +0200 Subject: off topic but please forgive me me and answer References: <4bb505c5$0$1133$4fafbaef@reader3.news.tin.it> <20100402214110.00a63457@geekmail.INVALID> <4bb73c0b$0$1125$4fafbaef@reader3.news.tin.it> <4bb75bea$0$27790$c3e8da3@news.astraweb.com> <63c2fbfa-cb74-4db3-adae-e79ce35dc9de@j21g2000yqh.googlegroups.com> Message-ID: <20100403212104.4fa701a9@geekmail.INVALID> On Sat, 03 Apr 2010 13:13:38 -0400 Steve Holden wrote: > Correct. Unfortunately, it doesn't help to use the right ones either. > In fact, that could almost be a definition of "crackpot" (and alas now > we approach territory where we risk offending the religious, so I will > cease and desist). Except that you didn't. ;) /W -- INVALID? DE! From martin.hellwig at dcuktec.org Sat Apr 3 16:17:10 2010 From: martin.hellwig at dcuktec.org (Martin P. Hellwig) Date: Sat, 03 Apr 2010 21:17:10 +0100 Subject: off topic but please forgive me me and answer In-Reply-To: References: <4bb505c5$0$1133$4fafbaef@reader3.news.tin.it> <20100402214110.00a63457@geekmail.INVALID> <4bb73c0b$0$1125$4fafbaef@reader3.news.tin.it> Message-ID: On 04/03/10 16:46, Patrick Maupin wrote: > On Apr 3, 9:43 am, "Martin P. Hellwig"> IMHO, the crackpot in this > regard is actually partially right, >> multiplication does mean that the number must get bigger, however for >> fractions you multiply four numbers, two numerators and two >> denominators. The resulting numerator and denominator by this >> multiplication get indeed bigger. > > That argument is great! Just make sure that you've managed to leave > before the class has to learn about irrational numbers that don't > *have* numerators and denominators ;-) Yeah but those numbers have their own problems anyway, one of them being that you are never sure how big/small they actually are, so by that logic you could argue that if you can not give an exact measure for a given number, bickering over it size after an operation is pretty pointless (pun intended) :-) Beside the only number that really matters is 42 ;-) -- mph From metolone+gmane at gmail.com Sat Apr 3 17:24:19 2010 From: metolone+gmane at gmail.com (Mark Tolonen) Date: Sat, 3 Apr 2010 14:24:19 -0700 Subject: WinXP, Python3.1.2, dir-listing to XML - problem with unicode file names References: Message-ID: "kai_nerda" wrote in message news:hp69ri+ao5e at eGroups.com... > Hi, > > OS = Windows XP (German language) > Python = 3.1.2 > > I need to write a directory listing into a XML file. > And after hours of trying and searching i have no clue. > > My main problem is that the file and folder names can > have characters of different languages like > German, Turkish, Russian, maybe else. > > Because Python 3.1 is better with unicode, I > decided to use that instead of 2.6 > > For testing I have created the following files: > http://img340.imageshack.us/img340/3461/files.png > (google for the words > russia, turkish, deutsch, france > to find websites with special characters and copy & paste) > > And this is the code I have now: > ############################################ > # -*- coding: iso-8859-1 -*- > # inspired by: > # http://www.dpawson.co.uk/java/dirlist.py > # (for Python ~2.4) > > import sys > print ('filesystemencoding: ' + sys.getfilesystemencoding()) > print ('defaultencoding: ' + sys.getdefaultencoding()) > > > from pprint import pprint > import os.path > from stat import * > from xml.sax.saxutils import XMLGenerator > > def recurse_dir(path, writer): > for cdir, subdirs, files in os.walk(path): > pprint (cdir) > writer.startElement('dir', { 'name': cdir }) > for f in files: > uf = f.encode('utf-8') > pprint (uf) > attribs = {'name': f} > attribs['size'] = str(os.stat(os.path.join(cdir,f))[ST_SIZE]) > pprint (attribs) > writer.startElement('file', attribs) > writer.endElement('file') > for subdir in subdirs: > recurse_dir(os.path.join(cdir, subdir), writer) > writer.endElement('directory') This should be: writer.endElement('dir') > break > > if __name__ == '__main__': > directory = 'c:\\_TEST\\' > out = open('C:\\_TEST.xml','w') The above line opens the file in the default file system encoding 'mbcs' (cp850 on your system). Try: out = open('C:\\_TEST.xml','w',encoding='utf8') Regards, -Mark > writer = XMLGenerator(out, 'utf-8') > writer.startDocument() > recurse_dir(directory, writer) > > out.close() > ############################################ From gagsl-py2 at yahoo.com.ar Sat Apr 3 18:58:01 2010 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 03 Apr 2010 19:58:01 -0300 Subject: Get a method instance through 'getattr' but not superclass's method References: Message-ID: Please reply inline; top posting is harder to read. > On Fri, Mar 12, 2010 at 12:15 AM, Gabriel Genellina > wrote: > >> En Thu, 11 Mar 2010 01:47:30 -0300, Radhakrishna Bhat >> escribi?: >> >> I am using getattr to get a method instance from a class. But it also >>> returns methods from the superclass. How to detect if an attribute is >>> from >>> superclass? >> >> You may look it up directly in the class dictionary (__dict__) En Sat, 03 Apr 2010 13:37:45 -0300, Radhakrishna Bhat escribi?:> > thanks. It is working for simple classes. But now i am trying for complex > objects. > > myclassinstance.__class__.dict__ returns > > Looping through the same returned dictproxy gives attributes of > superclass. > What am i doing wrong? Could you provide a failing example? It works for me in this case: py> class MyClass(int): ... "This is my derived class" ... foo = 1 ... def bar(self): pass ... py> MyClass py> MyClass.__dict__ py> MyClass.__dict__.keys() ['__module__', 'bar', '__dict__', 'foo', '__weakref__', '__doc__'] py> for name in MyClass.__dict__: ... print '%s: %.30r %.30r' % (name, getattr(MyClass,name), getattr(int,name,'*does*not*exist*')) ... __module__: '__main__' '__builtin__' bar: '*does*not*exist*' __dict__: integer\n\n foo and bar are new attributes. __module__, __dict__, __weakref__ and __doc__ are different from the base class. If you want to filter out the last four: - ignore all attribute names starting and ending with two underscores: if name[:2] == '__' == name[-2:]: continue - ignore all attributes already present in the base class. if hasattr(int, name): continue -- Gabriel Genellina From no.email at please.post Sat Apr 3 18:58:43 2010 From: no.email at please.post (kj) Date: Sat, 3 Apr 2010 22:58:43 +0000 (UTC) Subject: How to access args as a list? Message-ID: Suppose I have a function with the following signature: def spam(x, y, z): # etc. Is there a way to refer, within the function, to all its arguments as a single list? (I.e. I'm looking for Python's equivalent of Perl's @_ variable.) I'm aware of locals(), but I want to preserve the order in which the arguments appear in the signature. My immediate aim is to set up a simple class that will allow me to iterate over the arguments passed to the constructor (plus let me refer to these individual arguments by their names using an instance.attribute syntax, as usual). The best I have managed looks like this: class _Spam(object): def __init__(self, x, y, z): self.__dict__ = OrderedDict(()) for p in inspect.getargspec(_Spam.__init__).args[1:]: self.__dict__[p] = locals()[p] def __iter__(self): return iter(self.__dict__.values()) but rolling out inspect.getargspec for this sort of thing looks to me like overkill. Is there a more basic approach? P.S. this is just an example; the function I want to implement has more parameters in its signature, with longer, more informative names. From python.list at tim.thechases.com Sat Apr 3 19:20:34 2010 From: python.list at tim.thechases.com (Tim Chase) Date: Sat, 03 Apr 2010 18:20:34 -0500 Subject: How to access args as a list? In-Reply-To: References: Message-ID: <4BB7CD42.3000101@tim.thechases.com> kj wrote: > > > Suppose I have a function with the following signature: > > def spam(x, y, z): > # etc. > > Is there a way to refer, within the function, to all its arguments > as a single list? (I.e. I'm looking for Python's equivalent of > Perl's @_ variable.) It sounds like you want the "*" operator for arguments: def foo(*args): print "Args:", repr(args) print " Type:", type(args) for i, arg in enumerate(args): print " Arg #%i = %s" % (i, arg) foo(1) foo("abc", "def", 42) # pass a list as args lst = [1,2,3] foo(*lst) There's also a keyword form using "**": def foo(*args, **kwargs): print "Args:", repr(args) print " Type:", type(args) print "Keyword Args:", repr(kwargs) print " Type:", type(kwargs) for i, arg in enumerate(args): print " Arg #%i = %s" % (i+1, arg) for i, (k, v) in enumerate(kwargs.items()): print " kwarg #%i %r = %s" % (i+1, k, v) foo(1, "hello", something="Whatever", baz=42) # pass a list and a dict: lst = [1,2,3] dct = {100:10, 200:11} foo(*lst, **dct) Both prevent introspection, so if you want the auto-generated help to populate with named arguments, you'd have to use the inspection method you're currently using. But generally, if you want to be able to treat the args as lists/tuples/dicts, you don't care about the names given. -tim From python at mrabarnett.plus.com Sat Apr 3 19:20:52 2010 From: python at mrabarnett.plus.com (MRAB) Date: Sun, 04 Apr 2010 00:20:52 +0100 Subject: How to access args as a list? In-Reply-To: References: Message-ID: <4BB7CD54.3020903@mrabarnett.plus.com> kj wrote: > > > Suppose I have a function with the following signature: > > def spam(x, y, z): > # etc. > > Is there a way to refer, within the function, to all its arguments > as a single list? (I.e. I'm looking for Python's equivalent of > Perl's @_ variable.) > > I'm aware of locals(), but I want to preserve the order in which > the arguments appear in the signature. > > My immediate aim is to set up a simple class that will allow me to > iterate over the arguments passed to the constructor (plus let me > refer to these individual arguments by their names using an > instance.attribute syntax, as usual). > > The best I have managed looks like this: > > class _Spam(object): > def __init__(self, x, y, z): > self.__dict__ = OrderedDict(()) > for p in inspect.getargspec(_Spam.__init__).args[1:]: > self.__dict__[p] = locals()[p] > > def __iter__(self): > return iter(self.__dict__.values()) > > > but rolling out inspect.getargspec for this sort of thing looks to > me like overkill. Is there a more basic approach? > > P.S. this is just an example; the function I want to implement has > more parameters in its signature, with longer, more informative > names. > I think the closest approach to what you're asking is to capture the arguments as a list and then bind them to local names: def spam(*args): x, y, z = args # etc. From darkrho at gmail.com Sat Apr 3 19:21:38 2010 From: darkrho at gmail.com (Rolando Espinoza La Fuente) Date: Sat, 3 Apr 2010 18:51:38 -0430 Subject: How to access args as a list? In-Reply-To: References: Message-ID: On Sat, Apr 3, 2010 at 6:28 PM, kj wrote: > Is there a way to refer, within the function, to all its arguments > as a single list? ?(I.e. I'm looking for Python's equivalent of > Perl's @_ variable.) > def spam(*args, **kwargs): print args print kwargs class Spam: def __init__(self, *args, **kwargs): print args print kwargs That's what are you looking for? Regards, ~Rolando From dwlepage at yahoo.com Sat Apr 3 19:42:20 2010 From: dwlepage at yahoo.com (David LePage) Date: Sat, 3 Apr 2010 16:42:20 -0700 (PDT) Subject: Question on templates and python logging Message-ID: <273877.70578.qm@web51101.mail.re2.yahoo.com> Hi - I have been struggling with this problem for quite some time and was hoping somebody could give me some pointers. I have a wxPython front end wizard that collects some information and outputs some HTML pages (not hosted by a web server, but viewable locally on the machine running the application). The problem that i'm trying to solve is taking data collected along the way and outputting this into these HTML pages. One of the pages is simply collecting debug information about the execution of the program. All logging is currently being done using the python logging library. Due to the fact that my HTML files need to be populated in the tags, I wanted to write directly to the proper HTML page based on the logging level message (INFO, DEBUG, etc). Something like this works nicely if you have a dictionary storing the data: def template(): return open("html/html.tmpl", 'r').read() % vars print template("html/Logs.html", { 'body' : "A test body field" }) But in my case, some of the data could be MB in size and I didn't want to read/write that entire load of data before displaying the pages if at all possible. I was hoping I could tie the logging classes into something like this, where I was leveraging an HTML template, but also taking advantage of the logging library since it works nicely for me today. Does anybody have any suggestions on how they might approach this problem? thanks! DLP From no.email at please.post Sat Apr 3 19:52:42 2010 From: no.email at please.post (kj) Date: Sat, 3 Apr 2010 23:52:42 +0000 (UTC) Subject: How to access args as a list? References: Message-ID: In kj writes: >Suppose I have a function with the following signature: >def spam(x, y, z): > # etc. >Is there a way to refer, within the function, to all its arguments >as a single list? (I.e. I'm looking for Python's equivalent of >Perl's @_ variable.) >I'm aware of locals(), but I want to preserve the order in which >the arguments appear in the signature. >My immediate aim is to set up a simple class that will allow me to >iterate over the arguments passed to the constructor (plus letS me ^^^^^^^^^^^^ >refer to these individual arguments by their names using an ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ >instance.attribute syntax, as usual). ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ The underlined portion explains why __init__(self, *args) fails to fit the bill. >P.S. this is just an example; the function I want to implement has >more parameters in its signature, with longer, more informative >names. Andreas, perhaps this paragraph explains why I find your solution unappealing: it requires typing the same thing over and over, which increases the chances of bugs. That's the reason I avoid such repetitiveness, not laziness, as you so were so quick to accuse me of. ~K From no.email at please.post Sat Apr 3 19:55:10 2010 From: no.email at please.post (kj) Date: Sat, 3 Apr 2010 23:55:10 +0000 (UTC) Subject: How to access args as a list? References: Message-ID: In kj writes: >In kj writes: >>Suppose I have a function with the following signature: >>def spam(x, y, z): >> # etc. >>Is there a way to refer, within the function, to all its arguments >>as a single list? (I.e. I'm looking for Python's equivalent of >>Perl's @_ variable.) >>I'm aware of locals(), but I want to preserve the order in which >>the arguments appear in the signature. >>My immediate aim is to set up a simple class that will allow me to >>iterate over the arguments passed to the constructor (plus letS me > ^^^^^^^^^^^^ >>refer to these individual arguments by their names using an > ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ >>instance.attribute syntax, as usual). > ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ >The underlined portion explains why __init__(self, *args) fails to >fit the bill. The minute I hit "send" I realized that this is wrong. Sorry. Thanks. From usenot at geekmail.INVALID Sat Apr 3 20:16:13 2010 From: usenot at geekmail.INVALID (Andreas Waldenburger) Date: Sun, 4 Apr 2010 02:16:13 +0200 Subject: How to access args as a list? References: Message-ID: <20100404021613.3c275859@geekmail.INVALID> On Sat, 3 Apr 2010 22:58:43 +0000 (UTC) kj wrote: > The best I have managed looks like this: > > class _Spam(object): > def __init__(self, x, y, z): > self.__dict__ = OrderedDict(()) > for p in inspect.getargspec(_Spam.__init__).args[1:]: > self.__dict__[p] = locals()[p] > > def __iter__(self): > return iter(self.__dict__.values()) Looks like you're trying to be lazy by doing extra hard work. Anything wrong with this (?): class Spam(object): def __init__(self, x, y, z): self.x = x self.y = y self.z = z self.arguments = (x, y, z) def __iter__(self): return iter(self.arguments) # iter(...) kinda optional With what little I know about your use case, that's how I would do it. /W -- INVALID? DE! From ldo at geek-central.gen.new_zealand Sat Apr 3 20:26:05 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sun, 04 Apr 2010 12:26:05 +1200 Subject: (a==b) ? 'Yes' : 'No' References: <7316f3d2-bcc9-4a1a-8598-cdd5d41fd74b@k17g2000yqb.googlegroups.com> Message-ID: In message , Steve Holden wrote: > Lawrence D'Oliveiro wrote: > >> By the way, you don?t need the parentheses. > > But at the same time, if you don't *absolutely know* you don't need the > parentheses ... But you can ?abolutely know??it?s all spelled out here . Just keep that page open every time you write Python code. From invalid at invalid.invalid Sat Apr 3 21:14:24 2010 From: invalid at invalid.invalid (Grant Edwards) Date: Sun, 4 Apr 2010 01:14:24 +0000 (UTC) Subject: How to access args as a list? References: Message-ID: On 2010-04-03, kj wrote: > In kj writes: > >>Suppose I have a function with the following signature: > >>def spam(x, y, z): >> # etc. > >>Is there a way to refer, within the function, to all its arguments >>as a single list? (I.e. I'm looking for Python's equivalent of >>Perl's @_ variable.) > >>I'm aware of locals(), but I want to preserve the order in which >>the arguments appear in the signature. > >>My immediate aim is to set up a simple class that will allow me to >>iterate over the arguments passed to the constructor (plus letS me > ^^^^^^^^^^^^ >>refer to these individual arguments by their names using an > ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ >>instance.attribute syntax, as usual). > ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ > > The underlined portion explains why __init__(self, *args) fails to > fit the bill. then add the line below: x,y,z = *args -- Grant From ldo at geek-central.gen.new_zealand Sat Apr 3 21:21:34 2010 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sun, 04 Apr 2010 13:21:34 +1200 Subject: Encryption source code with md5 References: <91541c26-6f18-40c7-a0df-252a52bb7cd5@l25g2000yqd.googlegroups.com> <4baf3ac4$0$22903$e4fe514c@news.xs4all.nl> Message-ID: In message <4baf3ac4$0$22903$e4fe514c at news.xs4all.nl>, Irmen de Jong wrote: > On 28-3-2010 12:08, Lawrence D'Oliveiro wrote: > >> Don?t use MD5. > > Also, md5 is not an encryption algorithm at all, it is a secure hashing > function. You can use hash functions for encryption. From usenot at geekmail.INVALID Sat Apr 3 21:42:14 2010 From: usenot at geekmail.INVALID (Andreas Waldenburger) Date: Sun, 4 Apr 2010 03:42:14 +0200 Subject: How to access args as a list? References: Message-ID: <20100404034214.0a4a2a4d@geekmail.INVALID> On Sat, 3 Apr 2010 23:52:42 +0000 (UTC) kj wrote: > In kj writes: > > [snip] > >P.S. this is just an example; the function I want to implement has > >more parameters in its signature, with longer, more informative > >names. > > Andreas, perhaps this paragraph explains why I find your solution > unappealing: it requires typing the same thing over and over, > which increases the chances of bugs. That's the reason I avoid > such repetitiveness, not laziness, as you so were so quick to accuse > me of. > First up: I am sorry, I did not mean to offend. I apologize if I did. But I stand by my point: If this class is the only instance of this pattern, you'll only do this once. I see no reason to automate something that will run only once anyway. From your own reply to the above it seems that the *args-notation solves your problem (if I understand correctly). Since I'm patronizing by nature, I'd like to weigh in on this: The approach you describe seems like a Perl-ism[1]. *args is meant for variable argument lists. Using it as a shortcut for "many formal parameters" is misuse of that feature (not the worst kind, but not very good either). In addition to creating the impression that the function takes a variable number of arguments, it breaks introspection/self-documentation. Also, "many formal parameters" can be a signal to rethink the approach altogether. I feel that if a function has more than 6 or so parameters, I'm missing an opportunity to simplify my code. All of the above is philosophy, of course, and mine to boot, so feel free to ignore my rambling. But maybe you can elaborate a bit on why you need names *and* sequence of your parameters preserved and why there need to be so many of them. Perhaps a fresh perspective on this will yield a less problematic approach. Then again, maybe I have wasted your time enough already. ;) /W -- INVALID? DE! From steve at REMOVE-THIS-cybersource.com.au Sat Apr 3 22:03:45 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 04 Apr 2010 02:03:45 GMT Subject: off topic but please forgive me me and answer References: <4bb505c5$0$1133$4fafbaef@reader3.news.tin.it> <20100402214110.00a63457@geekmail.INVALID> <4bb73c0b$0$1125$4fafbaef@reader3.news.tin.it> <4bb75bea$0$27790$c3e8da3@news.astraweb.com> <63c2fbfa-cb74-4db3-adae-e79ce35dc9de@j21g2000yqh.googlegroups.com> Message-ID: <4bb7f380$0$8827$c3e8da3@news.astraweb.com> On Sat, 03 Apr 2010 09:35:34 -0700, Mensanator wrote: > On Apr 3, 10:17?am, Steven D'Aprano cybersource.com.au> wrote: >> On Sat, 03 Apr 2010 15:43:41 +0100, Martin P. Hellwig wrote: >> > I am replying to this post not because I disagree but because it >> > postalogically ?fits the best (I am by no means an expert either). >> >> > IMHO, the crackpot in this regard is actually partially right, >> > multiplication does mean that the number must get bigger, however for >> > fractions you multiply four numbers, two numerators and two >> > denominators. The resulting numerator and denominator by this >> > multiplication get indeed bigger. >> >> But you're not multiplying four numbers, > > You are if you're using Rationals. That is sheer unadulterated nonsense. A rational number (element of Q) is not a pair of numbers, it is a unique single point on the real number line R which does not depend on either the way you calculate it, or the representation you use to write it. The single number 1/2 can be written as any of 1/2, 2/4, 5/10, 1234/2468 or any of an infinite number of ratios representations. It can be written as a decimal expansion 0.5, or a binary expansion 0.1, or the negative- binary expansion 1.5, or as the base-eleven infinite expansion that starts as 0.55555... Numbers can also be written as continued fractions. The continued fraction representation for 1/2 is unexciting and happens to include two digits: [0; 2]. But the continued fraction representation of (say) 5/7 is [0; 1, 2, 2]. 5/7 isn't four numbers, or three, or two. It is one number. You might as well argue that 43/92 is "four numbers" -- you have a 4, and 3, and 9, and a 2, hence four numbers. The argument that 1/2 is two numbers is exactly as foolish as that. >> you're multiplying two numbers. > > Because they're expressed as Decimals. No, the number of operands is independent of the types of the operands. Multiplication is a binary operator: it takes exactly two arguments. Not four, or six, or one. Regardless of whether I write: Fraction(1,2)*Fraction(7,14) Decimal('0.5')*Decimal('0.5') 0.5*0.5 MyFraction.from_roman('I', 'II')*MyContinedFraction([0, 2, 0, 0, 0]) I still have two numbers being multiplied. >> One-half is not "two numbers", > > Sometimes it is. Only on Bizarro world. >> that would be a tuple > > Like this? > >>>> gmpy.mpq('0.5') > mpq(1,2) No, that's not a pair of numbers. It is a single number, equal to: ?(i=1,?,9/10**i) ---------------------- (ln(e)+sin(5?/2)) which is also a single number. >> or a list or >> possibly a coordinate pair. One-half is a single number, > > When dealing with crackpots, it does not help to use the wrong > arguments. And you think that telling the crackpot that he is right, multiplication always leads to bigger numbers, is somehow going to convince him that he is wrong about multiplication always leading to bigger numbers? > When multiplying gmpy.mpq(2,3) by gmpy.mpq(2,3), the > numerator and denominator have both indeed gotten bigger. So what? "One quarter" is bigger (longer) than "one half". Your point is? And in any case: >>> Fraction(3, 4)*Fraction(2, 3) Fraction(1, 2) Would you still like to argue that the numerator and denominator always get bigger when you multiply two fractions? > The trick is that when combined, the overall result is smaller. >> the number which >> if you double it gives one. >> >> Fortunately multiplication is consistent. Multiplying the two numbers >> 0.5 and 0.5 is exactly the same as multiplying 1*1 and 2*2 then >> dividing to get a single number. It's not the same as multiplying 1*1 >> and 2*2 to get two numbers, 1 and 4. >> >> You say that multiplication means that the number "must get bigger". > > Yes, not in every case, but in many cases it does. That makes no sense. It "must" get bigger, except for the cases where it doesn't? Or to put it another way: No, multiplication doesn't necessarily make numbers bigger. >> 5*1 = 5 >> 5*0 = 0 >> 5*-2 = -10 >> >> I hope you won't try to argue that 5, 0 and -10 are all bigger than 5. > > Yes, but these special cases don't help. It needs to be pointed out that > the argument is wrong even in cases like 2/3 * 2/3. The argument is that multiplication ALWAYS makes numbers bigger. Martin, out of some misguided and confused sense that the representation of a number was somehow relevant, argued that this is correct. It's not correct, not even for integers, let alone rationals. This is why I said that Martin should stop trying to justify the crackpot's belief that multiplication always makes numbers bigger, even a little bit. It's not even true for integers. It's not even true for positive (non-zero) integers. Arguments about numerators and denominators are just red-herrings. If the crackpot claimed that dolphins were fish, does it help to say he's partly right because dolphins live in water and have fins and a tail and a head just like fish? No. He wouldn't be partly right, he would be utterly, completely, 100% wrong, and he is utterly, completely, 100% wrong when he says multiplication always leads to bigger numbers. For many disagreements, neither party has it completely right and the truth lies somewhere in between. This is not one of them. Given two positions, that 1+1=2 and 1+1=7, the correct answer isn't halfway between them. Given two positions, that 1/2 multiplied by 1/2 is 1/4, or that 1/2 multiplied by 1/2 is NOT 1/4, the truth is not "both positions are partly correct". One position is just *wrong*. -- Steven From steve at REMOVE-THIS-cybersource.com.au Sat Apr 3 22:24:28 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 04 Apr 2010 02:24:28 GMT Subject: off topic but please forgive me me and answer References: <4bb505c5$0$1133$4fafbaef@reader3.news.tin.it> <20100402214110.00a63457@geekmail.INVALID> <4bb73c0b$0$1125$4fafbaef@reader3.news.tin.it> <08b9d5b5-5825-4d21-a68a-06a2d6183ee7@k19g2000yqn.googlegroups.com> Message-ID: <4bb7f85c$0$8827$c3e8da3@news.astraweb.com> On Sat, 03 Apr 2010 10:56:37 -0700, Patrick Maupin wrote: >> The square root of 2 is irrational, but if you multiply it by itself >> then the result isn't irrational, so not all operations involving >> irrational numbers will result in an irrational result (unless that's >> what you mean by "closely related irrational numbers"). > > Yes, I think I am closely related to myself. But in addition to that > particular disclaimer, I qualified the statement with "most" and I also > mentioned that zero is special. I stand by the assertion that if you > take a random assortment of non-zero numbers, some irrational, some > rational, and a random assortment of numeric operators, that most > operations involving an irrational number will have an irrational > result. There are an infinite number of rational numbers. There are an infinite number of irrational numbers. But the infinity of the rationals is countable (1, 2, 3, 4, ... or aleph-0) while the infinity of the irrationals is uncountable (c or aleph-1), so there are infinitely more irrationals than rationals. To put it another way, even though there are an infinite number of rationals, they are vanishingly rare compared to the irrationals. If you could choose a random number from the real number line, it almost certainly would be irrational. (This is not to be confused with floats, which of course are all rational numbers.) -- Steven From steve at REMOVE-THIS-cybersource.com.au Sat Apr 3 22:27:02 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 04 Apr 2010 02:27:02 GMT Subject: (a==b) ? 'Yes' : 'No' References: <7316f3d2-bcc9-4a1a-8598-cdd5d41fd74b@k17g2000yqb.googlegroups.com> Message-ID: <4bb7f8f6$0$8827$c3e8da3@news.astraweb.com> On Sun, 04 Apr 2010 12:26:05 +1200, Lawrence D'Oliveiro wrote: > In message , Steve > Holden wrote: > >> Lawrence D'Oliveiro wrote: >> >>> By the way, you don?t need the parentheses. >> >> But at the same time, if you don't *absolutely know* you don't need the >> parentheses ... > > But you can ?abolutely know??it?s all spelled out here > . Just keep that page > open every time you write Python code. Or, when in doubt, you can add redundant parentheses. It makes no difference to the runtime, and vanishingly small difference to the compile-time, and sometimes it aids readability. Writing the absolutely minimal code necessary to do what you want is not necessarily the best approach in all cases. I find, for instance, that redundant parentheses aid readability of complex logical and arithmetic expressions, especially if you include whitespace. -- Steven From steve at REMOVE-THIS-cybersource.com.au Sat Apr 3 22:38:26 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 04 Apr 2010 02:38:26 GMT Subject: Encryption source code with md5 References: <91541c26-6f18-40c7-a0df-252a52bb7cd5@l25g2000yqd.googlegroups.com> <4baf3ac4$0$22903$e4fe514c@news.xs4all.nl> Message-ID: <4bb7fba2$0$8827$c3e8da3@news.astraweb.com> On Sun, 04 Apr 2010 13:21:34 +1200, Lawrence D'Oliveiro wrote: > In message <4baf3ac4$0$22903$e4fe514c at news.xs4all.nl>, Irmen de Jong > wrote: > >> On 28-3-2010 12:08, Lawrence D'Oliveiro wrote: >> >>> Don?t use MD5. >> >> Also, md5 is not an encryption algorithm at all, it is a secure hashing >> function. > > You can use hash functions for encryption. The purpose of encryption is for the holder of the secret key to be able to reverse the encryption easily and reliably, while nobody else can. Hash functions fail on three counts. Since there is no secret key to a hash function, if you can reverse it, so can anyone. That alone rules it out as encryption. Secondly, hash functions are generally difficult to reverse. For cryptographic hash functions, ideally they should be impossible to reverse short of trying every possible input. Thirdly, even when reversible, hash functions have collisions. Consequently, you can't be sure whether you have found the intended message, or merely some random string which happens to accidentally hash to the same value. Admittedly if you found a message that *made sense*, you could make a probabilistic argument that it probably was the original message. The shorter the message, the more you could be confident that you had found the right one: there is probably only one short, grammatically correct, semantically meaningful English sentence of less than ten words that has a MD5 hex digest of 22008290c5d1ff0bd5fae9e425b01d41, so if you find one, it probably will be "Meet at railway station at 3pm". On the other hand, there are a very large number of (say) 20GB data files that hash to 22008290c5d1ff0bd5fae9e425b01d41, and probably no practical way of distinguishing the true message from the false collisions. Even if you can distinguish them, since the cost of reversing the hash is prohibitive, every false positive hurts you a lot. Of course, none of this is to prohibit using a hash function as a component of a larger encryption scheme. -- Steven From steve at REMOVE-THIS-cybersource.com.au Sat Apr 3 23:00:22 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 04 Apr 2010 03:00:22 GMT Subject: Splitting a string References: <450895af-d8ec-4312-a31e-569e39aaa319@w17g2000yqj.googlegroups.com> <737b6e81-71ef-430d-b5e7-dffdf1569fd7@g30g2000yqc.googlegroups.com> Message-ID: <4bb800c5$0$8827$c3e8da3@news.astraweb.com> On Sat, 03 Apr 2010 11:17:36 +0200, Peter Otten wrote: >> That's certainly faster than a list comprehension (at least on long >> lists), but it might be a little obscure why the "if not s:" is needed, > > The function is small; with a test suite covering the corner cases and > perhaps a comment* nothing should go wrong. > > (*) you can certainly improve on my attempt > >> so unless Thomas has a really long result list, he might want to just >> keep the list comprehension, which is (IMO) very readable. > > Generally speaking performing tests of which you know they can't fail > can confuse the reader just as much as tests with unobvious > interdependencies. I'm not sure I agree with you. Tests which you know can't fail are called assertions, pre-conditions and post-conditions. We test them because if we don't, they will fail :) -- Steven From pmaupin at gmail.com Sat Apr 3 23:01:29 2010 From: pmaupin at gmail.com (Patrick Maupin) Date: Sat, 3 Apr 2010 20:01:29 -0700 (PDT) Subject: off topic but please forgive me me and answer References: <4bb505c5$0$1133$4fafbaef@reader3.news.tin.it> <20100402214110.00a63457@geekmail.INVALID> <4bb73c0b$0$1125$4fafbaef@reader3.news.tin.it> <08b9d5b5-5825-4d21-a68a-06a2d6183ee7@k19g2000yqn.googlegroups.com> <4bb7f85c$0$8827$c3e8da3@news.astraweb.com> Message-ID: <88a6b4c3-e258-401e-8dff-e6a1e6855504@k17g2000yqb.googlegroups.com> On Apr 3, 9:24?pm, Steven D'Aprano wrote: > To put it another way, even though there are an infinite number of > rationals, they are vanishingly rare compared to the irrationals. If you > could choose a random number from the real number line, it almost > certainly would be irrational. Yet another correspondence between the set of numbers and the set of people ;-) From alfps at start.no Sat Apr 3 23:01:48 2010 From: alfps at start.no (Alf P. Steinbach) Date: Sun, 04 Apr 2010 05:01:48 +0200 Subject: Splitting a string In-Reply-To: <4bb800c5$0$8827$c3e8da3@news.astraweb.com> References: <450895af-d8ec-4312-a31e-569e39aaa319@w17g2000yqj.googlegroups.com> <737b6e81-71ef-430d-b5e7-dffdf1569fd7@g30g2000yqc.googlegroups.com> <4bb800c5$0$8827$c3e8da3@news.astraweb.com> Message-ID: * Steven D'Aprano: > > Tests which you know can't fail are called assertions, pre-conditions and > post-conditions. We test them because if we don't, they will fail :) :-) It's the umbrella law. Cheers, - Alf From steve at REMOVE-THIS-cybersource.com.au Sat Apr 3 23:09:43 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 04 Apr 2010 03:09:43 GMT Subject: How to access args as a list? References: Message-ID: <4bb802f7$0$8827$c3e8da3@news.astraweb.com> On Sat, 03 Apr 2010 22:58:43 +0000, kj wrote: > Suppose I have a function with the following signature: > > def spam(x, y, z): > # etc. > > Is there a way to refer, within the function, to all its arguments as a > single list? (I.e. I'm looking for Python's equivalent of Perl's @_ > variable.) Does this help? >>> def spam(a, b, c=3, d=4): ... pass ... >>> spam.__code__.co_varnames ('a', 'b', 'c', 'd') The hardest part is having the function know its own name. I see that you are already using the inspect module. That almost certainly is the correct approach. I'd be surprised if inspect is too heavyweight, but if it is, you can pull out the bits you need into your own function. -- Steven From pmaupin at gmail.com Sat Apr 3 23:10:20 2010 From: pmaupin at gmail.com (Patrick Maupin) Date: Sat, 3 Apr 2010 20:10:20 -0700 (PDT) Subject: Splitting a string References: <450895af-d8ec-4312-a31e-569e39aaa319@w17g2000yqj.googlegroups.com> <737b6e81-71ef-430d-b5e7-dffdf1569fd7@g30g2000yqc.googlegroups.com> <4bb800c5$0$8827$c3e8da3@news.astraweb.com> Message-ID: <4f4b70c3-3fa0-4deb-836d-3df1a55d7b66@r1g2000yqj.googlegroups.com> On Apr 3, 10:00?pm, Steven D'Aprano wrote: > Tests which you know can't fail are called assertions, pre-conditions and > post-conditions. We test them because if we don't, they will fail :) Well, yes, but that can get rather tedious at times: a = 1 assert 0 < a < 2 b = a + 3 assert 2 < b - a < 4 c = b * 5 assert not c % 5 At least, I usually ameliorate the pain a little bit by not bothering to print any debugging information at the assertions until one of them actually fails; otherwise I'd *never* get any real coding done :-) From gagsl-py2 at yahoo.com.ar Sat Apr 3 23:31:27 2010 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 04 Apr 2010 00:31:27 -0300 Subject: Question on templates and python logging References: <273877.70578.qm@web51101.mail.re2.yahoo.com> Message-ID: En Sat, 03 Apr 2010 20:42:20 -0300, David LePage escribi?: > The problem that i'm trying to solve is taking data collected along the > way and outputting this into these HTML pages. > [...] > I was hoping I could tie the logging classes into something like this, > where I was leveraging an HTML template, but also taking advantage of > the logging library since it works nicely for me today. Try this recipe: http://code.activestate.com/recipes/577025-loggingwebmonitor-a-central-logging-server-and-mon/ -- Gabriel Genellina From renws1990 at gmail.com Sun Apr 4 00:13:31 2010 From: renws1990 at gmail.com (Vincent Ren) Date: Sat, 3 Apr 2010 21:13:31 -0700 (PDT) Subject: How to keep effects of image filters going for some seconds? References: Message-ID: <25423bdc-901b-4306-87a4-3ca5e5baa3c4@l25g2000yqd.googlegroups.com> On Mar 22, 6:00?am, Terry Reedy wrote: > On 3/21/2010 3:23 AM, Ren Wenshan wrote: > > > > > Hello, every pythoner. > > > Firstly, I want to mention that English is my second language, so > > maybe there are some sentences which makes you confused, sorry. > > > I have been learning Panda3D, an open source 3D engine, these days. > > Now, I'm trying to write a small game for fun and practice. However, > > I've ran into a problem. > > > I want to make some speicaleffectsand there is my code: > > > def ventose(self): > > > ? ? ?global potato_HP > > > ? ? ?if potato_HP[0] == 1 and potato_HP[1] == 0: > > ? ? ?if random()> ?.30: > > ? ? ? ? ?self.filters.setCartoonInk(separation = 0.8) > > ? ? ? ? ?self.robotVincent.resetHead.start() > > ? ? ? ? ?self.decreaseVincentHP() > > ? ? ? ? ? ? ?Wait(3) > > ? ? ? ? ? ? ?self.fliters.delCartoonInk() > > > However, it doesn't work, the CartoonInk effect will never been shown > > in my game and I don't want my game to wait three seconds, what I need > > is tokeepthe effect for a period of time while the game run as well. > > The generic answer is to turn CartoonInk on and set a timed event for > now+ 3 secs to turn it off. You will have to understand how to interact > with the Panda event loop. For a more specific answer, follow Donn's > advice -- Panda forum. I know there was one when I looked at Panda a > year ago. > > > Besides that, I also want to show a counting back like "3", then "2", > > then "1", finally "Go". > > Ok, instead to events set 1 sec in future. > > Terry Jan Reedy thx, I've sloved my proble with doMethodLater() From timr at probo.com Sun Apr 4 00:58:01 2010 From: timr at probo.com (Tim Roberts) Date: Sat, 03 Apr 2010 21:58:01 -0700 Subject: Incorrect scope of list comprehension variables References: <87hbnsg75j.fsf@dpt-info.u-strasbg.fr> Message-ID: <917gr5hbv4un4367r9ld635dlgiliqb593@4ax.com> Alain Ketterlin wrote: > >I've just spent a few hours debugging code similar to this: > >d = dict() >for r in [1,2,3]: > d[r] = [r for r in [4,5,6]] >print d Yes, this has been fixed in later revisions, but I'm curious to know what led you to believe that a list comprehension created a new scope. I don't that was ever promised. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From tummalavpr at gmail.com Sun Apr 4 00:59:33 2010 From: tummalavpr at gmail.com (Earn Money) Date: Sat, 3 Apr 2010 21:59:33 -0700 (PDT) Subject: Build A Home Internet Business For Extra Income Stream Message-ID: Why build a residential home internet concern in the primary place? Believe it or not, the the human race saving is changing. While Multinational expanding to total saving, employees are the Mainly vulnerable classify of folks. Therefore, looking into A secondary earnings like build a residential home internet concern happen to An increasing viable option in favor of many. Why you indicate to build an Internet based concern in the midst of other.. For Details visit on http://internetcafeincome.com/ From only.samurai at gmail.com Sun Apr 4 01:14:13 2010 From: only.samurai at gmail.com (Andrew Ellis) Date: Sun, 4 Apr 2010 01:14:13 -0400 Subject: Good Intermediate Tutorials In-Reply-To: <1270320740.14862.1368150401@webmail.messagingengine.com> References: <4bb56d74$1@dnews.tpgi.com.au> <1270320740.14862.1368150401@webmail.messagingengine.com> Message-ID: That's actually why I picked up this list, and it's done a lot to help. +1 for sure On Sat, Apr 3, 2010 at 2:52 PM, wrote: > Pick an arbitrary point in time, and begin reading this mailing list's > archives. I guarantee you will learn alot. > > Malcolm > -- > http://mail.python.org/mailman/listinfo/python-list > > -- Andrew http://blog.psych0tik.net From mensanator at aol.com Sun Apr 4 02:13:51 2010 From: mensanator at aol.com (Mensanator) Date: Sat, 3 Apr 2010 23:13:51 -0700 (PDT) Subject: off topic but please forgive me me and answer References: <4bb505c5$0$1133$4fafbaef@reader3.news.tin.it> <20100402214110.00a63457@geekmail.INVALID> <4bb73c0b$0$1125$4fafbaef@reader3.news.tin.it> <4bb75bea$0$27790$c3e8da3@news.astraweb.com> <63c2fbfa-cb74-4db3-adae-e79ce35dc9de@j21g2000yqh.googlegroups.com> <4bb7f380$0$8827$c3e8da3@news.astraweb.com> Message-ID: <8c552d27-b7b5-409e-89a9-4ecc99249506@r1g2000yqb.googlegroups.com> On Apr 3, 9:03?pm, Steven D'Aprano wrote: > On Sat, 03 Apr 2010 09:35:34 -0700, Mensanator wrote: > > On Apr 3, 10:17?am, Steven D'Aprano > cybersource.com.au> wrote: > >> On Sat, 03 Apr 2010 15:43:41 +0100, Martin P. Hellwig wrote: > >> > I am replying to this post not because I disagree but because it > >> > postalogically ?fits the best (I am by no means an expert either). > > >> > IMHO, the crackpot in this regard is actually partially right, > >> > multiplication does mean that the number must get bigger, however for > >> > fractions you multiply four numbers, two numerators and two > >> > denominators. The resulting numerator and denominator by this > >> > multiplication get indeed bigger. > > >> But you're not multiplying four numbers, > > > You are if you're using Rationals. > > That is sheer unadulterated nonsense. You obviously don't understand the workings of computers. > > A rational number (element of Q) is not a pair of numbers, Duh. Everybody knows that. But sometimes it is represented by a pair of numbers such as 1/2 or mpq(1,2). > it is a unique > single point on the real number line R which does not depend on either > the way you calculate it, There are no "real number lines" inside my computer. > or the representation you use to write it. And if you want the computer to do a calculation, then you are dependent on its representation. > > The single number 1/2 can be written as any of 1/2, 2/4, 5/10, 1234/2468 > or any of an infinite number of ratios representations. It can be written > as a decimal expansion 0.5, or a binary expansion 0.1, or the negative- > binary expansion 1.5, or as the base-eleven infinite expansion that > starts as 0.55555... But we are only discussing those representations that are a pair of numbers: numerator & denominator. Now look who's talking nonsense, bringing up things like 0.55555... > > Numbers can also be written as continued fractions. The continued > fraction representation for 1/2 is unexciting and happens to include two > digits: [0; 2]. But the continued fraction representation of (say) 5/7 is > [0; 1, 2, 2]. 5/7 isn't four numbers, or three, or two. It is one number. You're on a roll, aren't you? > > You might as well argue that 43/92 is "four numbers" -- you have a 4, and > 3, and 9, and a 2, hence four numbers. The argument that 1/2 is two > numbers is exactly as foolish as that. Are you really that stupid? > > >> you're multiplying two numbers. > > > Because they're expressed as Decimals. > > No, the number of operands is independent of the types of the operands. > Multiplication is a binary operator: it takes exactly two arguments. Not > four, or six, or one. Regardless of whether I write: > > Fraction(1,2)*Fraction(7,14) > Decimal('0.5')*Decimal('0.5') > 0.5*0.5 > MyFraction.from_roman('I', 'II')*MyContinedFraction([0, 2, 0, 0, 0]) > > I still have two numbers being multiplied. And you claim that the internal workings of all the above are the same? > > >> One-half is not "two numbers", > > > Sometimes it is. > > Only on Bizarro world. I thought you were supposed to be a Python expert? That you're supposed to understand the difference between an object and its contents? Is [1,2,3,4] one number? Of course not, it's four numbers that are part of one object. A Rational is two numbers, one object. Yes, squaring a Rational does mean multiplying two objects, but you know damn well that it involves four numbers. > > >> that would be a tuple > > > Like this? > > >>>> gmpy.mpq('0.5') > > mpq(1,2) > > No, that's not a pair of numbers. Yes, it is. Two numbers, one object. Perhaps you need to read the Tutorial? > It is a single number, equal to: The word you want here is "object". This is exactly the reason these words were invented. They're probably spinning in their grave. > > ? ?(i=1,?,9/10**i) > ---------------------- > ? (ln(e)+sin(5?/2)) > > which is also a single number. "Object". > > >> or a list or > >> possibly a coordinate pair. One-half is a single number, > > > When dealing with crackpots, it does not help to use the wrong > > arguments. > > And you think that telling the crackpot that he is right, multiplication > always leads to bigger numbers, is somehow going to convince him that he > is wrong about multiplication always leading to bigger numbers? Of course not. But it may help the OP understand that's one of the main fallacies that crackpots often engage in. Focusing on something that's true but is a Non Sequitur. > > > When multiplying gmpy.mpq(2,3) by gmpy.mpq(2,3), the > > numerator and denominator have both indeed gotten bigger. > > So what? "One quarter" is bigger (longer) than "one half". Your point is? That in this case, multiplication did, in fact, make things larger. It didn't make the object larger, but the numbers it contains are. The crackpot focuses on the numbers while ignoring the object. For you to say only the object matters and it's smaller makes you just as wrong as the crackpot. > > And in any case: > > >>> Fraction(3, 4)*Fraction(2, 3) > > Fraction(1, 2) Now you're cheating. Again, you know damn well that Fraction(3, 4)*Fraction(2, 3) = Fraction(6,12) and what you're seeing is reduction to lowest terms. I take that back, maybe you really are that ignorant since you don't seem to grasp the concept of objects. > > Would you still like to argue that the numerator and denominator always > get bigger when you multiply two fractions? Yep. > > > The trick is that when combined, the overall result is smaller. > >> the number which > >> if you double it gives one. > > >> Fortunately multiplication is consistent. Multiplying the two numbers > >> 0.5 and 0.5 is exactly the same as multiplying 1*1 and 2*2 then > >> dividing to get a single number. It's not the same as multiplying 1*1 > >> and 2*2 to get two numbers, 1 and 4. > > >> You say that multiplication means that the number "must get bigger". > > > Yes, not in every case, but in many cases it does. > > That makes no sense. It "must" get bigger, except for the cases where it > doesn't? Or to put it another way: No, multiplication doesn't necessarily > make numbers bigger. > > >> 5*1 = 5 > >> 5*0 = 0 > >> 5*-2 = -10 > > >> I hope you won't try to argue that 5, 0 and -10 are all bigger than 5. > > > Yes, but these special cases don't help. It needs to be pointed out that > > the argument is wrong even in cases like 2/3 * 2/3. > > The argument is that multiplication ALWAYS makes numbers bigger. Martin, > out of some misguided and confused sense that the representation of a > number was somehow relevant, argued that this is correct. It's not > correct, not even for integers, let alone rationals. > > This is why I said that Martin should stop trying to justify the > crackpot's belief that multiplication always makes numbers bigger, even a > little bit. But then, you never understand where the crackpot is coming from. If the crackpot is, in fact, a troll, his goal is not to get you to believe his bogus math (which he knows is bogus), but to get you so confused you don't know what's right or how to defend it. > It's not even true for integers. It's not even true for > positive (non-zero) integers. Arguments about numerators and denominators > are just red-herrings. Right, as I said, a Non Sequitur. > > If the crackpot claimed that dolphins were fish, does it help to say he's > partly right because dolphins live in water and have fins and a tail and > a head just like fish? No. He wouldn't be partly right, he would be > utterly, completely, 100% wrong, and he is utterly, completely, 100% > wrong when he says multiplication always leads to bigger numbers. Sounds like you'll never understand math. Better stick to regular expressions. > > For many disagreements, neither party has it completely right and the > truth lies somewhere in between. This is not one of them. Given two > positions, that 1+1=2 and 1+1=7, the correct answer isn't halfway between > them. Given two positions, that 1/2 multiplied by 1/2 is 1/4, or that 1/2 > multiplied by 1/2 is NOT 1/4, the truth is not "both positions are partly > correct". One position is just *wrong*. And it seems you can't grasp the concept of a smaller forest having larger trees. > > -- > Steven From showell30 at yahoo.com Sun Apr 4 02:30:32 2010 From: showell30 at yahoo.com (Steve Howell) Date: Sat, 3 Apr 2010 23:30:32 -0700 (PDT) Subject: Incorrect scope of list comprehension variables References: <87hbnsg75j.fsf@dpt-info.u-strasbg.fr> <917gr5hbv4un4367r9ld635dlgiliqb593@4ax.com> Message-ID: On Apr 3, 9:58?pm, Tim Roberts wrote: > Alain Ketterlin wrote: > > >I've just spent a few hours debugging code similar to this: > > >d = dict() > >for r in [1,2,3]: > > ? ?d[r] = [r for r in [4,5,6]] > >print d > > Yes, this has been fixed in later revisions, but I'm curious to know what > led you to believe that a list comprehension created a new scope. ?I don't > that was ever promised. Common sense about how programming languages should work? As confirmed by later revisions? From apt.shansen at gmail.invalid Sun Apr 4 03:17:43 2010 From: apt.shansen at gmail.invalid (Stephen Hansen) Date: Sun, 4 Apr 2010 00:17:43 -0700 Subject: Incorrect scope of list comprehension variables References: <87hbnsg75j.fsf@dpt-info.u-strasbg.fr> <917gr5hbv4un4367r9ld635dlgiliqb593@4ax.com> Message-ID: <2010040400174371179-aptshansen@gmailinvalid> On 2010-04-03 23:30:32 -0700, Steve Howell said: > On Apr 3, 9:58?pm, Tim Roberts wrote: >> Alain Ketterlin wrote: >> >>> I've just spent a few hours debugging code similar to this: >> >>> d = dict() >>> for r in [1,2,3]: >>> ? ?d[r] = [r for r in [4,5,6]] >>> print d >> >> Yes, this has been fixed in later revisions, but I'm curious to know what >> led you to believe that a list comprehension created a new scope. ?I don't >> that was ever promised. > > Common sense about how programming languages should work? As > confirmed by later revisions? Where exactly does this common sense come from? A list comprehension is basically syntactic sugar over a for loop, and... Python 3.1.2 (r312:79360M, Mar 24 2010, 01:33:18) [GCC 4.0.1 (Apple Inc. build 5493)] on darwin Type "copyright", "credits" or "license()" for more information. >>> for x in range(10): pass >>> x 9 -- --S ... p.s: change the ".invalid" to ".com" in email address to reply privately. From steve at REMOVE-THIS-cybersource.com.au Sun Apr 4 03:37:01 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 04 Apr 2010 07:37:01 GMT Subject: Splitting a string References: <450895af-d8ec-4312-a31e-569e39aaa319@w17g2000yqj.googlegroups.com> <737b6e81-71ef-430d-b5e7-dffdf1569fd7@g30g2000yqc.googlegroups.com> <4bb800c5$0$8827$c3e8da3@news.astraweb.com> <4f4b70c3-3fa0-4deb-836d-3df1a55d7b66@r1g2000yqj.googlegroups.com> Message-ID: <4bb8419d$0$8827$c3e8da3@news.astraweb.com> On Sat, 03 Apr 2010 20:10:20 -0700, Patrick Maupin wrote: > On Apr 3, 10:00?pm, Steven D'Aprano cybersource.com.au> wrote: >> Tests which you know can't fail are called assertions, pre-conditions >> and post-conditions. We test them because if we don't, they will fail >> :) > > Well, yes, but that can get rather tedious at times: > > a = 1 > assert 0 < a < 2 Please tell me that's just an exaggerated example for illustration purposes, and that you don't *actually* do that! In any case, the *right* test would be: a = 1 assert a == 1 and a*5==5 and str(a)=='1' and [None,a,None][a] is a *wink* > At least, I usually ameliorate the pain a little bit by not bothering to > print any debugging information at the assertions until one of them > actually fails; otherwise I'd *never* get any real coding done :-) Ditto. -- Steven From saimapk81 at gmail.com Sun Apr 4 03:56:58 2010 From: saimapk81 at gmail.com (saima81) Date: Sun, 4 Apr 2010 00:56:58 -0700 (PDT) Subject: "JOBS IN CALIFORNIA" "jobs in california orange county" "jobs in california for british" "jobs in california los angeles" "jobs in california usa" "california jobs" "california jobs for canadians" ON http://jobsincalifornia-usa.blogspot.com/ Message-ID: <7e50344b-1e4a-4efb-84b5-ca8e8c3abdbf@q16g2000yqq.googlegroups.com> "JOBS IN CALIFORNIA" "jobs in california orange county" "jobs in california for british" "jobs in california los angeles" "jobs in california usa" "california jobs" "california jobs for canadians" ON http://jobsincalifornia-usa.blogspot.com/ "JOBS IN CALIFORNIA" "jobs in california orange county" "jobs in california for british" "jobs in california los angeles" "jobs in california usa" "california jobs" "california jobs for canadians" ON http://jobsincalifornia-usa.blogspot.com/ "JOBS IN CALIFORNIA" "jobs in california orange county" "jobs in california for british" "jobs in california los angeles" "jobs in california usa" "california jobs" "california jobs for canadians" ON http://jobsincalifornia-usa.blogspot.com/ "JOBS IN CALIFORNIA" "jobs in california orange county" "jobs in california for british" "jobs in california los angeles" "jobs in california usa" "california jobs" "california jobs for canadians" ON http://jobsincalifornia-usa.blogspot.com/ "JOBS IN CALIFORNIA" "jobs in california orange county" "jobs in california for british" "jobs in california los angeles" "jobs in california usa" "california jobs" "california jobs for canadians" ON http://jobsincalifornia-usa.blogspot.com/ "JOBS IN CALIFORNIA" "jobs in california orange county" "jobs in california for british" "jobs in california los angeles" "jobs in california usa" "california jobs" "california jobs for canadians" ON http://jobsincalifornia-usa.blogspot.com/ "JOBS IN CALIFORNIA" "jobs in california orange county" "jobs in california for british" "jobs in california los angeles" "jobs in california usa" "california jobs" "california jobs for canadians" ON http://jobsincalifornia-usa.blogspot.com/ "JOBS IN CALIFORNIA" "jobs in california orange county" "jobs in california for british" "jobs in california los angeles" "jobs in california usa" "california jobs" "california jobs for canadians" ON http://jobsincalifornia-usa.blogspot.com/ "JOBS IN CALIFORNIA" "jobs in california orange county" "jobs in california for british" "jobs in california los angeles" "jobs in california usa" "california jobs" "california jobs for canadians" ON http://jobsincalifornia-usa.blogspot.com/ "JOBS IN CALIFORNIA" "jobs in california orange county" "jobs in california for british" "jobs in california los angeles" "jobs in california usa" "california jobs" "california jobs for canadians" ON http://jobsincalifornia-usa.blogspot.com/ "JOBS IN CALIFORNIA" "jobs in california orange county" "jobs in california for british" "jobs in california los angeles" "jobs in california usa" "california jobs" "california jobs for canadians" ON http://jobsincalifornia-usa.blogspot.com/ "JOBS IN CALIFORNIA" "jobs in california orange county" "jobs in california for british" "jobs in california los angeles" "jobs in california usa" "california jobs" "california jobs for canadians" ON http://jobsincalifornia-usa.blogspot.com/ "JOBS IN CALIFORNIA" "jobs in california orange county" "jobs in california for british" "jobs in california los angeles" "jobs in california usa" "california jobs" "california jobs for canadians" ON http://jobsincalifornia-usa.blogspot.com/ "JOBS IN CALIFORNIA" "jobs in california orange county" "jobs in california for british" "jobs in california los angeles" "jobs in california usa" "california jobs" "california jobs for canadians" ON http://jobsincalifornia-usa.blogspot.com/ "JOBS IN CALIFORNIA" "jobs in california orange county" "jobs in california for british" "jobs in california los angeles" "jobs in california usa" "california jobs" "california jobs for canadians" ON http://jobsincalifornia-usa.blogspot.com/ "JOBS IN CALIFORNIA" "jobs in california orange county" "jobs in california for british" "jobs in california los angeles" "jobs in california usa" "california jobs" "california jobs for canadians" ON http://jobsincalifornia-usa.blogspot.com/ "JOBS IN CALIFORNIA" "jobs in california orange county" "jobs in california for british" "jobs in california los angeles" "jobs in california usa" "california jobs" "california jobs for canadians" ON http://jobsincalifornia-usa.blogspot.com/ "JOBS IN CALIFORNIA" "jobs in california orange county" "jobs in california for british" "jobs in california los angeles" "jobs in california usa" "california jobs" "california jobs for canadians" ON http://jobsincalifornia-usa.blogspot.com/ "JOBS IN CALIFORNIA" "jobs in california orange county" "jobs in california for british" "jobs in california los angeles" "jobs in california usa" "california jobs" "california jobs for canadians" ON http://jobsincalifornia-usa.blogspot.com/ "JOBS IN CALIFORNIA" "jobs in california orange county" "jobs in california for british" "jobs in california los angeles" "jobs in california usa" "california jobs" "california jobs for canadians" ON http://jobsincalifornia-usa.blogspot.com/ "JOBS IN CALIFORNIA" "jobs in california orange county" "jobs in california for british" "jobs in california los angeles" "jobs in california usa" "california jobs" "california jobs for canadians" ON http://jobsincalifornia-usa.blogspot.com/ "JOBS IN CALIFORNIA" "jobs in california orange county" "jobs in california for british" "jobs in california los angeles" "jobs in california usa" "california jobs" "california jobs for canadians" ON http://jobsincalifornia-usa.blogspot.com/ "JOBS IN CALIFORNIA" "jobs in california orange county" "jobs in california for british" "jobs in california los angeles" "jobs in california usa" "california jobs" "california jobs for canadians" ON http://jobsincalifornia-usa.blogspot.com/ "JOBS IN CALIFORNIA" "jobs in california orange county" "jobs in california for british" "jobs in california los angeles" "jobs in california usa" "california jobs" "california jobs for canadians" ON http://jobsincalifornia-usa.blogspot.com/ "JOBS IN CALIFORNIA" "jobs in california orange county" "jobs in california for british" "jobs in california los angeles" "jobs in california usa" "california jobs" "california jobs for canadians" ON http://jobsincalifornia-usa.blogspot.com/ "JOBS IN CALIFORNIA" "jobs in california orange county" "jobs in california for british" "jobs in california los angeles" "jobs in california usa" "california jobs" "california jobs for canadians" ON http://jobsincalifornia-usa.blogspot.com/ "JOBS IN CALIFORNIA" "jobs in california orange county" "jobs in california for british" "jobs in california los angeles" "jobs in california usa" "california jobs" "california jobs for canadians" ON http://jobsincalifornia-usa.blogspot.com/ "JOBS IN CALIFORNIA" "jobs in california orange county" "jobs in california for british" "jobs in california los angeles" "jobs in california usa" "california jobs" "california jobs for canadians" ON http://jobsincalifornia-usa.blogspot.com/ "JOBS IN CALIFORNIA" "jobs in california orange county" "jobs in california for british" "jobs in california los angeles" "jobs in california usa" "california jobs" "california jobs for canadians" ON http://jobsincalifornia-usa.blogspot.com/ "JOBS IN CALIFORNIA" "jobs in california orange county" "jobs in california for british" "jobs in california los angeles" "jobs in california usa" "california jobs" "california jobs for canadians" ON http://jobsincalifornia-usa.blogspot.com/ "JOBS IN CALIFORNIA" "jobs in california orange county" "jobs in california for british" "jobs in california los angeles" "jobs in california usa" "california jobs" "california jobs for canadians" ON http://jobsincalifornia-usa.blogspot.com/ "JOBS IN CALIFORNIA" "jobs in california orange county" "jobs in california for british" "jobs in california los angeles" "jobs in california usa" "california jobs" "california jobs for canadians" ON http://jobsincalifornia-usa.blogspot.com/ "JOBS IN CALIFORNIA" "jobs in california orange county" "jobs in california for british" "jobs in california los angeles" "jobs in california usa" "california jobs" "california jobs for canadians" ON http://jobsincalifornia-usa.blogspot.com/ "JOBS IN CALIFORNIA" "jobs in california orange county" "jobs in california for british" "jobs in california los angeles" "jobs in california usa" "california jobs" "california jobs for canadians" ON http://jobsincalifornia-usa.blogspot.com/ "JOBS IN CALIFORNIA" "jobs in california orange county" "jobs in california for british" "jobs in california los angeles" "jobs in california usa" "california jobs" "california jobs for canadians" ON http://jobsincalifornia-usa.blogspot.com/ "JOBS IN CALIFORNIA" "jobs in california orange county" "jobs in california for british" "jobs in california los angeles" "jobs in california usa" "california jobs" "california jobs for canadians" ON http://jobsincalifornia-usa.blogspot.com/ "JOBS IN CALIFORNIA" "jobs in california orange county" "jobs in california for british" "jobs in california los angeles" "jobs in california usa" "california jobs" "california jobs for canadians" ON http://jobsincalifornia-usa.blogspot.com/ "JOBS IN CALIFORNIA" "jobs in california orange county" "jobs in california for british" "jobs in california los angeles" "jobs in california usa" "california jobs" "california jobs for canadians" ON http://jobsincalifornia-usa.blogspot.com/ "JOBS IN CALIFORNIA" "jobs in california orange county" "jobs in california for british" "jobs in california los angeles" "jobs in california usa" "california jobs" "california jobs for canadians" ON http://jobsincalifornia-usa.blogspot.com/ "JOBS IN CALIFORNIA" "jobs in california orange county" "jobs in california for british" "jobs in california los angeles" "jobs in california usa" "california jobs" "california jobs for canadians" ON http://jobsincalifornia-usa.blogspot.com/ "JOBS IN CALIFORNIA" "jobs in california orange county" "jobs in california for british" "jobs in california los angeles" "jobs in california usa" "california jobs" "california jobs for canadians" ON http://jobsincalifornia-usa.blogspot.com/ "JOBS IN CALIFORNIA" "jobs in california orange county" "jobs in california for british" "jobs in california los angeles" "jobs in california usa" "california jobs" "california jobs for canadians" ON http://jobsincalifornia-usa.blogspot.com/ "JOBS IN CALIFORNIA" "jobs in california orange county" "jobs in california for british" "jobs in california los angeles" "jobs in california usa" "california jobs" "california jobs for canadians" ON http://jobsincalifornia-usa.blogspot.com/ "JOBS IN CALIFORNIA" "jobs in california orange county" "jobs in california for british" "jobs in california los angeles" "jobs in california usa" "california jobs" "california jobs for canadians" ON http://jobsincalifornia-usa.blogspot.com/ "JOBS IN CALIFORNIA" "jobs in california orange county" "jobs in california for british" "jobs in california los angeles" "jobs in california usa" "california jobs" "california jobs for canadians" ON http://jobsincalifornia-usa.blogspot.com/ "JOBS IN CALIFORNIA" "jobs in california orange county" "jobs in california for british" "jobs in california los angeles" "jobs in california usa" "california jobs" "california jobs for canadians" ON http://jobsincalifornia-usa.blogspot.com/ "JOBS IN CALIFORNIA" "jobs in california orange county" "jobs in california for british" "jobs in california los angeles" "jobs in california usa" "california jobs" "california jobs for canadians" ON http://jobsincalifornia-usa.blogspot.com/ "JOBS IN CALIFORNIA" "jobs in california orange county" "jobs in california for british" "jobs in california los angeles" "jobs in california usa" "california jobs" "california jobs for canadians" ON http://jobsincalifornia-usa.blogspot.com/ From catalinfest at gmail.com Sun Apr 4 04:42:19 2010 From: catalinfest at gmail.com (catalinfest at gmail.com) Date: Sun, 4 Apr 2010 01:42:19 -0700 (PDT) Subject: vars().has_key() question about how working . Message-ID: Hi everyone . My questions is "why vars().has_key('b') is False ?' I expecting to see "True" because is a variable ... Thanks Please see code bellow . >>> x=11 >>> def something(): ... b=25 ... >>> vars().has_key('x') True >>> vars().has_key('b') False >>> globals().has_key('x') True >>> globals().has_key('b') False >>> From clp2 at rebertia.com Sun Apr 4 04:51:09 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Sun, 4 Apr 2010 01:51:09 -0700 Subject: vars().has_key() question about how working . In-Reply-To: References: Message-ID: On Sun, Apr 4, 2010 at 1:42 AM, catalinfest at gmail.com wrote: > Hi everyone . > My questions is "why vars().has_key('b') is False ?' > I expecting to see "True" because is a variable ... The built-in constants and functions aren't global variables, they're in the special __builtins__ dictionary/namespace, and thus not part of globals() or vars(). Cheers, Chris -- http://blog.rebertia.com From ptmcg at austin.rr.com Sun Apr 4 04:59:23 2010 From: ptmcg at austin.rr.com (Paul McGuire) Date: Sun, 4 Apr 2010 01:59:23 -0700 (PDT) Subject: vars().has_key() question about how working . References: Message-ID: On Apr 4, 3:42?am, "catalinf... at gmail.com" wrote: > Hi everyone . > My questions is "why vars().has_key('b') is False ?' > I expecting to see "True" because is a variable ... > Thanks Yes, 'b' is a var, but only within the scope of something(). See how this is different: >>> def sth(): ... b = 25 ... print 'b' in vars() ... >>> sth() True (Also, has_key() is the old-style way to test for key existence in a dict, and is kept around for compatibility with old code, but the preferred method now is to use 'in'.) -- Paul From catalinfest at gmail.com Sun Apr 4 05:02:13 2010 From: catalinfest at gmail.com (Cata) Date: Sun, 4 Apr 2010 12:02:13 +0300 Subject: vars().has_key() question about how working . In-Reply-To: References: Message-ID: So is not possible to testing if a variable is defined with this functions vars(), globals(), locals() ? Or maybe i make confusion with another issue. Please more specific ... Thank you 2010/4/4 Chris Rebert > On Sun, Apr 4, 2010 at 1:42 AM, catalinfest at gmail.com > wrote: > > Hi everyone . > > My questions is "why vars().has_key('b') is False ?' > > I expecting to see "True" because is a variable ... > > The built-in constants and functions aren't global variables, they're > in the special __builtins__ dictionary/namespace, and thus not part of > globals() or vars(). > > Cheers, > Chris > -- > http://blog.rebertia.com > -------------- next part -------------- An HTML attachment was scrubbed... URL: From clp2 at rebertia.com Sun Apr 4 05:16:14 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Sun, 4 Apr 2010 02:16:14 -0700 Subject: vars().has_key() question about how working . In-Reply-To: References: Message-ID: > 2010/4/4 Chris Rebert >> >> On Sun, Apr 4, 2010 at 1:42 AM, catalinfest at gmail.com >> wrote: >> > Hi everyone . >> > My questions is "why vars().has_key('b') is False ?' >> > I expecting to see "True" because is a variable ... >> >> The built-in constants and functions aren't global variables, they're >> in the special __builtins__ dictionary/namespace, and thus not part of >> globals() or vars(). On Sun, Apr 4, 2010 at 2:02 AM, Cata wrote: > So is not possible to testing if a variable is defined with this functions > vars(), globals(), locals() ? No, you just need to add another case for __builtins__ The scopes Python consults when looking up a name are: 1. Local scope - locals() 2. Nested function scope(s) - [I don't think these vars can be listed at runtime] 3. Global scope - globals() 4. Built-ins - __builtins__ If you want to just check whether a variable is currently defined+accessible, a try-except is much simpler: var_name = "foo" try: eval(var_name) except NameError: defined = False else: defined = True However, wanting to test whether a variable is defined or not is usually a sign of bad code. Could you explain exactly why you want/need to do such testing? Cheers, Chris -- http://blog.rebertia.com From bieffe62 at gmail.com Sun Apr 4 05:17:59 2010 From: bieffe62 at gmail.com (Francesco Bochicchio) Date: Sun, 4 Apr 2010 02:17:59 -0700 (PDT) Subject: passing command line arguments to executable References: <4a636ae6-d68a-4b34-8e3f-9c11aa352793@g11g2000yqe.googlegroups.com> <5d3a56da-aab2-4715-b288-1c9de47c9ece@k13g2000yqe.googlegroups.com> <404ca155-866e-45d0-b496-a37e9fb9155a@10g2000yqq.googlegroups.com> Message-ID: On 3 Apr, 19:20, mcanjo wrote: > On Apr 3, 11:15?am, Patrick Maupin wrote: > > > > > On Apr 3, 11:09?am, mcanjo wrote: > > > > I have an executable (I don't have access to the source code) that > > > processes some data. I double click on the icon and a Command prompt > > > window pops up. The program asks me for the input file, I hit enter, > > > and then it asks me for and output filename, I hit enter a second time > > > and it goes off and does its thing and when it is finished running the > > > Command Prompt goes away and I have my new output file in the same > > > directory as my executable and input file. I would like to be able to > > > batch process a group of files. I thought about using "os.spawnv()" in > > > a loop and at each iteration of the loop passing in the file in and > > > out names but that didn't work. Does anyone have any ideas? > > > You need to look at the subprocess module, and use pipes. > > > Regards, > > Pat > > I tried doing the following code: > > from subprocess import Popen > from subprocess import PIPE, STDOUT > exefile = Popen('pmm.exe', stdout = PIPE, stdin = PIPE, stderr = > STDOUT) > exefile.communicate('MarchScreen.pmm\nMarchScreen.out')[0] > > and the Command Prompt opened and closed, no exceptions were generated > but the program didn't run. Am I doing something wrong? I would try a couple of things (never done what you are trying to do, so my suggestions may be useless ): 1. use shell=True as parameter of Popen 2. capture the output of communicate method, which returns whatever the process emits on standard output and standard error: there could be some message that give you hints about the solution. Ciao -- FB From clp2 at rebertia.com Sun Apr 4 05:18:15 2010 From: clp2 at rebertia.com (Chris Rebert) Date: Sun, 4 Apr 2010 02:18:15 -0700 Subject: vars().has_key() question about how working . In-Reply-To: References: Message-ID: Ah, (bleep). Disregard both my responses. Darn headache. Cheers, Chris -- Definitely going to bed now. http://blog.rebertia.com From __peter__ at web.de Sun Apr 4 05:58:25 2010 From: __peter__ at web.de (Peter Otten) Date: Sun, 04 Apr 2010 11:58:25 +0200 Subject: Splitting a string References: <450895af-d8ec-4312-a31e-569e39aaa319@w17g2000yqj.googlegroups.com> <737b6e81-71ef-430d-b5e7-dffdf1569fd7@g30g2000yqc.googlegroups.com> <4bb800c5$0$8827$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano wrote: > On Sat, 03 Apr 2010 11:17:36 +0200, Peter Otten wrote: > >>> That's certainly faster than a list comprehension (at least on long >>> lists), but it might be a little obscure why the "if not s:" is needed, >> >> The function is small; with a test suite covering the corner cases and >> perhaps a comment* nothing should go wrong. >> >> (*) you can certainly improve on my attempt >> >>> so unless Thomas has a really long result list, he might want to just >>> keep the list comprehension, which is (IMO) very readable. >> >> Generally speaking performing tests of which you know they can't fail >> can confuse the reader just as much as tests with unobvious >> interdependencies. > > > I'm not sure I agree with you. I'm going to help you make up your mind ;) > Tests which you know can't fail are called assertions, pre-conditions and > post-conditions. We test them because if we don't, they will fail :) Note that I said /can/ not /do/ confuse. Consider the actual context, removing a special value from the start/end of a list: (1) if parts[0] == "": del parts[0] if not parts: return parts if parts[-1] == "": del parts[-1] return parts (2) return [item for item in parts if item != ""] Now assume you have to familiarize yourself with the above code. Variant (1) clearly expresses that the code is meant to touch only the first and last item. (2) could be just removing all empty strings from a list. Another way to look at it: it is much easier to refactor from (1) to (2) than from (2) to (1). As to assertions etc: you don't perform arbitrary tests like assert 42 == 42, you make estimates about what can go wrong if you get unexpected input or make an error in an algorithm that you cannot safely grasp in its entirety. As an example you could add assert "" not in parts[1:-1] as a precondition to the above snippets. The superfluous tests in the list comprehension are the opposite of that assertion: they could eat items == "" in the list that either are intended to pass through or that indicate an error in code above. Personally, though, I prefer unit tests over assertions. Peter From bieffe62 at gmail.com Sun Apr 4 06:11:59 2010 From: bieffe62 at gmail.com (Francesco Bochicchio) Date: Sun, 4 Apr 2010 03:11:59 -0700 (PDT) Subject: How to access args as a list? References: Message-ID: <9e1c511b-6f63-48ac-a288-52903d6e117d@35g2000yqm.googlegroups.com> On 4 Apr, 00:58, kj wrote: > Suppose I have a function with the following signature: > > def spam(x, y, z): > ? ? # etc. > > Is there a way to refer, within the function, to all its arguments > as a single list? ?(I.e. I'm looking for Python's equivalent of > Perl's @_ variable.) > > I'm aware of locals(), but I want to preserve the order in which > the arguments appear in the signature. > > My immediate aim is to set up a simple class that will allow me to > iterate over the arguments passed to the constructor (plus let me > refer to these individual arguments by their names using an > instance.attribute syntax, as usual). > > The best I have managed looks like this: > > class _Spam(object): > ? ? def __init__(self, x, y, z): > ? ? ? ? self.__dict__ = OrderedDict(()) > ? ? ? ? for p in inspect.getargspec(_Spam.__init__).args[1:]: > ? ? ? ? ? ? self.__dict__[p] = locals()[p] > > ? ? def __iter__(self): > ? ? ? ? return iter(self.__dict__.values()) > > but rolling out inspect.getargspec for this sort of thing looks to > me like overkill. ?Is there a more basic approach? > > P.S. this is just an example; the function I want to implement has > more parameters in its signature, with longer, more informative > names. Hi, I once tried something to emulate in python the way Scala language allows to automatically generate class attributes from constructor parameter. I never tried in real code, but see if it fits your bill. It uses class decorators though, so only works with python3. Here is my code: class FieldsDecorator: """It adds a generic scala-like constructor to a class. You can create as instance as c = MyClass(f1=3, f2=4) and have automatically c.f1=3, c.f2=4. Only parameter names listed in the decorator are allowed. """ def __init__(self, *names): self.names = names def __call__(self, cls): def constructor(instance, **kwds): for n,v in kwds.items(): if n in self.names: setattr(instance, n, v) else: raise TypeError("%s is not a valid field" % s ) setattr(cls, '__init__', constructor ) return cls @FieldsDecorator("uno", "due") class Prova: pass p = Prova(uno=12, due=9) print (p.uno, p.due ) Ciao ---- FB From albert at spenarnc.xs4all.nl Sun Apr 4 07:28:15 2010 From: albert at spenarnc.xs4all.nl (Albert van der Horst) Date: 04 Apr 2010 11:28:15 GMT Subject: Is there any library for indexing binary data? References: Message-ID: In article , =?GB2312?B?zPC5zw==?= wrote: >Well, Database is not proper because 1. the table is very big (~10^9 >rows) 2. we should support very fast *simple* query that is to get >value corresponding to single key (~10^7 queries / second). > >Currently, I have implemented a specific algorithm to deal with my >problem. However, I want to employ some library to simplify codings, >otherwise I have to write my own code for each big table. It is >possible that, after using indexing library, the program cannot run as >fast as homemade code. But if it can greatly simplify my job and can >provide satisfied speed (eg 10^5~10^6 queries / second), the indexing >library is still a good choice for me. At first sight this looks to me like B-trees would be an ideal solution. The first levels of the tree are in memory, so with some luck you have only one or two disk accesses per search. > >-- >ShenLei > Groetjes Albert -- -- Albert van der Horst, UTRECHT,THE NETHERLANDS Economic growth -- being exponential -- ultimately falters. albert at spe&ar&c.xs4all.nl &=n http://home.hccnet.nl/a.w.m.van.der.horst From simon at brunningonline.net Sun Apr 4 07:32:33 2010 From: simon at brunningonline.net (Simon Brunning) Date: Sun, 4 Apr 2010 12:32:33 +0100 Subject: passing command line arguments to executable In-Reply-To: <404ca155-866e-45d0-b496-a37e9fb9155a@10g2000yqq.googlegroups.com> References: <4a636ae6-d68a-4b34-8e3f-9c11aa352793@g11g2000yqe.googlegroups.com> <5d3a56da-aab2-4715-b288-1c9de47c9ece@k13g2000yqe.googlegroups.com> <404ca155-866e-45d0-b496-a37e9fb9155a@10g2000yqq.googlegroups.com> Message-ID: On 3 April 2010 18:20, mcanjo wrote: > I tried doing the following code: > > from subprocess import Popen > from subprocess import PIPE, STDOUT > exefile = Popen('pmm.exe', stdout = PIPE, stdin = PIPE, stderr = > STDOUT) > exefile.communicate('MarchScreen.pmm\nMarchScreen.out')[0] > > and the Command Prompt opened and closed, no exceptions were generated > but the program didn't run. Am I doing something wrong? Have you tried running pmm.exe from the command line? What does that look like? Does it matter what the current working directory is at the time? -- Cheers, Simon B. From usenot at geekmail.INVALID Sun Apr 4 07:59:57 2010 From: usenot at geekmail.INVALID (Andreas Waldenburger) Date: Sun, 4 Apr 2010 13:59:57 +0200 Subject: off topic but please forgive me me and answer References: <4bb505c5$0$1133$4fafbaef@reader3.news.tin.it> <20100402214110.00a63457@geekmail.INVALID> <4bb73c0b$0$1125$4fafbaef@reader3.news.tin.it> <4bb75bea$0$27790$c3e8da3@news.astraweb.com> <63c2fbfa-cb74-4db3-adae-e79ce35dc9de@j21g2000yqh.googlegroups.com> <4bb7f380$0$8827$c3e8da3@news.astraweb.com> <8c552d27-b7b5-409e-89a9-4ecc99249506@r1g2000yqb.googlegroups.com> Message-ID: <20100404135957.7d76fbef@geekmail.INVALID> On Sat, 3 Apr 2010 23:13:51 -0700 (PDT) Mensanator wrote: > On Apr 3, 9:03?pm, Steven D'Aprano cybersource.com.au> wrote: > > On Sat, 03 Apr 2010 09:35:34 -0700, Mensanator wrote: > > > On Apr 3, 10:17?am, Steven D'Aprano > > cybersource.com.au> wrote: > > >> But you're not multiplying four numbers, > > > > > You are if you're using Rationals. > > > > That is sheer unadulterated nonsense. > > You obviously don't understand the workings of computers. > Now this is what's wrong about internet discussions. Nobody actually defines what they are talking about *until* it becomes a problem. And then the retconning starts. This discussion up to this point had not explicitly been about the workings of computers. It had not really explicitly been about mathematical numbers either (although to my understanding this had been implicit, but that's personal). Let this be a reminder that defining your terms is one of the best ideas ever. Its the reason for the success of mathematics. I'd like it to be a reason for the success of discussions as well. /W PS: Accusing someone publicly of "obviously" not understanding [some topic] is pretty low by any standards. And especially so when the argument for doing so is bogus: Computers by themselves have as much a notion of Rationals as they have of Irrationals, or, for that matter, the cuteness puppies. Software does. -- INVALID? DE! From usenot at geekmail.INVALID Sun Apr 4 08:09:40 2010 From: usenot at geekmail.INVALID (Andreas Waldenburger) Date: Sun, 4 Apr 2010 14:09:40 +0200 Subject: off topic but please forgive me me and answer References: <4bb505c5$0$1133$4fafbaef@reader3.news.tin.it> <20100402214110.00a63457@geekmail.INVALID> <4bb73c0b$0$1125$4fafbaef@reader3.news.tin.it> <4bb75bea$0$27790$c3e8da3@news.astraweb.com> <63c2fbfa-cb74-4db3-adae-e79ce35dc9de@j21g2000yqh.googlegroups.com> <4bb7f380$0$8827$c3e8da3@news.astraweb.com> <8c552d27-b7b5-409e-89a9-4ecc99249506@r1g2000yqb.googlegroups.com> <20100404135957.7d76fbef@geekmail.INVALID> Message-ID: <20100404140940.4402de11@geekmail.INVALID> On Sun, 4 Apr 2010 13:59:57 +0200 Andreas Waldenburger wrote: > Computers by themselves have as much a notion of Rationals as they > have of Irrationals, or, for that matter, the cuteness puppies. Strike that. Floats in computers are Rationals. So computers do know them. However, they are still not "two numbers". /W -- INVALID? DE! From steve at REMOVE-THIS-cybersource.com.au Sun Apr 4 08:10:02 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 04 Apr 2010 12:10:02 GMT Subject: Is there a standard name for this tree structure? Message-ID: <4bb8819a$0$8827$c3e8da3@news.astraweb.com> I have a hierarchical structure something like a directory tree or a nested tree structure: Mammal +-- Ape : +-- Chimpanzee : +-- Gorilla : +-- Human +-- Carnivore : +-- Cat : +-- Tiger Reptile +-- Lizard +-- Snake +-- Cobra +-- Python This is a forest because each top-level element (Mammal, Reptile) is itself a tree. By adding a root to the (former) top-level elements, I turn it into a single tree. I can implement this tree using a flat dict: root = object() data = {root: ['Mammal', 'Reptile'], 'Mammal': ['Ape', 'Carnivore'], 'Ape': ['Chimpanzee', 'Gorilla', 'Human'], 'Reptile': ['Lizard', 'Snake'], # fill in the rest yourself... } Is there a particular name for this structure? I've been calling it a dict-based flattened tree, but I can't shake the feeling that there is another name for it... -- Steven From alfps at start.no Sun Apr 4 08:34:47 2010 From: alfps at start.no (Alf P. Steinbach) Date: Sun, 04 Apr 2010 14:34:47 +0200 Subject: Is there a standard name for this tree structure? In-Reply-To: <4bb8819a$0$8827$c3e8da3@news.astraweb.com> References: <4bb8819a$0$8827$c3e8da3@news.astraweb.com> Message-ID: * Steven D'Aprano: > I have a hierarchical structure something like a directory tree or a > nested tree structure: > > Mammal > +-- Ape > : +-- Chimpanzee > : +-- Gorilla > : +-- Human > +-- Carnivore > : +-- Cat > : +-- Tiger > Reptile > +-- Lizard > +-- Snake > +-- Cobra > +-- Python > > This is a forest because each top-level element (Mammal, Reptile) is > itself a tree. By adding a root to the (former) top-level elements, I > turn it into a single tree. > > I can implement this tree using a flat dict: > > root = object() > data = {root: ['Mammal', 'Reptile'], > 'Mammal': ['Ape', 'Carnivore'], > 'Ape': ['Chimpanzee', 'Gorilla', 'Human'], > 'Reptile': ['Lizard', 'Snake'], > # fill in the rest yourself... > } > > > Is there a particular name for this structure? I've been calling it a > dict-based flattened tree, but I can't shake the feeling that there is > another name for it... The only difference from an ordinary tree is that you have a provided a way to access non-root nodes (with strings as keys) that doesn't work for the root node. Still, all nodes can be accessed with objects as keys. So, you have just introduced some ambiguity that allows both views: it's a tree, and it's a forest, depending on what point of view one chooses. In passing, this terminology is the one used in programming and computer science. Donald Knuth notes that for e.g. a binary tree, if one (impractically) adopted the terminology of some authors on graph theory then one would have to say "topological bifurcating arborescence" instead of "binary tree"... Cheers & hth., - Alf From ethan at stoneleaf.us Sun Apr 4 08:50:01 2010 From: ethan at stoneleaf.us (Ethan Furman) Date: Sun, 04 Apr 2010 05:50:01 -0700 Subject: Incorrect scope of list comprehension variables In-Reply-To: References: <87hbnsg75j.fsf@dpt-info.u-strasbg.fr> <917gr5hbv4un4367r9ld635dlgiliqb593@4ax.com> Message-ID: <4BB88AF9.30505@stoneleaf.us> Steve Howell wrote: > On Apr 3, 9:58 pm, Tim Roberts wrote: > >>Alain Ketterlin wrote: >> >> >>>I've just spent a few hours debugging code similar to this: >> >>>d = dict() >>>for r in [1,2,3]: >>> d[r] = [r for r in [4,5,6]] >>>print d >> >>Yes, this has been fixed in later revisions, but I'm curious to know what >>led you to believe that a list comprehension created a new scope. I don't >>that was ever promised. > > > Common sense about how programming languages should work? As > confirmed by later revisions? Common sense? About *somebody else's* idea of how a programming language should work? Please. Experiment and read the manual. ~Ethan~ From alfps at start.no Sun Apr 4 09:06:46 2010 From: alfps at start.no (Alf P. Steinbach) Date: Sun, 04 Apr 2010 15:06:46 +0200 Subject: Incorrect scope of list comprehension variables In-Reply-To: References: <87hbnsg75j.fsf@dpt-info.u-strasbg.fr> <917gr5hbv4un4367r9ld635dlgiliqb593@4ax.com> Message-ID: * Ethan Furman: > Steve Howell wrote: >> On Apr 3, 9:58 pm, Tim Roberts wrote: >> >>> Alain Ketterlin wrote: >>> >>> >>>> I've just spent a few hours debugging code similar to this: >>> >>>> d = dict() >>>> for r in [1,2,3]: >>>> d[r] = [r for r in [4,5,6]] >>>> print d >>> >>> Yes, this has been fixed in later revisions, but I'm curious to know >>> what >>> led you to believe that a list comprehension created a new scope. I >>> don't >>> that was ever promised. >> >> >> Common sense about how programming languages should work? As >> confirmed by later revisions? > > Common sense? About *somebody else's* idea of how a programming > language should work? Common sense is about practical solutions. Since there is no practical gain from a list comprehension affecting the bindings of outside variables, and there correspondingly is a practical pay-off from list comprehensions not affecting the bindings of outside variables, common sense is to expect the latter. It's in the nature of common sense that those who possess this ability often tend to make the same tentative assumptions when presented with the same problem. It doesn't mean that they're consulting each other, like your "somebody else's": it just means that they're applying similar common sense reasoning. So, there's no great conspiracy. > Please. Experiment and read the manual. Common sense is applied first, as a heuristic. You really wouldn't want to drill down into the architect's drawings in order to get office 215 in a building. First you apply common sense. Cheers & hth., - Alf From bblais at bryant.edu Sun Apr 4 09:22:37 2010 From: bblais at bryant.edu (Brian Blais) Date: Sun, 04 Apr 2010 09:22:37 -0400 Subject: Incorrect scope of list comprehension variables In-Reply-To: <2010040400174371179-aptshansen@gmailinvalid> References: <87hbnsg75j.fsf@dpt-info.u-strasbg.fr> <917gr5hbv4un4367r9ld635dlgiliqb593@4ax.com> <2010040400174371179-aptshansen@gmailinvalid> Message-ID: On Apr 4, 2010, at 3:17 , Stephen Hansen wrote: > Where exactly does this common sense come from? A list > comprehension is > basically syntactic sugar over a for loop, and... well, since I've been bitten by this particular wart, I was surprised to see that the list comp didn't have it's own scope. If it's syntactic sugar for a for-loop, I figured that rather than converting d = dict() for r in [1,2,3]: d[r] = [r for r in [4,5,6]] to d = dict() for r in [1,2,3]: L=[] for r in [4,5,6]: L.append(r) d[r] = L it would convert it to something like: d = dict() for r in [1,2,3]: L=[] for _r in [4,5,6]: L.append(_r) d[r] = L still a for-loop, but without the surprising side-effect. I'm glad they fixed this one! surely, once you know, it's easy to overcome. as a curiosity, I just went and skimmed the section: http://docs.python.org/tutorial/datastructures.html which describes list comps, and didn't see any mention of this behavior. it's probably there, but it certainly doesn't jump out. bb -- Brian Blais bblais at bryant.edu http://web.bryant.edu/~bblais http://bblais.blogspot.com/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From darcy at druid.net Sun Apr 4 09:43:51 2010 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Sun, 4 Apr 2010 09:43:51 -0400 Subject: Incorrect scope of list comprehension variables In-Reply-To: References: <87hbnsg75j.fsf@dpt-info.u-strasbg.fr> <917gr5hbv4un4367r9ld635dlgiliqb593@4ax.com> Message-ID: <20100404094351.6f5f3d2d.darcy@druid.net> On Sun, 04 Apr 2010 15:06:46 +0200 "Alf P. Steinbach" wrote: > Common sense is applied first, as a heuristic. You really wouldn't want to drill > down into the architect's drawings in order to get office 215 in a building. > First you apply common sense. Oh goodie, bad analogies. Can I play too? Getting to office 215 is not analogous to writing a program. It is analogous to using the program. Writing the program is like building the office tower. You need to know about the tools and materials that you are working with. You don't use "common sense" to decide what materials to use. You study the literature and the specs. -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From duncan.booth at invalid.invalid Sun Apr 4 10:06:56 2010 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 4 Apr 2010 14:06:56 GMT Subject: Is there a standard name for this tree structure? References: <4bb8819a$0$8827$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano wrote: > I have a hierarchical structure something like a directory tree or a > nested tree structure: > > Mammal > +-- Ape >: +-- Chimpanzee >: +-- Gorilla >: +-- Human > +-- Carnivore >: +-- Cat >: +-- Tiger > Reptile > +-- Lizard > +-- Snake > +-- Cobra > +-- Python > ...snip... > Is there a particular name for this structure? I've been calling it a > dict-based flattened tree, but I can't shake the feeling that there is > another name for it... > Do you have any carniverous apes? If so it's a directed acyclic graph. From rantingrick at gmail.com Sun Apr 4 11:00:41 2010 From: rantingrick at gmail.com (rantingrick) Date: Sun, 4 Apr 2010 08:00:41 -0700 (PDT) Subject: off topic but please forgive me me and answer References: <4bb505c5$0$1133$4fafbaef@reader3.news.tin.it> Message-ID: On Apr 1, 3:44?pm, superpollo wrote: > how much is one half times one half? This is amazing, how can such an off topic post based completely on lunacy exist so long here? 54 posts and counting. I think i had this very argument in grade school. We have SD'A, Tim Chase, MSRB, and yes even Steve Holden again participating in the troll fest (even though some of their arguments are true). Of course i would expect mensenator to jump into this, but... A while back i had wondered why Guido never posts to c.l.py anymore. Was it because he thinks himself better than us, no, it's because of the "low-brow-infantile-Jerry-Springer-ish-nature" that this list has imploded into. *puke* From pmaupin at gmail.com Sun Apr 4 11:01:36 2010 From: pmaupin at gmail.com (Patrick Maupin) Date: Sun, 4 Apr 2010 08:01:36 -0700 (PDT) Subject: Splitting a string References: <450895af-d8ec-4312-a31e-569e39aaa319@w17g2000yqj.googlegroups.com> <737b6e81-71ef-430d-b5e7-dffdf1569fd7@g30g2000yqc.googlegroups.com> <4bb800c5$0$8827$c3e8da3@news.astraweb.com> Message-ID: <906f3248-9955-4712-960c-a6c7f77f8249@u31g2000yqb.googlegroups.com> On Apr 4, 4:58?am, Peter Otten <__pete... at web.de> wrote: > Personally, though, I prefer unit tests over assertions. IMO, the primary use cases for assertions and unit tests are not the same. When I have a well-defined, clearly understood specification that I am coding to and fully implementing with the aim of producing a fully general purpose solution that I are offering to others, unit tests are appropriate to make sure that the code matches the spec, and even to provide usage examples. When I am using Python in what I would call a more personal way, for example in an exploratory fashion to extract value from some large mass of data, or even to do something like parsing on a subset of another language, where I have no intention, desire, or time to implement the entire spec, assertions are perfectly appropriate to make sure that my code complains at a convenient point about input data that it would not handle properly. It is often the case that a more personal project will grow up and become more general purpose and widely used. At this point, it is appropriate to remove assertions, add unit tests, etc., but to complain about not having unit tests in the first place is to avoid acknowledging that there may be a higher cost associated with unit tests than with assertions, especially with immature code that may be severely refactored several times before settling on the best solution. Regards, Pat From pmaupin at gmail.com Sun Apr 4 11:03:49 2010 From: pmaupin at gmail.com (Patrick Maupin) Date: Sun, 4 Apr 2010 08:03:49 -0700 (PDT) Subject: Splitting a string References: <450895af-d8ec-4312-a31e-569e39aaa319@w17g2000yqj.googlegroups.com> <737b6e81-71ef-430d-b5e7-dffdf1569fd7@g30g2000yqc.googlegroups.com> <4bb800c5$0$8827$c3e8da3@news.astraweb.com> <4f4b70c3-3fa0-4deb-836d-3df1a55d7b66@r1g2000yqj.googlegroups.com> <4bb8419d$0$8827$c3e8da3@news.astraweb.com> Message-ID: <69982c33-991a-4069-80cc-66f4d366e904@q23g2000yqd.googlegroups.com> On Apr 4, 2:37?am, Steven D'Aprano wrote: > In any case, the *right* test would be: > > a = 1 > assert a == 1 and a*5==5 and str(a)=='1' and [None,a,None][a] is a You're right. I was very tired when I wrote that, and forgot the last 3 assertions... From stefan_ml at behnel.de Sun Apr 4 11:18:21 2010 From: stefan_ml at behnel.de (Stefan Behnel) Date: Sun, 04 Apr 2010 17:18:21 +0200 Subject: Is there a standard name for this tree structure? In-Reply-To: <4bb8819a$0$8827$c3e8da3@news.astraweb.com> References: <4bb8819a$0$8827$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano, 04.04.2010 14:10: > I have a hierarchical structure something like a directory tree or a > nested tree structure: > > Mammal > +-- Ape > : +-- Chimpanzee > : +-- Gorilla > : +-- Human > +-- Carnivore > : +-- Cat > : +-- Tiger > Reptile > +-- Lizard > +-- Snake > +-- Cobra > +-- Python Maybe not quite what you asked for, but given the names in the example above I would call this an ontology. Stefan From utente at esempio.net Sun Apr 4 11:41:15 2010 From: utente at esempio.net (superpollo) Date: Sun, 04 Apr 2010 17:41:15 +0200 Subject: off topic but please forgive me me and answer In-Reply-To: References: <4bb505c5$0$1133$4fafbaef@reader3.news.tin.it> Message-ID: <4bb8b31c$0$1123$4fafbaef@reader3.news.tin.it> rantingrick ha scritto: > On Apr 1, 3:44 pm, superpollo wrote: >> how much is one half times one half? > > This is amazing, how can such an off topic post based completely on > lunacy exist so long here? 54 posts and counting. I think i had this > very argument in grade school. We have SD'A, Tim Chase, MSRB, and yes > even Steve Holden again participating in the troll fest (even though > some of their arguments are true). Of course i would expect mensenator > to jump into this, but... > > A while back i had wondered why Guido never posts to c.l.py anymore. > Was it because he thinks himself better than us, no, it's because of > the "low-brow-infantile-Jerry-Springer-ish-nature" that this list has > imploded into. *puke* relax mate. From pmaupin at gmail.com Sun Apr 4 11:41:25 2010 From: pmaupin at gmail.com (Patrick Maupin) Date: Sun, 4 Apr 2010 08:41:25 -0700 (PDT) Subject: Is there a standard name for this tree structure? References: <4bb8819a$0$8827$c3e8da3@news.astraweb.com> Message-ID: On Apr 4, 9:06?am, Duncan Booth wrote: > Do you have any carniverous apes? If so it's a directed acyclic graph. Well, since he has a root node, he's really only described the *use* of this data structure implementation for a rooted tree. As you point out, the implementation itself is more general than a rooted tree, and could be used for any DAG. But you don't go far enough. This particular implementation could be used for any directed graph -- there is nothing (other than the problem domain) requiring that data in this dict be acyclic. In fact, there are sometimes good reasons for using this sort of structure for cyclic data. Having a name for each node, and always indirectly referring to the node by its name, can sometimes greatly simplify the implementation of problems requiring a cyclic graph (starting with the really basic problem of wanting to dump the whole structure out in a reasonable fashion for debugging). The primary differences between this structure and just haphazardly wiring up random objects into a directed graph are that (1) there may be some performance differences (but when the garbage collector has to figure out how to break cycles, these difference might or might not be in the direction you expect) and (2) with this structure, every object needs a globally unique name for indexing purposes. Having said all that, I don't know what the proper name for this data structure is, either :-) However, in determining the name, I would probably focus on the data structure being represented (in Steven's case, a tree), and the data structure used to represent it (a Python dict), and *why/how* the underlying structure is used. So I would probably call it something like an "associatively addressed tree". Regards, Pat From pmaupin at gmail.com Sun Apr 4 11:43:50 2010 From: pmaupin at gmail.com (Patrick Maupin) Date: Sun, 4 Apr 2010 08:43:50 -0700 (PDT) Subject: Is there a standard name for this tree structure? References: <4bb8819a$0$8827$c3e8da3@news.astraweb.com> Message-ID: <51fa366f-cb58-4fb1-94f5-5a8b07918756@v20g2000yqv.googlegroups.com> On Apr 4, 10:41?am, Patrick Maupin wrote: > The primary differences between this structure and just haphazardly > wiring up random objects into a directed graph are that (1) there may > be some performance differences (but when the garbage collector has to > figure out how to break cycles, these difference might or might not be > in the direction you expect) and (2) with this structure, every object > needs a globally unique name for indexing purposes. (Just wanted to point out that I realize there aren't any cycles in Steven's example data -- point (1) this paragraph was about the more general use of the dict structure for general directed graphs.) Pat From alfps at start.no Sun Apr 4 12:14:06 2010 From: alfps at start.no (Alf P. Steinbach) Date: Sun, 04 Apr 2010 18:14:06 +0200 Subject: In disGuiodoise? Message-ID: * ratingrick: > > A while back i had wondered why Guido never posts to c.l.py anymore. > Was it because he thinks himself better than us, no, it's because of > the "low-brow-infantile-Jerry-Springer-ish-nature" that this list has > imploded into. Perhaps Guido provides subtle guidance under some unrecognized nick? "He walks among you, and you don't recognize him" - Old jungle proverb Hm, interesting Google results for that phrase. Cheers, - Alf From pmaupin at gmail.com Sun Apr 4 12:58:55 2010 From: pmaupin at gmail.com (Patrick Maupin) Date: Sun, 4 Apr 2010 09:58:55 -0700 (PDT) Subject: off topic but please forgive me me and answer References: <4bb505c5$0$1133$4fafbaef@reader3.news.tin.it> Message-ID: <09a14e34-b2d5-4f55-9b4d-8b3af5f01c46@y14g2000yqm.googlegroups.com> On Apr 4, 10:00?am, rantingrick wrote: > This is amazing, how can such an off topic post based completely on > lunacy exist so long here? 54 posts and counting. I think i had this > very argument in grade school. We have SD'A, Tim Chase, MSRB, and yes > even Steve Holden again participating in the troll fest (even though > some of their arguments are true). Of course i would expect mensenator > to jump into this, but... Excellent technique. Pick a topic that is guaranteed in any universe to generate a lot of posts (a short provocative question asked on April Fool's Day), then stay above the fray, not posting until the traffic dies down, and only then make a post expressly engineered to try to start the traffic up again. Rinse and repeat as necessary. I bow at the feet of the master. From alfps at start.no Sun Apr 4 13:06:18 2010 From: alfps at start.no (Alf P. Steinbach) Date: Sun, 04 Apr 2010 19:06:18 +0200 Subject: In disGuiodoise? In-Reply-To: <7671d587-2d6c-4017-a2aa-b0350c6ac034@n34g2000yqb.googlegroups.com> References: <7671d587-2d6c-4017-a2aa-b0350c6ac034@n34g2000yqb.googlegroups.com> Message-ID: * Patrick Maupin: > On Apr 4, 11:14 am, "Alf P. Steinbach" wrote: >> "He walks among you, and you don't recognize him" - Old jungle proverb >> >> Hm, interesting Google results for that phrase. > > Interesting self-promotion :-) No, I'm not Guido. Cheers, - Alf From pmaupin at gmail.com Sun Apr 4 13:06:31 2010 From: pmaupin at gmail.com (Patrick Maupin) Date: Sun, 4 Apr 2010 10:06:31 -0700 (PDT) Subject: In disGuiodoise? References: Message-ID: <7671d587-2d6c-4017-a2aa-b0350c6ac034@n34g2000yqb.googlegroups.com> On Apr 4, 11:14?am, "Alf P. Steinbach" wrote: > "He walks among you, and you don't recognize him" - Old jungle proverb > > Hm, interesting Google results for that phrase. Interesting self-promotion :-) http://www.google.com/#q=%22He+walks+among+you,+and+you+don%27t+recognize+him%22&hl=en&safe=off&filter=0&fp=a2bb30ecf4f91972 From python at mrabarnett.plus.com Sun Apr 4 13:47:24 2010 From: python at mrabarnett.plus.com (MRAB) Date: Sun, 04 Apr 2010 18:47:24 +0100 Subject: In disGuiodoise? In-Reply-To: References: <7671d587-2d6c-4017-a2aa-b0350c6ac034@n34g2000yqb.googlegroups.com> Message-ID: <4BB8D0AC.5020905@mrabarnett.plus.com> Alf P. Steinbach wrote: > * Patrick Maupin: >> On Apr 4, 11:14 am, "Alf P. Steinbach" wrote: >>> "He walks among you, and you don't recognize him" - Old jungle proverb >>> >>> Hm, interesting Google results for that phrase. >> >> Interesting self-promotion :-) > > No, I'm not Guido. > That's exactly what the true Guido would say! :-) From lie.1296 at gmail.com Sun Apr 4 13:48:45 2010 From: lie.1296 at gmail.com (Lie Ryan) Date: Mon, 05 Apr 2010 03:48:45 +1000 Subject: off topic but please forgive me me and answer In-Reply-To: <88a6b4c3-e258-401e-8dff-e6a1e6855504@k17g2000yqb.googlegroups.com> References: <4bb505c5$0$1133$4fafbaef@reader3.news.tin.it> <20100402214110.00a63457@geekmail.INVALID> <4bb73c0b$0$1125$4fafbaef@reader3.news.tin.it> <08b9d5b5-5825-4d21-a68a-06a2d6183ee7@k19g2000yqn.googlegroups.com> <4bb7f85c$0$8827$c3e8da3@news.astraweb.com> <88a6b4c3-e258-401e-8dff-e6a1e6855504@k17g2000yqb.googlegroups.com> Message-ID: <4bb8d130$1@dnews.tpgi.com.au> On 04/04/10 13:01, Patrick Maupin wrote: > On Apr 3, 9:24 pm, Steven D'Aprano cybersource.com.au> wrote: >> To put it another way, even though there are an infinite number of >> rationals, they are vanishingly rare compared to the irrationals. If you >> could choose a random number from the real number line, it almost >> certainly would be irrational. > > Yet another correspondence between the set of numbers and the set of > people ;-) Not really. The set of all irrational numbers is not enumerable (aleph-1) and thus uncountable, but the set of all irrational people is a countable finite set (even though it may be very difficult to enumerate them). From emile at fenx.com Sun Apr 4 14:53:56 2010 From: emile at fenx.com (Emile van Sebille) Date: Sun, 04 Apr 2010 11:53:56 -0700 Subject: In disGuiodoise? In-Reply-To: References: Message-ID: On 4/4/2010 9:14 AM Alf P. Steinbach said... > * ratingrick: >> >> A while back i had wondered why Guido never posts to c.l.py anymore. As I recall, about the time of the 1.6/2.0 schism (2000?) the primary developers split off as python had grown to the point where there was enough new user support, and the traffic volume was seen as too much noise to get meaningful work done. Emile From nagle at animats.com Sun Apr 4 14:57:48 2010 From: nagle at animats.com (John Nagle) Date: Sun, 04 Apr 2010 11:57:48 -0700 Subject: C-style static variables in Python? In-Reply-To: References: Message-ID: <4bb8dc5a$0$1664$742ec2ed@news.sonic.net> kj wrote: > When coding C I have often found static local variables useful for > doing once-only run-time initializations. If you want functions with state, use an object. That's what they're for. Don't muck with the internal representation of functions. John Nagle From nagle at animats.com Sun Apr 4 14:59:40 2010 From: nagle at animats.com (John Nagle) Date: Sun, 04 Apr 2010 11:59:40 -0700 Subject: In disGuiodoise? In-Reply-To: References: Message-ID: <4bb8dccb$0$1664$742ec2ed@news.sonic.net> Alf P. Steinbach wrote: > * ratingrick: >> >> A while back i had wondered why Guido never posts to c.l.py anymore. >> Was it because he thinks himself better than us, no, it's because of >> the "low-brow-infantile-Jerry-Springer-ish-nature" that this list has >> imploded into. Maybe Google is making him do some real work. John Nagle From pmaupin at gmail.com Sun Apr 4 16:35:54 2010 From: pmaupin at gmail.com (Patrick Maupin) Date: Sun, 4 Apr 2010 13:35:54 -0700 (PDT) Subject: C-style static variables in Python? References: <4bb8dc5a$0$1664$742ec2ed@news.sonic.net> Message-ID: On Apr 4, 1:57?pm, John Nagle wrote: > ? ? If you want functions with state, use an object. That's what they're > for. ?Don't muck with the internal representation of functions. > While "Don't muck with the internal representation of functions" is excellent advice over 99% of the time, it is also true that it is often possible, sometimes even encouraged, to have "functions with state." This is done without "mucking" and without explicitly declaring a class or a class instance. See, e.g. closures and generator functions. Regards, Pat From no.email at nospam.invalid Sun Apr 4 17:50:54 2010 From: no.email at nospam.invalid (Paul Rubin) Date: Sun, 04 Apr 2010 14:50:54 -0700 Subject: Incorrect scope of list comprehension variables References: <87hbnsg75j.fsf@dpt-info.u-strasbg.fr> Message-ID: <7xpr2e28g1.fsf@ruckus.brouhaha.com> Alain Ketterlin writes: > d[r] = [r for r in [4,5,6]] > THe problem is that the "r" in d[r] somehow captures the value of the > "r" in the list comprehension, and somehow kills the loop interator. Yes, this is a well known design error in Python 2.x. The 3.x series fixes this error but introduces other errors of its own. It is evil enough that I almost always use this syntax instead: d[r] = list(r for r in [4,5,6]) that works in 3.x and the later releases of 2.x. In early 2.x (maybe up to 2.2) it throws an error at compile time rather than at run time. From robert.kern at gmail.com Sun Apr 4 18:03:02 2010 From: robert.kern at gmail.com (Robert Kern) Date: Sun, 04 Apr 2010 17:03:02 -0500 Subject: Encryption source code with md5 In-Reply-To: References: <91541c26-6f18-40c7-a0df-252a52bb7cd5@l25g2000yqd.googlegroups.com> <4baf3ac4$0$22903$e4fe514c@news.xs4all.nl> Message-ID: On 2010-04-03 20:21 , Lawrence D'Oliveiro wrote: > In message<4baf3ac4$0$22903$e4fe514c at news.xs4all.nl>, Irmen de Jong wrote: > >> On 28-3-2010 12:08, Lawrence D'Oliveiro wrote: >> >>> Don?t use MD5. >> >> Also, md5 is not an encryption algorithm at all, it is a secure hashing >> function. > > You can use hash functions for encryption. You can *build* an encryption algorithm out of hash functions as a primitive, yes. Paul Rubin's p3.py is an example of using SHA-1 to build an encryption algorithm: http://www.nightsong.com/phr/crypto/p3.py However, a hash function is not an encryption algorithm itself. One does not "encrypt with md5" as the OP asked. For crypto-knowledgeable people, this may just be an issue of terminology (although I think an important one), but I think it demonstrates the ignorance of the OP and the need for Irmen's clarification. -- 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 johngilbrough at gmail.com Sun Apr 4 18:12:10 2010 From: johngilbrough at gmail.com (johngilbrough) Date: Sun, 4 Apr 2010 15:12:10 -0700 (PDT) Subject: local variable referenced before assignment Message-ID: I cannot make sense of what's happening here ... I'm getting the following error: initializing last modified time /home/john/Dropbox/Projects/python/scripts/src 29 referencing last modified time /home/john/Dropbox/Projects/python/scripts/src 29 referencing last modified time Traceback (most recent call last): File "/home/john/Dropbox/Projects/python/scripts/src/file-watch.py", line 42, in time.sleep(10000) File "/home/john/Dropbox/Projects/python/scripts/src/file-watch.py", line 18, in handler if modifiedTime <> lastModifiedTime: UnboundLocalError: local variable 'lastModifiedTime' referenced before assignment >From this logic: #!/usr/bin/python def watchFile(filePath, callback): ### # calls callback whenever file is changed ### import fcntl import os import signal print "initializing last modified time" lastModifiedTime = os.path.getmtime(filePath) def handler(signum, frame): ## this gets called twice whenever a file changes print filePath + " " + str(signum) modifiedTime = os.path.getmtime(filePath) print "referencing last modified time" if modifiedTime <> lastModifiedTime: lastModifiedTime = modifiedTime callback() signal.signal(signal.SIGIO, handler) fd = os.open(filePath, os.O_RDONLY) fcntl.fcntl(fd, fcntl.F_SETSIG, 0) fcntl.fcntl(fd, fcntl.F_NOTIFY, 0 | fcntl.DN_MODIFY | fcntl.DN_CREATE | fcntl.DN_MULTISHOT # what's this? ) def doSomething (): print "in doSomething" import time filePath = "/home/john/Dropbox/Projects/python/scripts/src" watchFile (filePath, doSomething) while True: # needed to keep this alive - gets interrupted when a file changes time.sleep(10000) print "*", From alfps at start.no Sun Apr 4 18:22:48 2010 From: alfps at start.no (Alf P. Steinbach) Date: Mon, 05 Apr 2010 00:22:48 +0200 Subject: local variable referenced before assignment In-Reply-To: References: Message-ID: * johngilbrough: > I cannot make sense of what's happening here ... I'm getting the > following error: > > initializing last modified time > /home/john/Dropbox/Projects/python/scripts/src 29 > referencing last modified time > /home/john/Dropbox/Projects/python/scripts/src 29 > referencing last modified time > Traceback (most recent call last): > File "/home/john/Dropbox/Projects/python/scripts/src/file-watch.py", > line 42, in > time.sleep(10000) > File "/home/john/Dropbox/Projects/python/scripts/src/file-watch.py", > line 18, in handler > if modifiedTime <> lastModifiedTime: > UnboundLocalError: local variable 'lastModifiedTime' referenced before > assignment > > From this logic: > > #!/usr/bin/python > def watchFile(filePath, callback): > ### > # calls callback whenever file is changed > ### > import fcntl > import os > import signal > print "initializing last modified time" > lastModifiedTime = os.path.getmtime(filePath) > > def handler(signum, frame): > ## this gets called twice whenever a file changes > print filePath + " " + str(signum) > modifiedTime = os.path.getmtime(filePath) > print "referencing last modified time" > if modifiedTime <> lastModifiedTime: > lastModifiedTime = modifiedTime > callback() Since 'handler' has an assignment to 'lastModifiedTime' that name becomes the name of a local variable. It's not the execution of the assignment that creates the variable. It's the /presence/ of the assignment (this helps the compiler generate code that allocates all local variables on entry to the function). There are a couple of ways around. (1) At least in Py3 you can declare the variable as 'global', like this: global lastModifiedTime within the function. (2) Or, you can apply some indirection, which is nearly always a solution to any computer science and programming problem, and declare your variable like so: class Object: pass g = Object() g.lastModifiedTime = os.path.getmtime( filePath ) Then when you assign to 'g.lastModifiedTime' in 'handler' you're not creating a variable, because you're assigning to an attribute of an object. (3) Best is however to recognize that you have some state (your variable) and some operations on that state (your callback), and that that is what objects are all about. I.e. wrap your logic in a class. Then 'lastModifiedTime' becomes an instance attribute, and 'handler' becomes a method. It doesn't matter that there will only ever be one object (instance) of that class. Classes were meant for just this sort of thing, state + operations. Cheers & hth., - Alf From gagsl-py2 at yahoo.com.ar Sun Apr 4 18:23:07 2010 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 4 Apr 2010 15:23:07 -0700 (PDT) Subject: passing command line arguments to executable References: <4a636ae6-d68a-4b34-8e3f-9c11aa352793@g11g2000yqe.googlegroups.com> <5d3a56da-aab2-4715-b288-1c9de47c9ece@k13g2000yqe.googlegroups.com> <404ca155-866e-45d0-b496-a37e9fb9155a@10g2000yqq.googlegroups.com> Message-ID: <7b25775e-2de6-4c57-b50b-b3de55e3a6ca@g10g2000yqh.googlegroups.com> On 4 abr, 06:17, Francesco Bochicchio wrote: > On 3 Apr, 19:20, mcanjo wrote: > > On Apr 3, 11:15?am, Patrick Maupin wrote: > > > On Apr 3, 11:09?am, mcanjo wrote: > > > > > I have an executable (I don't have access to the source code) that > > > > processes some data. I double click on the icon and a Command prompt > > > > window pops up. The program asks me for the input file, I hit enter, > > > > and then it asks me for and output filename, I hit enter a second time ^^^^^^^^^^^^^^^^^^^^^^^^^ > > > > and it goes off and does its thing and when it is finished ... > > > > You need to look at the subprocess module, and use pipes. > > > I tried doing the following code: > > > from subprocess import Popen > > from subprocess import PIPE, STDOUT > > exefile = Popen('pmm.exe', stdout = PIPE, stdin = PIPE, stderr = > > STDOUT) > > exefile.communicate('MarchScreen.pmm\nMarchScreen.out')[0] > > > and the Command Prompt opened and closed, no exceptions were generated > > but the program didn't run. Am I doing something wrong? > > I would try a couple of things (never done what you are trying to do, > so my suggestions may be useless ): > 1. use shell=True as parameter of Popen > 2. capture the output of communicate method, which returns whatever > the process emits on standard output and standard error: there could > be some message that give you hints about the solution. To mcanjo: note that you didn't provide the second '\n' Also, are you sure the program does not accept command line arguments? Many do, and switch to interactive mode when no argument is provided. I'd try with -h /h --help /help -? /? -- Gabriel Genellina From apt.shansen at gmail.invalid Sun Apr 4 18:32:36 2010 From: apt.shansen at gmail.invalid (Stephen Hansen) Date: Sun, 4 Apr 2010 15:32:36 -0700 Subject: local variable referenced before assignment References: Message-ID: <2010040415323696894-aptshansen@gmailinvalid> On 2010-04-04 15:22:48 -0700, Alf P. Steinbach said: > * johngilbrough: >> I cannot make sense of what's happening here ... I'm getting the >> following error: > (1) > At least in Py3 you can declare the variable as 'global', like this: > > global lastModifiedTime > > within the function. Actually, what you're looking for in py3 is the "nonlocal" keyword, which addresses this precise situation. Using "global" would mark the variable as *global* -- top-level module namespace. nonlocal (within "handler") would make the assignment apply to the enclosing scope lastModifiedTime, instead. -- --S ... p.s: change the ".invalid" to ".com" in email address to reply privately. From alfps at start.no Sun Apr 4 18:35:25 2010 From: alfps at start.no (Alf P. Steinbach) Date: Mon, 05 Apr 2010 00:35:25 +0200 Subject: local variable referenced before assignment In-Reply-To: <2010040415323696894-aptshansen@gmailinvalid> References: <2010040415323696894-aptshansen@gmailinvalid> Message-ID: * Stephen Hansen: > On 2010-04-04 15:22:48 -0700, Alf P. Steinbach said: > >> * johngilbrough: >>> I cannot make sense of what's happening here ... I'm getting the >>> following error: >> (1) >> At least in Py3 you can declare the variable as 'global', like this: >> >> global lastModifiedTime >> >> within the function. > > Actually, what you're looking for in py3 is the "nonlocal" keyword, > which addresses this precise situation. Using "global" would mark the > variable as *global* -- top-level module namespace. Thanks, I didn't see that. I thought it was a global. > nonlocal (within "handler") would make the assignment apply to the > enclosing scope lastModifiedTime, instead. Cheers, - Alf From debatem1 at gmail.com Sun Apr 4 18:44:48 2010 From: debatem1 at gmail.com (geremy condra) Date: Sun, 4 Apr 2010 18:44:48 -0400 Subject: Encryption source code with md5 In-Reply-To: References: <91541c26-6f18-40c7-a0df-252a52bb7cd5@l25g2000yqd.googlegroups.com> <4baf3ac4$0$22903$e4fe514c@news.xs4all.nl> Message-ID: On Sun, Apr 4, 2010 at 6:03 PM, Robert Kern wrote: > On 2010-04-03 20:21 , Lawrence D'Oliveiro wrote: >> >> In message<4baf3ac4$0$22903$e4fe514c at news.xs4all.nl>, Irmen de Jong wrote: >> >>> On 28-3-2010 12:08, Lawrence D'Oliveiro wrote: >>> >>>> Don?t use MD5. >>> >>> Also, md5 is not an encryption algorithm at all, it is a secure hashing >>> function. >> >> You can use hash functions for encryption. > > You can *build* an encryption algorithm out of hash functions as a > primitive, yes. Paul Rubin's p3.py is an example of using SHA-1 to build an > encryption algorithm: > > ?http://www.nightsong.com/phr/crypto/p3.py > > However, a hash function is not an encryption algorithm itself. One does not > "encrypt with md5" as the OP asked. For crypto-knowledgeable people, this > may just be an issue of terminology (although I think an important one), but > I think it demonstrates the ignorance of the OP and the need for Irmen's > clarification. > > -- > Robert Kern I don't mean to disrespect Paul Rubin, but p3.py comes up in every discussion of cryptography in python on this list and, AFAICT, has yet to come under significant cryptanalytic scrutiny. That doesn't make it a bad example in this case, but I would caution the OP that it probably doesn't make it a good candidate for your encryption needs. Geremy Condra From iurisilvio at gmail.com Sun Apr 4 18:48:39 2010 From: iurisilvio at gmail.com (Iuri) Date: Sun, 4 Apr 2010 19:48:39 -0300 Subject: def method with variable no of parameters file.writeStuff(n, a1, a2, ...an) In-Reply-To: References: Message-ID: What you need is var-args: def func(*args): for arg in args: print arg func(1,2,3,4) On Fri, Apr 2, 2010 at 8:25 AM, vlad_fig wrote: > Hello all, > > I would like some help with setting up a method that would allow me to > change its number of parameters. For example: > > #--------------------- > class createfile(object): > > def __init__(self, > modelName = None, > someLines = None): > > self.modelName = modelName > > if someLines is None: > self.someLines = [] > else: > self.someLines = someLines > > def writeStuff(self, > numberParameters = None, > Parameter1 = None,... ??? ) > self.someLines .append("yes, we can %s" % self.Parameter1) > #--------------------- > file = createfile('file') > > file.writeStuff(2,a1,a2) > file.writeStuff(3,a1,a2,a3) > .... > file.writeStuff(n,a1,a2,...an) > > --- > so i want a method i can call based on the number of parameters n , and > that allows me to add these extra parameters based on n > > Thank you, > Vicnic > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From rt8396 at gmail.com Sun Apr 4 19:05:37 2010 From: rt8396 at gmail.com (r) Date: Sun, 4 Apr 2010 16:05:37 -0700 (PDT) Subject: In disGuiodoise? References: Message-ID: <230a2742-70f5-48ae-b8f2-dfa52f0f5cdd@z3g2000yqz.googlegroups.com> On Apr 4, 11:14?am, "Alf P. Steinbach" wrote: > > Perhaps Guido provides subtle guidance under some unrecognized nick? > "He walks among you, and you don't recognize him" - Old jungle proverb Ah yes i have often wondered who could it be? I have a few good suspects who could be Guido's sock-puppets. Although i don't know Guido's personality enough to pick him out of the crowd. If it were you i would be happy! Some of the other suspects are quite annoying, but their knowledge level and self righteousness seem to be so overwhelming. So finding out that they are Guido would be a disappointment. But again i don't know Guido so it would be hard for me to say...? """ The White Wizard is cunning. He walks here and there they say, as an old man, hooded and cloaked... And everywhere his spies slip past our nets!""" However i have also considered that maybe *all* the "well knowns" are in fact the many colorful personalities of Guido. * When he's in the mood for fire breathing debate and cunning undermining he fires up the SD'A account. * When he's feeling vindictive he drops one-line poop bombs from Alex23. * if someone announces a new module without documenting it he fires off troll feeds from mensenator. * When he's feeling nice he uses Chris Rebert. * If he feeling like spreading propaganda he fires up the George Sakkis or Bruno Desthuilliers. * If he wants to feel stately he masquerades as Steve Holden (although lately we've seen the grumpy side of this personality). * And last but not least when he feels like trolling on a grandiose scale he posts to c.l.lisp, c.p.ruby, and c.l.python, and five other sites as xah lee. Heck i may be the only non-Guido "regular" here! ;-) PS: Sorry if i left anyone out. From gatoygata2 at gmail.com Sun Apr 4 19:17:43 2010 From: gatoygata2 at gmail.com (Joaquin Abian) Date: Sun, 4 Apr 2010 16:17:43 -0700 (PDT) Subject: def method with variable no of parameters file.writeStuff(n, a1, a2, ...an) References: Message-ID: On Apr 2, 1:25?pm, "vlad_fig" wrote: > Hello all, > > I would like some help with setting up a method that would allow me to change its number of parameters. For example: > > #--------------------- > class createfile(object): > > def __init__(self, > modelName = None, > someLines = None): > > self.modelName = modelName > > if someLines is None: > self.someLines = [] > else: > self.someLines = someLines > > def writeStuff(self, > numberParameters = None, > Parameter1 = None,... ??? ) > self.someLines .append("yes, we can %s" % self.Parameter1) > #--------------------- > file = createfile('file') > > file.writeStuff(2,a1,a2) > file.writeStuff(3,a1,a2,a3) > .... > file.writeStuff(n,a1,a2,...an) > > --- > so i want a method i can call based on the number of parameters n , and that allows me to add these extra parameters based on n > > Thank you, > Vicnic Maybe you are looking for *args: class Test(): def meth(self, *args): print args inst = Test() inst.meth(1,2,3,4,5,6,7) #prints (1,2,3,4,5,6,7) Cheers Joaquin From wuwei23 at gmail.com Sun Apr 4 19:19:39 2010 From: wuwei23 at gmail.com (alex23) Date: Sun, 4 Apr 2010 16:19:39 -0700 (PDT) Subject: def method with variable no of parameters file.writeStuff(n, a1, a2, ...an) References: Message-ID: <75f83b09-fc53-4b42-a514-f7defb62d72a@r1g2000yqb.googlegroups.com> "vlad_fig" wrote: > file.writeStuff(2,a1,a2) > file.writeStuff(3,a1,a2,a3) > .... > file.writeStuff(n,a1,a2,...an) > --- > so i want a method i can call based on the number of parameters > n , and that allows me to add these extra parameters based on n It's not necessary to have to specify the number of parameters, you can use Python's support for optional parameters[1] instead: def writeStuff(self, *args): self.someLines.append(args) args will be a list of the values passed into writeStuff. 1: http://docs.python.org/reference/expressions.html#calls From monkey at joemoney.net Sun Apr 4 19:46:24 2010 From: monkey at joemoney.net (monkeys paw) Date: Sun, 04 Apr 2010 19:46:24 -0400 Subject: reduce in loop Message-ID: Why does the following fail with the Traceback? def add(x,y): return x+y for rrr in range(1,20): reduce(add, range(1, r)) Traceback (most recent call last): File "", line 2, in TypeError: reduce() of empty sequence with no initial value From benjamin.kaplan at case.edu Sun Apr 4 19:55:29 2010 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Sun, 4 Apr 2010 19:55:29 -0400 Subject: reduce in loop In-Reply-To: References: Message-ID: On Sun, Apr 4, 2010 at 7:46 PM, monkeys paw wrote: > Why does the following fail with the Traceback? > > def add(x,y): return x+y > for rrr in range(1,20): > ? ? ? ?reduce(add, range(1, r)) > > Traceback (most recent call last): > ?File "", line 2, in > TypeError: reduce() of empty sequence with no initial value > -- >>> for x in range(1,1) : ... print x ... >>> ranges start at the first value and go up to, but not including, the second value. So range(1,1) gives you no values. reduce doesn't know what to do with an empty sequence, so it throws an error. > http://mail.python.org/mailman/listinfo/python-list > From steve at REMOVE-THIS-cybersource.com.au Sun Apr 4 19:57:00 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 04 Apr 2010 23:57:00 GMT Subject: Irony overload [was Re: off topic but please forgive me me and answer] References: <4bb505c5$0$1133$4fafbaef@reader3.news.tin.it> Message-ID: <4bb9274b$0$8827$c3e8da3@news.astraweb.com> On Sun, 04 Apr 2010 08:00:41 -0700, rantingrick wrote: > A while back i had wondered why Guido never posts to c.l.py anymore. Was > it because he thinks himself better than us, no, it's because of the > "low-brow-infantile-Jerry-Springer-ish-nature" that this list has > imploded into. *puke* Complaining about the infantile nature of the list immediately before throwing up. Methinks "rantingrick" is projecting just a little. -- Steven From steve at REMOVE-THIS-cybersource.com.au Sun Apr 4 19:58:26 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 04 Apr 2010 23:58:26 GMT Subject: In disGuiodoise? References: <7671d587-2d6c-4017-a2aa-b0350c6ac034@n34g2000yqb.googlegroups.com> Message-ID: <4bb927a2$0$8827$c3e8da3@news.astraweb.com> On Sun, 04 Apr 2010 19:06:18 +0200, Alf P. Steinbach wrote: > * Patrick Maupin: >> On Apr 4, 11:14 am, "Alf P. Steinbach" wrote: >>> "He walks among you, and you don't recognize him" - Old jungle proverb >>> >>> Hm, interesting Google results for that phrase. >> >> Interesting self-promotion :-) > > No, I'm not Guido. I AM SPARTACUS^W GUIDO! -- Steven From steve at REMOVE-THIS-cybersource.com.au Sun Apr 4 20:01:20 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 05 Apr 2010 00:01:20 GMT Subject: Incorrect scope of list comprehension variables References: <87hbnsg75j.fsf@dpt-info.u-strasbg.fr> <917gr5hbv4un4367r9ld635dlgiliqb593@4ax.com> Message-ID: <4bb92850$0$8827$c3e8da3@news.astraweb.com> On Sun, 04 Apr 2010 05:50:01 -0700, Ethan Furman wrote: >>>Yes, this has been fixed in later revisions, but I'm curious to know >>>what led you to believe that a list comprehension created a new scope. >>>I don't that was ever promised. >> >> >> Common sense about how programming languages should work? As confirmed >> by later revisions? > > Common sense? About *somebody else's* idea of how a programming > language should work? Nevertheless, it is a common intuition that the list comp variable should *not* be exposed outside of the list comp, and that the for-loop variable should. Perhaps it makes no sense, but it is very common -- I've never heard of anyone being surprised that the for-loop variable is exposed, but I've seen many people surprised by the fact that list-comps do expose their loop variable. -- Steven From steve at REMOVE-THIS-cybersource.com.au Sun Apr 4 20:01:34 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 05 Apr 2010 00:01:34 GMT Subject: Incorrect scope of list comprehension variables References: <87hbnsg75j.fsf@dpt-info.u-strasbg.fr> <7xpr2e28g1.fsf@ruckus.brouhaha.com> Message-ID: <4bb9285e$0$8827$c3e8da3@news.astraweb.com> On Sun, 04 Apr 2010 14:50:54 -0700, Paul Rubin wrote: > Alain Ketterlin writes: >> d[r] = [r for r in [4,5,6]] >> THe problem is that the "r" in d[r] somehow captures the value of the >> "r" in the list comprehension, and somehow kills the loop interator. > > Yes, this is a well known design error in Python 2.x. The 3.x series > fixes this error but introduces other errors of its own. Oh, do tell? -- Steven From tjreedy at udel.edu Sun Apr 4 20:02:47 2010 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 04 Apr 2010 20:02:47 -0400 Subject: reduce in loop In-Reply-To: References: Message-ID: On 4/4/2010 7:46 PM, monkeys paw wrote: > Why does the following fail with the Traceback? > > def add(x,y): return x+y > for rrr in range(1,20): I presume that this was 'for r...' > reduce(add, range(1, r)) and that this was indented. > Traceback (most recent call last): > File "", line 2, in > TypeError: reduce() of empty sequence with no initial value Just what it says. To debug this sort of this, try printing values just before the line that fails. When r is 1, range(1,1) = []. So either start r at 2 or add the third arg to reduce(add, range(1,r), 0). Terry Jan Reedy From greg.ewing at canterbury.ac.nz Sun Apr 4 20:08:31 2010 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Mon, 05 Apr 2010 12:08:31 +1200 Subject: (a==b) ? 'Yes' : 'No' In-Reply-To: <4bb6917c$0$8827$c3e8da3@news.astraweb.com> References: <4bb22b39$0$1638$742ec2ed@news.sonic.net> <4bb6917c$0$8827$c3e8da3@news.astraweb.com> Message-ID: <81snd6Fv07U1@mid.individual.net> Steven D'Aprano wrote: > Not according to the PEP. No fewer than 16 alternatives were put to a > vote, and with no clear winner (but many obvious losers) Guido made the > final decision. As I remember, the decision made on the basis of the vote was *not* to add a conditional expression at all, because of the fact that there was no clear winner. It was some time later that Guido suddenly announced out of the blue that he was accepting one of the choices that he had earlier said he didn't like! The ways of the BDFL are strange indeed. :-) -- Greg From steve at REMOVE-THIS-cybersource.com.au Sun Apr 4 20:19:12 2010 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 05 Apr 2010 00:19:12 GMT Subject: (a==b) ? 'Yes' : 'No' References: <4bb22b39$0$1638$742ec2ed@news.sonic.net> <4bb6917c$0$8827$c3e8da3@news.astraweb.com> <81snd6Fv07U1@mid.individual.net> Message-ID: <4bb92c7f$0$8827$c3e8da3@news.astraweb.com> On Mon, 05 Apr 2010 12:08:31 +1200, Gregory Ewing wrote: > Steven D'Aprano wrote: > >> Not according to the PEP. No fewer than 16 alternatives were put to a >> vote, and with no clear winner (but many obvious losers) Guido made the >> final decision. > > As I remember, the decision made on the basis of the vote was *not* to > add a conditional expression at all, because of the fact that there was > no clear winner. > > It was some time later that Guido suddenly announced out of the blue > that he was accepting one of the choices that he had earlier said he > didn't like! > > The ways of the BDFL are strange indeed. :-) I think what happened was the he got bitten by a subtle bug in the previous idiom for the ternary operator: condition and x or y will return (x if condition else y) *unless* x itself happens to be a false value. This demonstrated that the and/or idiom was not a suitable alternative to a short-circuiting ternary operator. -- Steven From apt.shansen at gmail.invalid Sun Apr 4 20:40:19 2010 From: apt.shansen at gmail.invalid (Stephen Hansen) Date: Sun, 4 Apr 2010 17:40:19 -0700 Subject: Incorrect scope of list comprehension variables References: <87hbnsg75j.fsf@dpt-info.u-strasbg.fr> <917gr5hbv4un4367r9ld635dlgiliqb593@4ax.com> <4bb92850$0$8827$c3e8da3@news.astraweb.com> Message-ID: <2010040417401964890-aptshansen@gmailinvalid> On 2010-04-04 17:01:20 -0700, Steven D'Aprano said: > On Sun, 04 Apr 2010 05:50:01 -0700, Ethan Furman wrote: > >>>> Yes, this has been fixed in later revisions, but I'm curious to know >>>> what led you to believe that a list comprehension created a new scope. >>>> I don't that was ever promised. >>> >>> >>> Common sense about how programming languages should work? As confirmed >>> by later revisions? >> >> Common sense? About *somebody else's* idea of how a programming >> language should work? > > Nevertheless, it is a common intuition that the list comp variable should > *not* be exposed outside of the list comp, and that the for-loop variable > should. Perhaps it makes no sense, but it is very common -- I've never > heard of anyone being surprised that the for-loop variable is exposed, > but I've seen many people surprised by the fact that list-comps do expose > their loop variable. IMHO, the real confusion-point of the situation wasn't so much list comps vs for loops, but that list comps did expose it, but gen comps didn't. If one thinks about how each would most likely be implemented they wouldn't be surprised, but I'm glad the behavior was harmonized in 3.x. That said, I can't quite imagine how anyone could really sit down and write code which would be broken by list comps "leaking". The example code in this thread is just nutty. Even if list comps did create a new scope, why in the world would you intentionally shadow an enclosing iteration variable? Obfuscation is not a good goal to go after :) -- --S ... p.s: change the ".invalid" to ".com" in email address to reply privately. From apt.shansen at gmail.invalid Sun Apr 4 20:42:08 2010 From: apt.shansen at gmail.invalid (Stephen Hansen) Date: Sun, 4 Apr 2010 17:42:08 -0700 Subject: Incorrect scope of list comprehension variables References: <87hbnsg75j.fsf@dpt-info.u-strasbg.fr> <7xpr2e28g1.fsf@ruckus.brouhaha.com> Message-ID: <2010040417420836130-aptshansen@gmailinvalid> On 2010-04-04 14:50:54 -0700, Paul Rubin said: > Alain Ketterlin writes: >> d[r] = [r for r in [4,5,6]] >> THe problem is that the "r" in d[r] somehow captures the value of the >> "r" in the list comprehension, and somehow kills the loop interator. > > Yes, this is a well known design error in Python 2.x. The 3.x series > fixes this error but introduces other errors of its own. It is evil > enough that I almost always use this syntax instead: > > d[r] = list(r for r in [4,5,6]) > > that works in 3.x and the later releases of 2.x. In early 2.x (maybe up > to 2.2) it throws an error at compile time rather than at run time. I have a dramatic suggestion. Why not use this syntax: d[r] = [something_else for something_else in [4,5,6]] Where something_else is basically any conceivable name in the whole wide world which does not have meaning in the current local scope. Just for clarity's sake, not sharing names is swell. -- --S ... p.s: change the ".invalid" to ".com" in email address to reply privately. From robert.kern at gmail.com Sun Apr 4 20:42:59 2010 From: robert.kern at gmail.com (Robert Kern) Date: Sun, 04 Apr 2010 19:42:59 -0500 Subject: Encryption source code with md5 In-Reply-To: References: <91541c26-6f18-40c7-a0df-252a52bb7cd5@l25g2000yqd.googlegroups.com> <4baf3ac4$0$22903$e4fe514c@news.xs4all.nl> Message-ID: On 2010-04-04 17:44 , geremy condra wrote: > On Sun, Apr 4, 2010 at 6:03 PM, Robert Kern wrote: >> On 2010-04-03 20:21 , Lawrence D'Oliveiro wrote: >>> >>> In message<4baf3ac4$0$22903$e4fe514c at news.xs4all.nl>, Irmen de Jong wrote: >>> >>>> On 28-3-2010 12:08, Lawrence D'Oliveiro wrote: >>>> >>>>> Don?t use MD5. >>>> >>>> Also, md5 is not an encryption algorithm at all, it is a secure hashing >>>> function. >>> >>> You can use hash functions for encryption. >> >> You can *build* an encryption algorithm out of hash functions as a >> primitive, yes. Paul Rubin's p3.py is an example of using SHA-1 to build an >> encryption algorithm: >> >> http://www.nightsong.com/phr/crypto/p3.py >> >> However, a hash function is not an encryption algorithm itself. One does not >> "encrypt with md5" as the OP asked. For crypto-knowledgeable people, this >> may just be an issue of terminology (although I think an important one), but >> I think it demonstrates the ignorance of the OP and the need for Irmen's >> clarification. >> >> -- >> Robert Kern > > I don't mean to disrespect Paul Rubin, but p3.py comes up in every discussion > of cryptography in python on this list and, AFAICT, has yet to come under > significant cryptanalytic scrutiny. That doesn't make it a bad example in this > case, but I would caution the OP that it probably doesn't make it a good > candidate for your encryption needs. For people looking for standardized cryptography, Google works fine to find PyCrypto or M2Crypto. p3 comes up so often in this group because people that need to ask here are looking for reasonably performant, pure-Python crypto, and p3 is the best-of-breed given those constraints (it happens to be mentioned here as an example, not a recommendation). Its security derives from its use of standardized, well-scrutinized components (and no, the recent attacks on SHA-1 do not affect the security properties that p3 relies on). It will probably never receive the kind of attention that AES or the rest get because it will never be fast enough to even be considered a peer of those algorithms. -- 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 czarniak at gmail.com Sun Apr 4 21:40:09 2010 From: czarniak at gmail.com (Wolfman) Date: Sun, 4 Apr 2010 18:40:09 -0700 (PDT) Subject: unset TCL_LIBRARY and TK_LIBRARY Message-ID: <28b3c894-7360-4523-96d7-9923d8861f48@v20g2000yqv.googlegroups.com> Hello- was hoping someone could give me a hand in permanently setting my TCL_LIBRARY and TK_LIBRARY. I downloaded Python2.6 to a ThinkPad that came installed with Python2.2, and I can not run IDLE as something automatically sets TCL_LIBRARY and TK_LIBRARY to C:\IBMTools\Python22\ each time i open a new command line window or reboot the machine. i have set them to the appropriate Python26 sub-directory via command line and IDLE opens just fine and dandy, but as soon as I close the command window or reboot computer it sets them back to the aforementioned C:\IBMTools\Python22 subdirectory how can i permanently SET TCL_LIBRARY and TK_LIBRARY? thanks From bantonj at gmail.com Sun Apr 4 21:47:01 2010 From: bantonj at gmail.com (Joshua) Date: Sun, 04 Apr 2010 21:47:01 -0400 Subject: passing command line arguments to executable In-Reply-To: <4a636ae6-d68a-4b34-8e3f-9c11aa352793@g11g2000yqe.googlegroups.com> References: <4a636ae6-d68a-4b34-8e3f-9c11aa352793@g11g2000yqe.googlegroups.com> Message-ID: <4bb94114$0$22520$607ed4bc@cv.net> On 4/3/10 12:09 PM, mcanjo wrote: > I have an executable (I don't have access to the source code) that > processes some data. I double click on the icon and a Command prompt > window pops up. The program asks me for the input file, I hit enter, > and then it asks me for and output filename, I hit enter a second time > and it goes off and does its thing and when it is finished running the > Command Prompt goes away and I have my new output file in the same > directory as my executable and input file. I would like to be able to > batch process a group of files. I thought about using "os.spawnv()" in > a loop and at each iteration of the loop passing in the file in and > out names but that didn't work. Does anyone have any ideas? I've done this a couple times on Windows. There are a few ways to do it, but I've found the easiest way is to use subprocess.check_call(). If you need to build the call with variables I find it cleaner to build the string before calling check_call(). Below is an example. callString = 'program.exe -x ' + variable returnMessage = subprocess.check_call(callString, shell=True) This works for programs that take arguments, I don't know how it will work with the program you have that asks for input in an interactive way. Does it accept arguments when you first run it? Not sure how to do it otherwise. -Josh B. From debatem1 at gmail.com Sun Apr 4 22:58:34 2010 From: debatem1 at gmail.com (geremy condra) Date: Sun, 4 Apr 2010 22:58:34 -0400 Subject: Encryption source code with md5 In-Reply-To: References: <91541c26-6f18-40c7-a0df-252a52bb7cd5@l25g2000yqd.googlegroups.com> <4baf3ac4$0$22903$e4fe514c@news.xs4all.nl> Message-ID: On Sun, Apr 4, 2010 at 8:42 PM, Robert Kern wrote: > On 2010-04-04 17:44 , geremy condra wrote: >> >> On Sun, Apr 4, 2010 at 6:03 PM, Robert Kern ?wrote: >>> >>> On 2010-04-03 20:21 , Lawrence D'Oliveiro wrote: >>>> >>>> In message<4baf3ac4$0$22903$e4fe514c at news.xs4all.nl>, Irmen de Jong >>>> wrote: >>>> >>>>> On 28-3-2010 12:08, Lawrence D'Oliveiro wrote: >>>>> >>>>>> Don?t use MD5. >>>>> >>>>> Also, md5 is not an encryption algorithm at all, it is a secure hashing >>>>> function. >>>> >>>> You can use hash functions for encryption. >>> >>> You can *build* an encryption algorithm out of hash functions as a >>> primitive, yes. Paul Rubin's p3.py is an example of using SHA-1 to build >>> an >>> encryption algorithm: >>> >>> ?http://www.nightsong.com/phr/crypto/p3.py >>> >>> However, a hash function is not an encryption algorithm itself. One does >>> not >>> "encrypt with md5" as the OP asked. For crypto-knowledgeable people, this >>> may just be an issue of terminology (although I think an important one), >>> but >>> I think it demonstrates the ignorance of the OP and the need for Irmen's >>> clarification. >>> >>> -- >>> Robert Kern >> >> I don't mean to disrespect Paul Rubin, but p3.py comes up in every >> discussion >> of cryptography in python on this list and, AFAICT, has yet to come under >> significant cryptanalytic scrutiny. That doesn't make it a bad example in >> this >> case, but I would caution the OP that it probably doesn't make it a good >> candidate for your encryption needs. > > For people looking for standardized cryptography, Google works fine to find > PyCrypto or M2Crypto. p3 comes up so often in this group because people that > need to ask here are looking for reasonably performant, pure-Python crypto, > and p3 is the best-of-breed given those constraints (it happens to be > mentioned here as an example, not a recommendation). Its security derives > from its use of standardized, well-scrutinized components (and no, the > recent attacks on SHA-1 do not affect the security properties that p3 relies > on). It will probably never receive the kind of attention that AES or the > rest get because it will never be fast enough to even be considered a peer > of those algorithms. > > -- > Robert Kern I have no comment on why it hasn't received substantial attention; my point is simply that it hasn't, and that without that scrutiny it probably isn't wise to depend on its security. There are plenty of tried-and-true cryptosystems to use; people without an extensive knowledge of what they're getting into should be encouraged to use them. Apologies if it sounded like I was claiming more. Geremy Condra From sanamsingh at hotmail.com Mon Apr 5 00:56:20 2010 From: sanamsingh at hotmail.com (sanam singh) Date: Mon, 5 Apr 2010 04:56:20 +0000 Subject: help req: installing debugging symbols Message-ID: Hi,I am using ununtu 9.10. I want to install a version of Python that was compiled with debug symbols.But if I delete python from ubuntu it would definitely stop working . And python comes preintalled in ubuntu without debugging symbols.How can i install python with debugging symbols ?Thanks.Regards,Sanam _________________________________________________________________ Hotmail: Trusted email with Microsoft?s powerful SPAM protection. https://signup.live.com/signup.aspx?id=60969 -------------- next part -------------- An HTML attachment was scrubbed... URL: From smcbutler at gmail.com Mon Apr 5 02:28:26 2010 From: smcbutler at gmail.com (Si) Date: Sun, 4 Apr 2010 23:28:26 -0700 (PDT) Subject: Python/Django linux build consultant required Message-ID: <1950bed6-9557-4bd2-b70b-786fdb89b386@g11g2000yqe.googlegroups.com> Hi, we are a San Francisco based startup company and are looking for a Python/Django person to help us roll out our recently completed. We're looking for 5 years + Python experience with a knowledge of tools such as pyinstall (or other build systems). Please contact me directly interested. Rgds. From hiralsmaillist at gmail.com Mon Apr 5 04:03:52 2010 From: hiralsmaillist at gmail.com (hiral) Date: Mon, 5 Apr 2010 01:03:52 -0700 (PDT) Subject: output from popen Message-ID: <3ac34608-2b1c-4424-b3ef-c8a6c73d240d@r27g2000yqn.googlegroups.com> Hi, I am trying following script...